Skip to content

Commit 3e2d511

Browse files
committed
Optimization solution 0015
1 parent bbb448d commit 3e2d511

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

leetcode/0015.3Sum/15. 3Sum.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,44 @@ import (
44
"sort"
55
)
66

7+
// 解法一 最优解,双指针 + 排序
78
func threeSum(nums []int) [][]int {
9+
sort.Ints(nums)
10+
result, start, end, index, addNum, length := make([][]int, 0), 0, 0, 0, 0, len(nums)
11+
if length > 0 && (nums[0] > 0 || nums[length-1] < 0) {
12+
return result
13+
}
14+
for index = 1; index < length-1; index++ {
15+
start, end = 0, length-1
16+
if index > 1 && nums[index] == nums[index-1] {
17+
start = index - 1
18+
}
19+
for start < index && end > index {
20+
if start > 0 && nums[start] == nums[start-1] {
21+
start++
22+
continue
23+
}
24+
if end < length-1 && nums[end] == nums[end+1] {
25+
end--
26+
continue
27+
}
28+
addNum = nums[start] + nums[end] + nums[index]
29+
if addNum == 0 {
30+
result = append(result, []int{nums[start], nums[index], nums[end]})
31+
start++
32+
end--
33+
} else if addNum > 0 {
34+
end--
35+
} else {
36+
start++
37+
}
38+
}
39+
}
40+
return result
41+
}
42+
43+
// 解法二
44+
func threeSum1(nums []int) [][]int {
845
res := [][]int{}
946
counter := map[int]int{}
1047
for _, value := range nums {

website/content/ChapterFour/0015.3Sum.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,44 @@ import (
4242
"sort"
4343
)
4444

45+
// 解法一 最优解,双指针 + 排序
4546
func threeSum(nums []int) [][]int {
47+
sort.Ints(nums)
48+
result, start, end, index, addNum, length := make([][]int, 0), 0, 0, 0, 0, len(nums)
49+
if length > 0 && (nums[0] > 0 || nums[length-1] < 0) {
50+
return result
51+
}
52+
for index = 1; index < length-1; index++ {
53+
start, end = 0, length-1
54+
if index > 1 && nums[index] == nums[index-1] {
55+
start = index - 1
56+
}
57+
for start < index && end > index {
58+
if start > 0 && nums[start] == nums[start-1] {
59+
start++
60+
continue
61+
}
62+
if end < length-1 && nums[end] == nums[end+1] {
63+
end--
64+
continue
65+
}
66+
addNum = nums[start] + nums[end] + nums[index]
67+
if addNum == 0 {
68+
result = append(result, []int{nums[start], nums[index], nums[end]})
69+
start++
70+
end--
71+
} else if addNum > 0 {
72+
end--
73+
} else {
74+
start++
75+
}
76+
}
77+
}
78+
return result
79+
}
80+
81+
// 解法二
82+
func threeSum1(nums []int) [][]int {
4683
res := [][]int{}
4784
counter := map[int]int{}
4885
for _, value := range nums {
@@ -76,6 +113,7 @@ func threeSum(nums []int) [][]int {
76113
}
77114

78115

116+
79117
```
80118

81119

0 commit comments

Comments
 (0)