Skip to content

Commit 2a47957

Browse files
committed
add testcase for 0016
1 parent 9bc120c commit 2a47957

File tree

3 files changed

+29
-17
lines changed

3 files changed

+29
-17
lines changed

LeetCode/0015. 3Sum/src/Solution.java

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,22 @@
33
import java.util.List;
44

55
/**
6-
* User: Changle
6+
* User: ChlZhYa
77
* Date: 2018-03-11 10:13
8-
* Source: https://leetcode.com/problems/3sum/description/
8+
* Source: <a href="https://leetcode.com/problems/3sum/description/">https://leetcode.com/problems/3sum/description/</a>
99
*/
1010

11-
/*
12-
考虑到 3sum 至少需要两遍循环,复杂度至少是 O(n^2) ,所以可以先排序。
13-
排序之后使用对撞指针即可。
1411

15-
相比 2sum ,关键在于过滤掉重复的结果。
16-
17-
时间复杂度: O(n^2)
18-
空间复杂度: O(n)
19-
*/
2012
public class Solution {
13+
/**
14+
考虑到 3sum 至少需要两遍循环,复杂度至少是 O(n^2) ,所以可以先排序。
15+
排序之后使用对撞指针即可。
2116
22-
class Solution {
17+
相比 2sum ,关键在于过滤掉重复的结果。
18+
19+
时间复杂度: O(n^2)
20+
空间复杂度: O(n)
21+
*/
2322
public List<List<Integer>> threeSum(int[] nums) {
2423
List<List<Integer>> res = new ArrayList<>();
2524
Arrays.sort(nums);
@@ -48,4 +47,3 @@ public List<List<Integer>> threeSum(int[] nums) {
4847
return res;
4948
}
5049
}
51-
}

LeetCode/0016. 3Sum Closest/src/Solution.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,22 @@
66
* Source: https://leetcode.com/problems/3sum-closest/description/
77
*/
88

9-
/*
9+
/**
1010
使用绝对值来判断距离。先排序,固定一个数,然后使用对撞指针。
1111
1212
时间复杂度: O(n^2)
1313
空间复杂度: O(1)
1414
*/
1515
public class Solution {
16-
// 因为必定存在结果,所以直接先把结果设置成数组里面三个数字的和
1716
public int threeSumClosest(int[] nums, int target) {
17+
int ans = nums[0] + nums[1] + nums[2];
1818
Arrays.sort(nums);
19-
int res = nums[0] + nums[1] + nums[2];
2019
for (int i = 0; i < nums.length - 2; i++) {
2120
int l = i + 1;
2221
int r = nums.length - 1;
2322
while (l < r) {
2423
int sum = nums[i] + nums[l] + nums[r];
25-
res = Math.abs(sum - target) < Math.abs(res - target) ? sum : res;
24+
ans = Math.abs(sum - target) < Math.abs(ans - target) ? sum : ans;
2625
if (sum < target) {
2726
l++;
2827
} else if (sum > target) {
@@ -32,6 +31,6 @@ public int threeSumClosest(int[] nums, int target) {
3231
}
3332
}
3433
}
35-
return res;
34+
return ans;
3635
}
3736
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @author clz
3+
* @date 2022/4/20
4+
*
5+
*/
6+
public class TestCase {
7+
8+
public static void main(String[] args) {
9+
Solution solution = new Solution();
10+
int[] arr = new int[]{1, 1, -1, -1, 3};
11+
int target = -1;
12+
System.out.println(solution.threeSumClosest(arr, target));
13+
}
14+
15+
}

0 commit comments

Comments
 (0)