iOS LeetCode ☞ 字典序的第K小数字

iOS LeetCode ☞ 字典序的第K小数字,第1张

给定整数 nk,返回 [1, n] 中字典序第 k 小的数字。

示例 1:

输入: n = 13, k = 2
输出: 10
解释: 字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10

示例 2:

输入: n = 1, k = 1
输出: 1

提示:

1 <= k <= n <= 109 解题思路

判断节点向右移动还是向下移动

代码
	// 440. 字典序的第K小数字
    func findKthNumber(_ n: Int, _ k: Int) -> Int {
        
        func stepCount(_ n: Int, _ node: Int) -> Int {
            var cur = node, next = node + 1, sum = 0
            while cur <= n {
                sum += min(n - cur + 1, next - cur)
                cur *= 10
                next *= 10
            }
            return sum
        }
        
        var cur = 1, needStep = k - 1
        
        while needStep > 0 {
            let tempStep = stepCount(n, cur)
            if tempStep > needStep {
                cur *= 10
                needStep -= 1
            } else {
                cur += 1
                needStep -= tempStep
            }
        }
        
        return cur
    }

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/993529.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存