From 2bc29faca461752a32608906fa3f28e97bbaabe2 Mon Sep 17 00:00:00 2001 From: preethamrn Date: Tue, 19 Oct 2021 19:59:11 -0700 Subject: [PATCH 1/2] Added Go solution for 15. 3Sum --- GO/three_sum.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 GO/three_sum.go diff --git a/GO/three_sum.go b/GO/three_sum.go new file mode 100644 index 00000000..73ebfd34 --- /dev/null +++ b/GO/three_sum.go @@ -0,0 +1,36 @@ +import ( + "fmt" + "sort" +) + +func threeSum(nums []int) [][]int { + sort.Slice(nums, func(i, j int) bool { + return nums[i] < nums[j] + }) + + var result [][]int + seen := map[string]bool{} + for i := 0; i < len(nums); i++ { + target := -nums[i] + l := i + 1 + r := len(nums) - 1 + for l < r { + val := nums[l] + nums[r] + if val < target { + l++ + } else if val > target { + r-- + } else if val == target { + resStr := fmt.Sprintf("%d,%d,%d", nums[i], nums[l], nums[r]) + if seen[resStr] { + l++ + continue + } + result = append(result, []int{nums[i], nums[l], nums[r]}) + seen[resStr] = true + l++ + } + } + } + return result +} \ No newline at end of file From ecc0b256230578ef89c54eeda0ce94bd1152cd70 Mon Sep 17 00:00:00 2001 From: preethamrn Date: Wed, 20 Oct 2021 20:22:03 -0700 Subject: [PATCH 2/2] Add main method --- GO/three_sum.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/GO/three_sum.go b/GO/three_sum.go index 73ebfd34..44ea8576 100644 --- a/GO/three_sum.go +++ b/GO/three_sum.go @@ -1,3 +1,5 @@ +package main + import ( "fmt" "sort" @@ -33,4 +35,8 @@ func threeSum(nums []int) [][]int { } } return result -} \ No newline at end of file +} + +func main() { + fmt.Println(threeSum([]int{-1, 0, 1, 2, -1, -4})) // output: [[-1,-1,2],[-1,0,1]] +}