File tree 1 file changed +48
-0
lines changed
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(logn)
2
+ // Space: O(logn)
3
+
4
+ class Solution {
5
+ public:
6
+ int numDupDigitsAtMostN (int N) {
7
+ const auto & digits = to_string (N + 1 );
8
+ int result = 0 ;
9
+
10
+ // Given 321
11
+ //
12
+ // 1. count numbers without repeated digits:
13
+ // - X
14
+ // - XX
15
+ for (int i = 1 ; i < digits.length (); ++i) {
16
+ result += P (9 , 1 ) * P (9 , i - 1 );
17
+ }
18
+
19
+ // 2. count numbers without repeated digits:
20
+ // - 1XX ~ 3XX
21
+ // - 30X ~ 32X
22
+ // - 320 ~ 321
23
+ unordered_set<int > prefix_set;
24
+ for (int i = 0 ; i < digits.length (); ++i) {
25
+ for (int d = (i == 0 ) ? 1 : 0 ; d < digits[i] - ' 0' ; ++d) {
26
+ if (prefix_set.count (d)) {
27
+ continue ;
28
+ }
29
+ result += P (9 - i, digits.length () - i - 1 );
30
+ }
31
+ if (prefix_set.count (digits[i] - ' 0' )) {
32
+ break ;
33
+ }
34
+ prefix_set.emplace (digits[i] - ' 0' );
35
+ }
36
+ return N - result;
37
+ }
38
+
39
+ private:
40
+ int P (int m, int n) const {
41
+ int result = 1 ;
42
+ while (n > 0 ) {
43
+ result *= m - n + 1 ;
44
+ --n;
45
+ }
46
+ return result;
47
+ }
48
+ };
You can’t perform that action at this time.
0 commit comments