[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 }
相關文章
相關標籤/搜索