Created
March 14, 2018 03:28
-
-
Save nleiva/386122b3774b4f368f388a9cc82bfa64 to your computer and use it in GitHub Desktop.
3Sum (15) from https://leetcode.com/problems/3sum/description/ ....too slow :-(
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
func threeSum(nums []int) [][]int { | |
result := [][]int{} | |
check := make(map[int]bool) | |
for i := 0; i < len(nums)-2; i++ { | |
if check[nums[i]] { | |
continue | |
} | |
for _, v := range twoSum(nums[i+1:], -nums[i]) { | |
if !(check[v[0]] || check[v[1]]) { | |
result = append(result, append(v, nums[i])) | |
} | |
} | |
check[nums[i]] = true | |
} | |
return result | |
} | |
func twoSum(nums []int, k int) [][]int { | |
result := [][]int{} | |
complement := make(map[int]int) | |
for i := 0; i < len(nums); i++ { | |
index, ok := complement[nums[i]] | |
if index == -1 { | |
continue | |
} | |
if ok { | |
result = append(result, []int{nums[i], nums[index]}) | |
complement[nums[i]] = -1 | |
complement[nums[index]] = -1 | |
} else { | |
complement[k-nums[i]] = i | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment