leetcode 440. K-th Smallest in Lexicographical Order 第k个字典序的数字

来源:互联网 发布:外贸crm软件 编辑:程序博客网 时间:2024/06/07 23:16

Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.

Note: 1 ≤ k ≤ n ≤ 109.

Example:

Input:
n: 13 k: 2

Output:
10

Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.

其实和这一道题leetcode 386. Lexicographical Numbers 字典序的排列 是一样的,不过本题是求第k个字典序的数字是哪一个,就这么做吧

代码如下:

#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 <cmath>using namespace std;class Solution {public:    int findKthNumber(int n, int k)     {        vector<int> res(n, 0);        int cur = 1;        for (int i = 0; i < n; i++)        {            res[i] = cur;            if (cur * 10 <= n)                cur *= 10;            else            {                if (cur >= n)                    cur /= 10;                cur += 1;                while (cur % 10 == 0)                    cur /= 10;            }        }        return res[k-1];    }};
原创粉丝点击