码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字

时间:2016-11-04 23:06:21      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:put   call   style   pos   order   under   更新   ast   参考   

 

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.

 

s

 

class Solution {
public:
    int findKthNumber(int n, int k) {
        int cur = 1;
        --k;
        while (k > 0) {
            long long step = 0, first = cur, last = cur + 1;
            while (first <= n) {
                step += min((long long)n + 1, last) - first;
                first *= 10;
                last *= 10;
            }
            if (step <= k) {
                ++cur;
                k -= step;
            } else {
                cur *= 10;
                --k; 
            }
        }
        return cur;
    }
};

 

类似题目:

Lexicographical Numbers

 

参考资料:

https://discuss.leetcode.com/topic/64624/concise-easy-to-understand-java-5ms-solution-with-explaination/2

https://discuss.leetcode.com/topic/64462/c-python-0ms-o-log-n-2-time-o-1-space-super-easy-solution-with-detailed-explanations

 

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字

标签:put   call   style   pos   order   under   更新   ast   参考   

原文地址:http://www.cnblogs.com/grandyang/p/6031787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!