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