[leetcode-400] Kth smallest digit in lexicographic order

topic

Returns      the lexicographically     smallest number in the given integer sum   n  .  k[1, n]k

Example 1

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

复制代码

Example 2

输入: n = 1, k = 1
输出: 1
复制代码

hint

  • 1 <= k <= n <= 109

answer

What is the simpler the problem, the bigger the matter, this is; the problem is one sentence, and the problem is solved for a long time.

Preorder traversal of polytree


graph TD
root --> 1
root --> 2
root --> 3[...]
root --> 9
1 --> 10
1 --> 11
1 --> 12[...]
1 --> 19
10 --> 100
10 --> 101
10 --> 102[...]
10 --> 109

  • The lexicographic order from 1 to n can be regarded as the node of the above incomplete 9-ary tree;
  • The kth node traversed from the above 9-ary tree node in preorder is the kth smallest number in lexicographic order

The above pictures and texts have given the solution ideas, the following is to convert the ideas into code

  • Is it possible to directly build a 9-ary tree from 1 to n? Yes, yes, but the complexity is a bit high. You only need to find the kth tree but build a complete tree, which is not worth the loss.
  • The characteristics of the tree can be used to simulate preorder traversal and reduce the time complexity

How to simulate?

  • If there is a method getChildren now, you can get how many child nodes child there are under the current node.

    • For example, from 1 to 100, there are 12 nodes under 1.
  • Assume that the number of child nodes child is less than k

    • Saying that the current node contains all child nodes is not the answer. The answer is in other siblings of the current node.
    • k minus child; and find whether the number of child nodes is less than k-child at the sibling node of the current node
    • Repeat the above operation
  • If the number of child nodes child >= k

    • The answer must exist in the current node or a child node of the current node
    • Recursively find the relationship between the number of child nodes of child nodes and k-1
    • Repeat the above operation

    Edit the code according to the above ideas as follows:

    full code

var findKthNumber = function (n, k) {
  let count = 1;
  k--;
  while (k > 0) {
    const children = getChildren(count);
    if (children <= k) {
      k -= children;
      count++;
    } else {
      count = count * 10;
      k--;
    }
  }
  return count;
  function getChildren(c) {
    let child = 0;
    let left = c;
    let right = c;
    while (left <= n) {
      child += Math.min(right, n) - left + 1;
      left *= 10;
      right = right * 10 + 9;
    }
    return child;
  }
};
复制代码

Epilogue

The author's level is limited, if there are any shortcomings, please correct me; any comments and suggestions are welcome to browse and discuss in the comment area

Guess you like

Origin juejin.im/post/7078246470914146312