Skip to content

Commit 4c0f6a8

Browse files
authored
add: 3sum solution in go (#37)
1 parent bab4440 commit 4c0f6a8

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ LeetCode
1818
|0012|[Integer to Roman](https://leetcode.com/problems/integer-to-roman) || [c++](./src/0012-Integer-to-Roman/0012.cpp) |[python](./src/0012-Integer-to-Roman/0012.py)|[go](./src/0012-Integer-to-Roman/0012.go)||||Medium|
1919
|0013|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/) || [c++](./src/0013-Roman-to-Integer/0013.cpp) |[python](./src/0013-Roman-to-Integer/0013.py)|[go](./src/0013-Roman-to-Integer/0013.go)|[js](./src/0013-Roman-to-Integer/0013.js)|[java](./src/0013-Roman-to-Integer/0013.java)||Easy|
2020
|0014|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) || [c++](./src/0014-Longest-Common-Prefix/0014.cpp) |[python](./src/0014-Longest-Common-Prefix/0014.py)|[go](./src/0014-Longest-Common-Prefix/0014.go)||||Easy|
21-
|0015|[3Sum](https://leetcode.com/problems/3sum/) || [c++](./src/0015-3Sum/0015.cpp) |[python](./src/0015-3Sum/0015.py)|||||Medium|
21+
|0015|[3Sum](https://leetcode.com/problems/3sum/) || [c++](./src/0015-3Sum/0015.cpp) |[python](./src/0015-3Sum/0015.py)|[go](./src/0015-3Sum/0015.go)||||Medium|
2222
|0016|[3Sum Closest](https://leetcode.com/problems/3Sum-Closest/) || [c++](./src/0016-3Sum-Closest/0016.cpp) |[python](./src/0016-3Sum-Closest/0016.py)|||||Medium|
2323
|0017|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) || [c++](./src/0017-Letter-Combinations-of-a-Phone-Number/0017.cpp) |[python](./src/0017-Letter-Combinations-of-a-Phone-Number/0017.py)|||||Medium|
2424
|0018|[4Sum](https://leetcode.com/problems/4sum/) || [c++](./src/0018-4Sum/0018.cpp) |[python](./src/0018-4Sum/0018.py)|||||Medium|

src/0015-3Sum/0015.go

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package sum
2+
3+
import (
4+
"sort"
5+
)
6+
7+
func threeSum(nums []int) [][]int {
8+
ans := make([][]int, 0)
9+
if len(nums) < 3 {
10+
return ans
11+
}
12+
sort.Ints(nums)
13+
for i := 0; i < len(nums)-2; i++ {
14+
if i > 0 && nums[i] == nums[i-1] {
15+
continue
16+
}
17+
lo, hi := i+1, len(nums)-1
18+
for lo < hi {
19+
val := nums[i] + nums[lo] + nums[hi]
20+
if val > 0 {
21+
hi--
22+
} else if val < 0 {
23+
lo++
24+
} else {
25+
temp := []int{nums[i], nums[lo], nums[hi]}
26+
ans = append(ans, temp)
27+
lo1, hi1 := lo, hi
28+
for lo < hi && nums[lo] == nums[lo1] {
29+
lo++
30+
}
31+
for lo < hi && nums[hi] == nums[hi1] {
32+
hi--
33+
}
34+
}
35+
}
36+
}
37+
return ans
38+
}

0 commit comments

Comments
 (0)