Note:

Basic idea could be same as Kth smallest number in sorted matrix.

But this could be different since all the numbers fall in [1, m*n + 1] range. But not all the numbers in the range belongs to the multiplication table.

So we need a helper function to calculate how many numbers from [1, mid]. It is counts += Math.min(value / i, n), since max value no larger than m.

class Solution {
    public int findKthNumber(int m, int n, int k) {
        int start = 1;
        int end = m * n + 1;
        while (start < end) {
            int mid = start + (end - start) / 2;
            int count = getCount(mid, m, n);
            if (count >= k) {
                end = mid;
            } else {
                start = mid + 1;
            }
        }
        return end;
    }
    
    private int getCount(int mid, int m, int n) {
        int count = 0;
        for (int i = 1; i <= m; i++) {
            count += Math.min(mid / i, n);
        }
        return count;
    }
}

 

posted on 2017-09-10 13:18  keepshuatishuati  阅读(637)  评论(0编辑  收藏  举报