Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created January 8, 2020 05:09
Show Gist options
  • Save spurscho/1c6142a6c08e8d763ee1f342bdc6f964 to your computer and use it in GitHub Desktop.
Save spurscho/1c6142a6c08e8d763ee1f342bdc6f964 to your computer and use it in GitHub Desktop.
15. 3Sum ( not understand )
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var nums = nums; nums.sort()
var result = [[Int]]()
guard nums.count >= 3 else {return result}
//i,l,r indices
for i in 0..<nums.count-2{
if(i > 0 && nums[i] == nums[i-1]) {continue}
var l=i+1, r=nums.count-1
var targetValue = nums[i]
while(l<r){
var leftValue = nums[l], rightValue = nums[r]
var sum = targetValue + leftValue + rightValue
if(sum == 0){result.append([targetValue, leftValue, rightValue])}
if(sum<0){
repeat {l += 1} while l<r && leftValue == nums[l]
}
else{
repeat {r -= 1} while l<r && rightValue == nums[r]
}
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment