三数之和, 每次都更新答案版

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
class Solution {
/**
* 三数之和, 每次都更新答案版
*/
public int threeSumClosest(int[] nums, int target) {
int ans = Integer.MAX_VALUE / 2;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (Math.abs(sum - target) < Math.abs(ans - target)) {
ans = sum;
}
if (sum == target) {
return target;
} else if (sum < target) {
j++;
} else {
k--;
}
}
}
return ans;
}
}

Comments