-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.3-sum-closest.java
More file actions
41 lines (39 loc) · 1.09 KB
/
Copy path16.3-sum-closest.java
File metadata and controls
41 lines (39 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
* @lc app=leetcode id=16 lang=java
*
* [16] 3Sum Closest
*/
// @lc code=start
class Solution {
public int threeSumClosest(int[] nums, int target) {
// 这里用long是因为会遇到res -(-1) 变成负数的情况
long res = Integer.MAX_VALUE;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// 双指针
int j = i + 1, k = nums.length - 1;
while (j < k) {
int currSum = nums[i] + nums[j] + nums[k];
if (currSum == target) {
return target;
}
else {
if (Math.abs(res - target) > Math.abs(currSum - target)) {
res = currSum;
}
if (currSum > target) {
k--;
}
else {
j++;
}
}
}
}
return (int)res;
}
}
// @lc code=end