原题说明
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input:
20
Output:1
Explanation: The only positive number(<= 20)with at least1repeated digit is11.
Example 2:
Input:
100
Output:10
Explanation: The positive numbers(<= 100)with atleast1repeated digit are11, 22, 33, 44, 55, 66, 77, 88, 99, and100.
Example 3:
Input:
1000
Output:262.
Note:
1 <= N <= 10^9
解题思路
题目要求求出比N小,同时至少存在一个重复数字的正整数的个数。运用brute force方法直接计算满足题目要求的数会有超时的问题,时间复杂度是O(N),不满足要求。更好的方法是先求出所有不满足要求的数的个数res,再用N减去res,反过来得出答案。
这里,不满足题目要求的数可以分为两类;
- 第一类是位数比
N小的数,同时数字各不相同 - 第二类是位数与
N相同的,比N小,同时数字各不相同。
这两类数就包含了所有不大于N,同时数字各不相同的数,而剩下的数就是至少包含一个相同数字,且不大于N的数。
同时,我们需要一个辅助函数helper,它的作用是用来求出m个不同数字组成长度是n位的数的个数。
第一类数的求解相对简单,最高位的可能是1~9一共9中可能,之后可以直接调用helper方便求解。
第二类数,需要分别对不同的相同前缀做分类计算。在确定相同前缀之后,再次调用helper可以求出对应的数的个数。
示例代码 (cpp)
1 | /* |
复杂度分析
时间复杂度: O(log N)
空间复杂度: O(log N)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!