leetcode 668. Kth Smallest Number in Multiplication Table 有序矩阵搜索

来源:互联网 发布:最小的c语言软件 编辑:程序博客网 时间:2024/06/06 15:54

Nearly every one have used the Multiplication Table. But could you find out the k-th smallest number quickly from the multiplication table?

Given the height m and the length n of a m * n Multiplication Table, and a positive integer k, you need to return the k-th smallest number in this table.

Example 1:
Input: m = 3, n = 3, k = 5
Output:
Explanation:
The Multiplication Table:
1 2 3
2 4 6
3 6 9

The 5-th smallest number is 3 (1, 2, 2, 3, 3).
Example 2:
Input: m = 2, n = 3, k = 6
Output:
Explanation:
The Multiplication Table:
1 2 3
2 4 6

The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).
Note:
The m and n will be in the range [1, 30000].
The k will be in the range [1, m * n]

本题题意就是在一个m*n的乘法表,然后要求找到第k小的数字

建议和leetcode 240. Search a 2D Matrix II 矩阵搜索 + 右上角搜索 和 leetcode 378. Kth Smallest Element in a Sorted Matrix一起学习

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public:    int findKthNumber(int m, int n, int k)     {        int left = 1 * 1, right = m*n;        while (left < right)        {            int mid = (right - left) / 2 + left;            int c = countLessThan(m, n, mid);            if (c < k)                left = mid+1;            else                right = mid;        }        return left;    }    int countLessThan(int m, int n, int target)    {        int count = 0 , i = m, j = 1;        while (i >= 1 && j <= n)        {            if(i*j <= target)            {                 count += i;                j++;            }            else                i--;        }        return count;    }};
阅读全文
0 0
原创粉丝点击