Skip to content

Commit

Permalink
0454.四数相加II:简化Swift实现
Browse files Browse the repository at this point in the history
  • Loading branch information
bqlin committed Jan 8, 2022
1 parent 3078fb8 commit 6144420
Showing 1 changed file with 16 additions and 20 deletions.
36 changes: 16 additions & 20 deletions problems/0454.四数相加II.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ D = [ 0, 2]

1. 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
2. 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。
3. 定义int变量count,用来统计a+b+c+d = 0 出现的次数。
3. 定义int变量count,用来统计 a+b+c+d = 0 出现的次数。
4. 在遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
5. 最后返回统计值 count 就可以了

Expand Down Expand Up @@ -139,7 +139,7 @@ class Solution(object):
return count


```
```

Go:
```go
Expand Down Expand Up @@ -229,28 +229,24 @@ class Solution {
Swift:
```swift
func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int {
// key:a+b的数值,value:a+b数值出现的次数
var map = [Int: Int]()
// 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中
for i in 0 ..< nums1.count {
for j in 0 ..< nums2.count {
let sum1 = nums1[i] + nums2[j]
map[sum1] = (map[sum1] ?? 0) + 1
// ab和: ab和出现次数
var countDic = [Int: Int]()
for a in nums1 {
for b in nums2 {
let key = a + b
countDic[key] = countDic[key, default: 0] + 1
}
}
// 统计a+b+c+d = 0 出现的次数
var res = 0
// 在遍历大num3和num4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。
for i in 0 ..< nums3.count {
for j in 0 ..< nums4.count {
let sum2 = nums3[i] + nums4[j]
let other = 0 - sum2
if map.keys.contains(other) {
res += map[other]!
}

// 通过-(c + d)作为key,去累加ab和出现的次数
var result = 0
for c in nums3 {
for d in nums4 {
let key = -(c + d)
result += countDic[key, default: 0]
}
}
return res
return result
}
```

Expand Down

0 comments on commit 6144420

Please sign in to comment.