Leetcode 440. 字典序的第K小数字

文章目录

  • 题目
  • 代码(10.2 首刷看解析)

题目

Leetcode 440. 字典序的第K小数字_第1张图片
Leetcode 440. 字典序的第K小数字

代码(10.2 首刷看解析)

首刷用优先队列超时了

字典序

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

你可能感兴趣的:(Leetcode专栏,leetcode,算法,职场和发展)