-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16.最接近的三数之和.java
44 lines (33 loc) · 974 Bytes
/
16.最接近的三数之和.java
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
41
42
43
/*
* @lc app=leetcode.cn id=16 lang=java
*
* [16] 最接近的三数之和
*/
// @lc code=start
class Solution {
public int threeSumClosest(int[] nums, int target) {
int diff=Integer.MAX_VALUE;
int res=0;
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
int left=i+1;
int right=nums.length-1;
while(left<right){
int temp=nums[i]+nums[left]+nums[right]-target;
if(Math.abs(temp)<diff){
res=nums[i]+nums[left]+nums[right];
diff=Math.abs(temp);
}
if(temp==0){
return target;
}else if(temp<0){
left++;
}else{
right--;
}
}
}
return res;
}
}
// @lc code=end