Skip to content

Commit 21886bd

Browse files
author
Yi Gu
committed
[Array] add Solution to 3Sum
1 parent 68146c6 commit 21886bd

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Array/ThreeSum.swift

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/3sum/
3+
* Primary idea: Sort the array, and traverse it, increment left or decrease right
4+
* predicated on their sum is greater or not than the target
5+
* Time Complexity: O(n^2), Space Complexity: O(n)
6+
*/
7+
8+
class ThreeSum {
9+
func threeSum(nums: [Int]) -> [[Int]] {
10+
var nums = nums.sort({$0 < $1})
11+
var res = [[Int]]()
12+
13+
if nums.count <= 2 {
14+
return res
15+
}
16+
17+
for i in 0...nums.count - 3 {
18+
if i == 0 || nums[i] != nums[i - 1] {
19+
var remain = -nums[i]
20+
var left = i + 1
21+
var right = nums.count - 1
22+
while left < right {
23+
if nums[left] + nums[right] == remain {
24+
var temp = [Int]()
25+
temp.append(nums[i])
26+
temp.append(nums[left])
27+
temp.append(nums[right])
28+
29+
res.append(temp)
30+
repeat {
31+
left += 1
32+
} while (left < right && nums[left] == nums[left - 1])
33+
repeat {
34+
right -= 1
35+
} while (left < right && nums[right] == nums[right + 1])
36+
} else if nums[left] + nums[right] < remain {
37+
repeat {
38+
left += 1
39+
} while (left < right && nums[left] == nums[left - 1])
40+
} else {
41+
repeat {
42+
right -= 1
43+
} while (left < right && nums[right] == nums[right + 1])
44+
}
45+
}
46+
}
47+
}
48+
49+
return res
50+
}
51+
}

0 commit comments

Comments
 (0)