返回介绍

solution / 0400-0499 / 0440.K-th Smallest in Lexicographical Order / README_EN

发布于 2024-06-17 01:04:00 字数 3308 浏览 0 评论 0 收藏 0

440. K-th Smallest in Lexicographical Order

中文文档

Description

Given two integers n and k, return _the_ kth _lexicographically smallest integer in the range_ [1, n].

 

Example 1:

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.

Example 2:

Input: n = 1, k = 1
Output: 1

 

Constraints:

  • 1 <= k <= n <= 109

Solutions

Solution 1

class Solution:
  def findKthNumber(self, n: int, k: int) -> int:
    def count(curr):
      next, cnt = curr + 1, 0
      while curr <= n:
        cnt += min(n - curr + 1, next - curr)
        next, curr = next * 10, curr * 10
      return cnt

    curr = 1
    k -= 1
    while k:
      cnt = count(curr)
      if k >= cnt:
        k -= cnt
        curr += 1
      else:
        k -= 1
        curr *= 10
    return curr
class Solution {
  private int n;

  public int findKthNumber(int n, int k) {
    this.n = n;
    long curr = 1;
    --k;
    while (k > 0) {
      int cnt = count(curr);
      if (k >= cnt) {
        k -= cnt;
        ++curr;
      } else {
        --k;
        curr *= 10;
      }
    }
    return (int) curr;
  }

  public int count(long curr) {
    long next = curr + 1;
    long cnt = 0;
    while (curr <= n) {
      cnt += Math.min(n - curr + 1, next - curr);
      next *= 10;
      curr *= 10;
    }
    return (int) cnt;
  }
}
class Solution {
public:
  int n;

  int findKthNumber(int n, int k) {
    this->n = n;
    --k;
    long long curr = 1;
    while (k) {
      int cnt = count(curr);
      if (k >= cnt) {
        k -= cnt;
        ++curr;
      } else {
        --k;
        curr *= 10;
      }
    }
    return (int) curr;
  }

  int count(long long curr) {
    long long next = curr + 1;
    int cnt = 0;
    while (curr <= n) {
      cnt += min(n - curr + 1, next - curr);
      next *= 10;
      curr *= 10;
    }
    return cnt;
  }
};
func findKthNumber(n int, k int) int {
  count := func(curr int) int {
    next := curr + 1
    cnt := 0
    for curr <= n {
      cnt += min(n-curr+1, next-curr)
      next *= 10
      curr *= 10
    }
    return cnt
  }
  curr := 1
  k--
  for k > 0 {
    cnt := count(curr)
    if k >= cnt {
      k -= cnt
      curr++
    } else {
      k--
      curr *= 10
    }
  }
  return curr
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文