Skip to content

Commit 4d4acfc

Browse files
committed
15. three sum
1 parent 906292c commit 4d4acfc

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
Not only Leetcode solutions in Swift.
44

55
* [1.Two Sum](https://leetcode.com/problems/two-sum/)
6+
* [15. 3Sum](https://leetcode.com/problems/3sum/)
67
* [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
78
* [170. Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design)
89
* [Two Sum - Less than or equal to target](http://www.lintcode.com/en/problem/two-sum-less-than-or-equal-to-target/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,68 @@ let twoSumTarget = 9
3737

3838
Solution.twoSum(nums: twoSumNums, twoSumTarget)
3939

40+
/**
41+
* 15. 3Sum
42+
* https://leetcode.com/problems/3sum/
43+
*/
44+
45+
extension Solution {
46+
class func threeSum(nums: [Int]?) -> [[Int]]?{
47+
guard let nums = nums, nums.count > 2 else { return nil }
48+
49+
var results: [[Int]]?
50+
let sortedNums = nums.sorted()
51+
52+
for i in 0..<sortedNums.count - 2 {
53+
54+
if (i > 0 && sortedNums[i] == sortedNums[i-1]) {
55+
continue
56+
}
57+
58+
var left = i + 1
59+
var right = sortedNums.count - 1
60+
let target = -sortedNums[i]
61+
62+
while (left < right) {
63+
if (sortedNums[left] + sortedNums[right] == target) {
64+
65+
if (results != nil) {
66+
results!.append([-target, sortedNums[left], sortedNums[right]])
67+
68+
left += 1
69+
right -= 1
70+
71+
while (left < right && sortedNums[left] == sortedNums[left - 1]) {
72+
left += 1
73+
}
74+
75+
while (left < right && sortedNums[right] == sortedNums[right + 1]) {
76+
right -= 1
77+
}
78+
79+
} else {
80+
results = [[Int]]()
81+
}
82+
83+
84+
} else if (sortedNums[left] + sortedNums[right] < target) {
85+
left += 1
86+
} else {
87+
right -= 1
88+
}
89+
}
90+
91+
}
92+
93+
return results
94+
}
95+
96+
}
97+
98+
// usage
99+
100+
let threeSumNums = [-1, 0, 1, 2, -1, -4]
101+
Solution.threeSum(nums: threeSumNums)
40102
/**
41103
* 167. Two Sum II - Input array is sorted
42104
* https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

0 commit comments

Comments
 (0)