Skip to content

Commit b684201

Browse files
aQuaaQua
aQua
authored and
aQua
committed
added Problem 16
1 parent e1b471a commit b684201

File tree

3 files changed

+20
-35
lines changed

3 files changed

+20
-35
lines changed

Algorithms/0016.3sum-closest/3sum-closest.go

Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
)
77

88
func threeSumClosest(nums []int, target int) int {
9-
109
// 排序后,可以按规律查找
1110
sort.Ints(nums)
1211
res, delta := 0, math.MaxInt64
@@ -21,45 +20,24 @@ func threeSumClosest(nums []int, target int) int {
2120

2221
for l < r {
2322
s := nums[i] + nums[l] + nums[r]
24-
temp := abs(target - s)
2523
switch {
26-
case temp < delta:
27-
24+
case s < target:
2825
l++
29-
case s > 0:
30-
// 较大的 r 需要变小
26+
if delta > target-s {
27+
delta = target - s
28+
res = s
29+
}
30+
case s > target:
3131
r--
32+
if delta > s-target {
33+
delta = s - target
34+
res = s
35+
}
3236
default:
33-
res = append(res, []int{nums[i], nums[l], nums[r]})
34-
// 为避免重复添加,l 和 r 都需要移动到不同的元素上。
35-
l, r = next(nums, l, r)
37+
return s
3638
}
3739
}
3840
}
3941

4042
return res
4143
}
42-
43-
func next(nums []int, l, r int) (int, int) {
44-
for l < r {
45-
switch {
46-
case nums[l] == nums[l+1]:
47-
l++
48-
case nums[r] == nums[r-1]:
49-
r--
50-
default:
51-
l++
52-
r--
53-
return l, r
54-
}
55-
}
56-
57-
return l, r
58-
}
59-
60-
func abs(a int) int {
61-
if a > 0 {
62-
return a
63-
}
64-
return -a
65-
}

Algorithms/0016.3sum-closest/3sum-closest_test.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,14 @@ func Test_Problem0016(t *testing.T) {
3434
para{[]int{-1, 2, 1, -4}, 1},
3535
ans{2},
3636
},
37-
37+
question{
38+
para{[]int{-1, 2, 2, 2, 2, 2, 2, 2, 1, -4}, 1},
39+
ans{0},
40+
},
41+
question{
42+
para{[]int{-1, 2, 2, 2, 2, 2, 2, 2, 1, -4}, 0},
43+
ans{0},
44+
},
3845
// 如需多个测试,可以复制上方元素。
3946
}
4047

Algorithms/0016.3sum-closest/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ For example, given array S = {-1 2 1 -4}, and target = 1.
88
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
99
```
1010
## 解题思路
11-
11+
这一题和15题的思路基本一致。
1212

1313
## 总结
1414

0 commit comments

Comments
 (0)