[Swift]LeetCode1012. 至少有 1 位重复的数字 | Numbers With 1 Repeated Digit

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-odnqadpg-md.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.git

Example 1:github

Input: 20
Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11. 

Example 2:微信

Input: 100
Output: 10 Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. 

Example 3:less

Input: 1000
Output: 262 

Note:spa

  1. 1 <= N <= 10^9

给定正整数 N,返回小于等于 N 且具备至少 1 位重复数字的正整数。 code

示例 1:htm

输入:20
输出:1
解释:具备至少 1 位重复数字的正数(<= 20)只有 11 。

示例 2:blog

输入:100
输出:10
解释:具备至少 1 位重复数字的正数(<= 100)有 11,22,33,44,55,66,77,88,99 和 100 。

示例 3:get

输入:1000
输出:262 

提示:

  1. 1 <= N <= 10^9

Runtime: 4 ms
Memory Usage: 19.1 MB
 1 class Solution {
 2     func numDupDigitsAtMostN(_ N: Int) -> Int {
 3         var L:[Int] = [Int]()
 4         var x:Int = N + 1
 5         while(x > 0)
 6         {
 7             L.insert(x % 10,at:0)           
 8             x /= 10
 9         }
10         var res:Int = 0
11         var n:Int = L.count
12         for i in 1..<n
13         {
14             res += 9 * A(9, i - 1)
15         }
16         var seen:Set<Int> = Set<Int>()
17         for i in 0..<n
18         {
19             var j:Int = i > 0 ? 0 : 1
20             while(j < L[i])
21             {
22                 if !seen.contains(j)
23                 {
24                     res += A(9 - i, n - i - 1)
25                 }
26                 j += 1
27             }
28             if seen.contains(L[i]) {break}
29             seen.insert(L[i])
30         }        
31         return N - res
32     }
33     
34     func A(_ m:Int,_ n:Int) -> Int
35     {
36         return n == 0 ? 1 : A(m, n - 1) * (m - n + 1)
37     }
38 }
相关文章
相关标签/搜索