按字典顺序排列的数字从1到N的第K个数字

问题描述 投票:4回答:1

给定整数N,找到从1到N的按字典顺序排序的数字数组中排名第k的第k个。

例:N = 12

按字典顺序排序的数字是:[1,10,11,12,2,3,4,5,6,7,8,9]

如果K = 4,程序应返回:12。

程序的复杂性应该是O(logN)。

生成该数组是为了解释而不是作为输入提供。生成数组和排序将占用Nlog(N)时间,从而打败了目的。

我最近在面试过程中遇到了这个问题。无法在给定的时间复杂度中找出解决方案,因此寻求帮助

谢谢!!

string algorithm sorting time-complexity
1个回答
2
投票

我们取N = 13000,K = 12031.当指定为最左边的每个数字从1到9得到:

                                      total
1 single digit number 9 * 1              9
10 two-digit numbers  9 * 10            99
100 three-digit numbers 9 * 100        999
1000 four-digit numbers 9 * 1000      9999
10000 five-digit numbers      --->  here we have to start examining

                                             Total
                                             ----
1 gets 13000 - 8 * (1 + 10 + 100 + 1000)  =  4112 of them
2 gets 1111                                  5223
3 gets 1111                                  6334
4 gets 1111                                  7445
5 gets 1111                                  8556
6 gets 1111                                  9667
7 gets 1111                                  10778
8 gets 1111                                  11889
9 gets 1111 ----> answer is somewhere here 

答:9xxx。现在是第二个数字。对于以一个或多个零结尾的每个数字,我们必须使用等效前缀计算所有较低的数字。

3 numbers with zero or nothing before 9000   11892
9 90 900

100 + 9 numbers with 90xx
9000 9001 9002.., but also 901 902..         12001

答:91xx。第三位数。

2 numbers with zero or nothing before 9100
91 910                                       12003

10 four-digit numbers with 0 as third digit
9100 9101 9102..                             12013

1 number with zero or nothing before 9110
911                                          12014

10 numbers with 1 as third digit
9110 9111 9112..                             12024

1 number with zero or nothing before 9120
912                                          12025

+ 6

答:9126

© www.soinside.com 2019 - 2024. All rights reserved.