当前位置:网站首页>leetcode:440. The k-th smallest digit in dictionary order
leetcode:440. The k-th smallest digit in dictionary order
2022-04-21 23:27:00 【Oceanstar's study notes】
Title source
Title Description

title
Train of thought
class Solution {
/* * Calculation [1,n] Internal to cur Root ( start ) Number of nodes */
long getNodes(long prefix, long n){
//prefix Is prefix ,n Is the upper limit
long curr = prefix;
long next = prefix + 1; // Next prefix
long totalNodes = 0; // Count the number of qualified nodes
while (curr <= n){
// Of course, the current prefix cannot be greater than the upper limit
//totalNodes += (std::min(next, n + 1) - curr); // Subtract the starting point of the current prefix from the starting point of the next prefix
totalNodes += std::min(next - curr, n + 1 - curr);
curr *= 10; // Go down
next *= 10; // Go down
}
return totalNodes; // Return the child nodes under the current prefix .
}
public:
int findKthNumber(int n, int k) {
long cur = 1; // First traverse to 1 Big numbers at the beginning
--k; // because 1 Ergodic , therefore k--
while (k > 0){
int nodes = getNodes(cur, n); // To get to cur The child nodes at the beginning are qualified (<=n) number nodes
if(nodes <= k){
// if nodes<=k It means that this nodes All nodes haven't arrived yet k
cur++; // cur turn right
k -= nodes; // Offset nodes Nodes
} else{
// if nodes>k It means that nodes One node is enough
cur *= 10; // cur Go down
--k; // take cur Calculate into k
}
}
return (int)cur; // Last cur Will stay in the second k On a small number
}
};

Train of thought two
The question is leetcode:386. Dictionary order number Extension of , Let's print the array in dictionary order before , And this question allows us to quickly locate a certain position , Then we can't be the same as the previous question , One by one , You can't pass OJ, This is also the reason why the question is set as Hard Why . Then we have to find a way to locate quickly .
Look carefully at the array of dictionary order , We can find out , In fact, this is a 10 Fork tree , That is, the child node of each node can have , Such as digital 1 The child node of is 10 To 19, Numbers 10 The child nodes of can be 100 To 109, But because of n Size limit , It's not a full cross tree . By analyzing the examples given in the title, we can know , Numbers 1 The child nodes of are 4 individual (10,11,12,13), And the last number 2 To 9 No child nodes , So this problem actually becomes a problem of traversing a cross tree in advance , Then the difficulty becomes how to calculate the number of child nodes of each node , Such as digital 1 And number 2, We ask to start from... In dictionary traversal order 1 To 2 How many numbers to go through , Realize the 1 Add the number itself to step in . Then we expand the scope ten times , The scope becomes 10 To 20 Between , But because we have to consider n Size , First n by 13, So only 4 Child node , So we know from the numbers 1 Traverse to the number 2 To pass 5 A digital , Then let's see step Less than or equal to k, If it is , We cur Self increasing 1,k subtract step; If not , Indicate that the required number is in the child node , We are now cur multiply 10,k Self reduction 1, And so on , until k by 0 Launch cycle , here cur It's what you want :
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;
}
};
This is a dictionary tree

Every node has 10 Child node , And each child node will have 10 Child node ……. You can find , The whole dictionary order arrangement is the pre order traversal of the cross tree :1, 10, 100, 101, … 11, 110 …
According to the meaning of the topic , We need to find it in the k The number of bits , Find this row , There are three things you need to know :
- How to determine the number of all child nodes under a prefix
- If the first k The number is under the current prefix , How to continue to look for the child nodes below ?
- If the first k The number is not in the current prefix , That is, the current prefix is relatively small , How to expand the prefix , Increase the scope of the search .
Determines the number of all child nodes under the specified prefix
Now what we have to do is , Give a prefix , Returns the total number of child nodes below .
The train of thought is : Subtract the starting point of the current prefix from the starting point of the next prefix , Then it is the sum of the number of all child nodes under the current prefix .
long getCount(long prefix, long n){
//prefix Is prefix ,n Is the upper limit
long curr = prefix;
long next = prefix + 1; // Next prefix
long count = 0;
while (curr <= n){
// Of course, the current prefix cannot be greater than the upper limit
count += (next - curr); // Subtract the starting point of the current prefix from the starting point of the next prefix
curr *= 10;
next *= 10;
// If it's just prefix yes 1,next yes 2, So now they are 10 and 20
// 1 Add... To the children of the prefix 10 individual , Ten forked trees add a layer , It's two layers
// If now prefix yes 10,next yes 20, So now they are 100 and 200,
// 1 Add... To the children of the prefix 100 individual , The ten fork tree has added another layer , It's three layers
}
return count; // Return the child nodes under the current prefix .
}
The problem is , When next When the value of is greater than the upper limit , Then the cross tree with this prefix as the root node is not a full cross tree , You should go to the upper limit , There are no more child nodes behind , therefore count+=next−cur There are still some problems . Let's fix this problem :
count += (std::min(next, n + 1) - curr);
You may ask : Why ? How is n+1 , instead of n Well ? I didn't say that n Is that the upper limit ?
for instance , If now the upper bound n by 12, Work out to 1 Number of subsegments for prefix , First 1 Itself is a node , Next, let's count 10,11,12, Altogether 4 Child node .
If you use std::min(next, n + 1) - curr, At this time, there will be one less ,12 - 10 Add the root node , In the end, it's just 3 individual . So we must write n+1. namely :
long getCount(long prefix, long n){
//prefix Is prefix ,n Is the upper limit
long curr = prefix;
long next = prefix + 1; // Next prefix
long count = 0;
while (curr <= n){
// Of course, the current prefix cannot be greater than the upper limit
count += (std::min(next, n + 1) - curr); // Subtract the starting point of the current prefix from the starting point of the next prefix
curr *= 10;
next *= 10;
// If it's just prefix yes 1,next yes 2, So now they are 10 and 20
// 1 Add... To the children of the prefix 10 individual , Ten forked trees add a layer , It's two layers
// If now prefix yes 10,next yes 20, So now they are 100 and 200,
// 1 Add... To the children of the prefix 100 individual , The ten fork tree has added another layer , It's three layers
}
return count; // Return the child nodes under the current prefix .
}
The first k The number is under the current prefix
You need to look inside the subtree , That is to add a layer :
prefix *= 10
The first k The number is not under the current prefix
To put it bluntly , The current prefix is small , Let's expand the prefix .
prefix ++;
summary
class Solution {
/* * Calculation [1,n] Internal to cur Root ( start ) Number of nodes */
long getNodes(long prefix, long n){
//prefix Is prefix ,n Is the upper limit
long curr = prefix;
long next = prefix + 1; // Next prefix
long totalNodes = 0; // Count the number of qualified nodes
while (curr <= n){
// Of course, the current prefix cannot be greater than the upper limit
//totalNodes += (std::min(next, n + 1) - curr); // Subtract the starting point of the current prefix from the starting point of the next prefix
totalNodes += std::min(next - curr, n + 1 - curr);
curr *= 10; // Go down
next *= 10; // Go down
// If it's just prefix yes 1,next yes 2, So now they are 10 and 20
// 1 Add... To the children of the prefix 10 individual , Ten forked trees add a layer , It's two layers
// If now prefix yes 10,next yes 20, So now they are 100 and 200,
// 1 Add... To the children of the prefix 100 individual , The ten fork tree has added another layer , It's three layers
}
return totalNodes; // Return the child nodes under the current prefix .
}
public:
int findKthNumber(int n, int k) {
long curr = 1; // The first dictionary order is small ( Namely 1)
long prefix = 1;
while (curr < k){
// Prefix from 1 Start
long nodes = getNodes(prefix, n); // With prefix Root , With n The total number of elements of the maximum cross tree
if(curr + nodes > k) {
// The first k The number is under the current prefix
prefix *= 10; // Go down to the next level
curr++; // Point the pointer to the position of the first child node , such as 11 ride 10 Later into 110, Pointer from 11 Yes 110
}else {
// With prefix There is no second in a rooted cross tree k Elements
prefix++; // Expand the range
curr += nodes ;
}
}
return prefix;
}
};
版权声明
本文为[Oceanstar's study notes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204212324225297.html
边栏推荐
- 2022 electrician (elementary) examination simulated 100 questions and simulated examination
- Classified summary of series articles (second issue)
- golang力扣leetcode 2245.转角路径的乘积中最多能有几个尾随零
- MYSQL 为什么不要使用SELECT * 作为查询条件?(持续更新)
- Simple and easy to collect navigation website source code
- Basic concepts of audio and video and a simple introduction to ffmpeg
- [H.264] H.264 parsing tool, web parsing
- MySQL Chapter 3 basic SQL syntax
- How to set blind area in VOS
- File operation and IO
猜你喜欢

Buuctf question brushing record

从零开始自制实现WebServer(十六)---- 学习新工具CMake自动编写MakeFile 分门别类整理源文件心情愉悦

87 r K-means, hierarchical clustering, implementation of EM clustering

Red Star Macalline labor pains: "wield a knife" to reduce leverage and cut the net interest rate

BUUCTF 你(竟)然赶我走

How does the applet integrate instant messaging with instant messaging
技术、产品、品牌都不是问题,对上汽奥迪而言,这2点或生死攸关

【ACM】46. Full Permutation (1. Here, the previous elements need to be used for permutation, so StartIndex is not used (only for combination and division); 2. Pay attention to whether the elements in t

Mobile app Games / software / resource download station / software box source code

pytorch(五)——笔记
随机推荐
Pytorch (V) -- Notes
痞子衡嵌入式:聊聊系统看门狗WDOG1在i.MXRT1xxx系统启动中的应用及影响
通过点击导入的文件或点击组件进入对应的组件页面进行编辑
[H.264] H.264 parsing tool, web parsing
TextView 倾斜属性
C language topic 1: three digits that can be composed of 1,2,3,4
5、网络结构与ISP,分组延时、丢失、吞吐量
Developing Cami community system with ThinkPHP
341 Linux connection database
云原生架构下的微服务选型和演进
MySQL problem solving_ Multi table joint query_ The operator wants to calculate the average answer volume of users from different schools and different difficulties who participated in the answer. Ple
雲原生架構下的微服務選型和演進
MySQL Chapter 3 basic SQL syntax
Pytoch framework | torch nn. modules. Module(nn.Module)
Basic concepts of audio and video and a simple introduction to ffmpeg
红星美凯龙阵痛:“挥刀“降杠杆、净利率腰斩
Connexion personnalisée traitée avec succès
大厂面经合集,这些知识点你会吗
340 leetcode valid Letter ectopic words
Ruffian Heng embedded: talk about the application and influence of system watchdog wdog1 in the startup of i.mxrt1xxx system