forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Yi Gu
committed
Apr 24, 2016
1 parent
68146c6
commit 21886bd
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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(n) | ||
*/ | ||
|
||
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 | ||
} | ||
} |