最接近的三数之和

题目

https://leetcode-cn.com/problems/3sum-closest/

解法

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
public int threeSumClosest(int[] nums, int target) {
if (nums==null || nums.length < 3) {
return Integer.MAX_VALUE;
}

Arrays.sort(nums);
int minRes = Integer.MAX_VALUE;
int dis = Integer.MAX_VALUE;

for (int i = 0; i < nums.length-2; i++) {
int twoSum = target - nums[i];
int j = i+1, k = nums.length-1;
while (j<k) {

if (Math.abs(nums[i] + nums[j] + nums[k] - target) < dis) {
dis = Math.abs(nums[i] + nums[j] + nums[k] - target);
minRes = nums[i] + nums[j] + nums[k];
}

if (nums[j] + nums[k] < twoSum) {
j++;

} else if (nums[j] + nums[k] > twoSum) {
k--;
} else if (nums[j] + nums[k] == twoSum) {
break;
}

}

if (j < k) {
break;
}
}
return minRes;

}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×