Skip to content

Commit b0095e5

Browse files
Merge pull request youngyangyang04#705 from qxuewei/master
添加 第454题.四数相加II Swift版本
2 parents 8631472 + ed1b1d2 commit b0095e5

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

problems/0383.赎金信.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,28 @@ var canConstruct = function(ransomNote, magazine) {
266266
};
267267
```
268268

269+
Swift:
270+
```swift
271+
func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
272+
var record = Array(repeating: 0, count: 26);
273+
let aUnicodeScalarValue = "a".unicodeScalars.first!.value
274+
for unicodeScalar in magazine.unicodeScalars {
275+
// 通过record 记录 magazine 里各个字符出现的次数
276+
let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue)
277+
record[idx] += 1
278+
}
279+
for unicodeScalar in ransomNote.unicodeScalars {
280+
// 遍历 ransomNote,在record里对应的字符个数做 -- 操作
281+
let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue)
282+
record[idx] -= 1
283+
// 如果小于零说明在magazine没有
284+
if record[idx] < 0 {
285+
return false
286+
}
287+
}
288+
return true
289+
}
290+
```
269291

270292

271293
-----------------------

problems/0454.四数相加II.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,8 +220,33 @@ var fourSumCount = function(nums1, nums2, nums3, nums4) {
220220
};
221221
```
222222

223-
224-
223+
Swift:
224+
```swift
225+
func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int {
226+
// key:a+b的数值,value:a+b数值出现的次数
227+
var map = [Int: Int]()
228+
// 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中
229+
for i in 0 ..< nums1.count {
230+
for j in 0 ..< nums2.count {
231+
let sum1 = nums1[i] + nums2[j]
232+
map[sum1] = (map[sum1] ?? 0) + 1
233+
}
234+
}
235+
// 统计a+b+c+d = 0 出现的次数
236+
var res = 0
237+
// 在遍历大num3和num4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。
238+
for i in 0 ..< nums3.count {
239+
for j in 0 ..< nums4.count {
240+
let sum2 = nums3[i] + nums4[j]
241+
let other = 0 - sum2
242+
if map.keys.contains(other) {
243+
res += map[other]!
244+
}
245+
}
246+
}
247+
return res
248+
}
249+
```
225250

226251
-----------------------
227252
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)