Skip to content

Commit 7b37311

Browse files
committed
454. 4Sum II
1 parent 6ffb6fd commit 7b37311

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ Not only Leetcode solutions in Swift.
1414
* [217. Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
1515
* [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)
1616
* [259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller)
17+
* [454. 4Sum II](https://leetcode.com/problems/4sum-ii/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,3 +482,47 @@ extension Solution {
482482
let threeSumSmallerNums = [-2, 0, 1, 3]
483483
let threeSumSmallerTarget = 2
484484
Solution.threeSumSmaller(nums: threeSumSmallerNums, threeSumSmallerTarget)
485+
486+
/**
487+
* 454. 4Sum II
488+
* https://leetcode.com/problems/4sum-ii/
489+
*/
490+
491+
extension Solution {
492+
class func fourSumII(A: [Int]?, B: [Int]?, C: [Int]?, D: [Int]?) -> Int {
493+
494+
guard let a = A, a.count > 0, let b = B, b.count > 0, let c = C, c.count > 0, let d = D, d.count > 0 else {
495+
return 0
496+
}
497+
498+
let aCount = a.count, bCount = b.count, cCount = c.count, dCount = d.count
499+
var map = [Int: Int]()
500+
var result = 0
501+
502+
for i in 0..<aCount {
503+
for j in 0..<bCount {
504+
if (map[a[i] + b[j]] != nil) {
505+
map[a[i] + b[j]]! += 1
506+
} else {
507+
map[a[i] + b[j]] = 1
508+
}
509+
}
510+
}
511+
512+
for i in 0..<cCount {
513+
for j in 0..<dCount {
514+
let target = -(c[i] + d[j])
515+
if let count = map[target] {
516+
result += count
517+
}
518+
}
519+
}
520+
521+
return result
522+
}
523+
}
524+
525+
// usage
526+
527+
let A = [ 1, 2], B = [-2,-1], C = [-1, 2], D = [0, 2]
528+
Solution.fourSumII(A: A, B: B, C: C, D: D)

0 commit comments

Comments
 (0)