Блог пользователя 51stDimension

Автор 51stDimension, история, 3 года назад, По-английски

Quesion Link Leetcode: Leetode Question Link Codeforces Link

This problem has a binary search solution which goes like this:

class Solution {
    public boolean enough(int x, int m, int n, int k) {
        int count = 0;
        for (int i = 1; i <= m; i++) {
            count += Math.min(x / i, n);
        }
        return count >= k;
    }

    public int findKthNumber(int m, int n, int k) {
        int lo = 1, hi = m * n;
        while (lo < hi) {
            int mi = lo + (hi - lo) / 2;
            if (!enough(mi, m, n, k)) lo = mi + 1;
            else hi = mi;
        }
        return lo;
    }
}

The only doubt that I have is how come we are sure that this algorithm will give a answer which lies in multiplication table because not all numbers from [1:n*m] are present in the table. For example this is a table for n=5 and m=7 and has missing numbers like 11,22,23 etc. 1 2 3 4 5 6 7 2 4 6 8 10 12 14 3 6 9 12 15 18 21 4 8 12 16 20 24 28 5 10 15 20 25 30 35

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится +11 Проголосовать: не нравится

The algorithm finds the minimum integer $$$x$$$ such that there are at least $$$k$$$ numbers $$$\leq x$$$ in the multiplication table. The result $$$r$$$ must be in the list, because if it weren't, $$$r - 1$$$ would be smaller and still satisfy the second condition (since all numbers $$$\leq r$$$ in the list would also be $$$\leq r - 1$$$).