diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index fd17af62..f12b5869 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -206,6 +206,23 @@ function twoSum(array $nums, int $target): array } ``` +Swift: +```swift +func twoSum(_ nums: [Int], _ target: Int) -> [Int] { + var res = [Int]() + var dict = [Int : Int]() + for i in 0 ..< nums.count { + let other = target - nums[i] + if dict.keys.contains(other) { + res.append(i) + res.append(dict[other]!) + return res + } + dict[nums[i]] = i + } + return res +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index b9386a68..e6365c71 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -191,7 +191,37 @@ var isHappy = function(n) { }; ``` - +Swift: +```swift +// number 每个位置上的数字的平方和 +func getSum(_ number: Int) -> Int { + var sum = 0 + var num = number + while num > 0 { + let temp = num % 10 + sum += (temp * temp) + num /= 10 + } + return sum +} +func isHappy(_ n: Int) -> Bool { + var set = Set() + var num = n + while true { + let sum = self.getSum(num) + if sum == 1 { + return true + } + // 如果这个sum曾经出现过,说明已经陷入了无限循环了 + if set.contains(sum) { + return false + } else { + set.insert(sum) + } + num = sum + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index f7d323aa..c0ca578e 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -268,6 +268,47 @@ func min(a,b int)int{ return a } ``` + +Swift: +```swift +func commonChars(_ words: [String]) -> [String] { + var res = [String]() + if words.count < 1 { + return res + } + let aUnicodeScalarValue = "a".unicodeScalars.first!.value + let lettersMaxCount = 26 + // 用于统计所有字符串每个字母出现的 最小 频率 + var hash = Array(repeating: 0, count: lettersMaxCount) + // 统计第一个字符串每个字母出现的次数 + for unicodeScalar in words.first!.unicodeScalars { + hash[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1 + } + // 统计除第一个字符串每个字母出现的次数 + for idx in 1 ..< words.count { + var hashOtherStr = Array(repeating: 0, count: lettersMaxCount) + for unicodeScalar in words[idx].unicodeScalars { + hashOtherStr[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1 + } + // 更新hash,保证hash里统计的字母为出现的最小频率 + for k in 0 ..< lettersMaxCount { + hash[k] = min(hash[k], hashOtherStr[k]) + } + } + // 将hash统计的字符次数,转成输出形式 + for i in 0 ..< lettersMaxCount { + while hash[i] != 0 { // 注意这里是while,多个重复的字符 + let currentUnicodeScalarValue: UInt32 = UInt32(i) + aUnicodeScalarValue + let currentUnicodeScalar: UnicodeScalar = UnicodeScalar(currentUnicodeScalarValue)! + let outputStr = String(currentUnicodeScalar) // UnicodeScalar -> String + res.append(outputStr) + hash[i] -= 1 + } + } + return res +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)