Merge pull request #695 from qxuewei/master

添加 1002. 查找常用字符 Swift版本
This commit is contained in:
程序员Carl
2021-09-02 08:50:37 +08:00
committed by GitHub
3 changed files with 89 additions and 1 deletions

View File

@@ -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)

View File

@@ -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<Int>()
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)

View File

@@ -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)