Skip to content

Commit

Permalink
[Array] add Solution to 3Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Apr 24, 2016
1 parent 68146c6 commit 21886bd
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Array/ThreeSum.swift
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
}
}

0 comments on commit 21886bd

Please sign in to comment.