-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.java
More file actions
25 lines (25 loc) · 827 Bytes
/
3SumClosest.java
File metadata and controls
25 lines (25 loc) · 827 Bytes
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
public class 3SumClosest {
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int ans = num[0]+ num[1]+ num[2];
for(int i = 0; i < num.length-2; i++){
if(i == 0 || num[i-1] != num[i]){
int left = i+1, right = num.length-1;
while(left < right){
int now = num[i] + num[left] + num[right];
if(Math.abs(now -target) < Math.abs(ans -target)){
ans = now;
}
if(now > target){
right--;
}else if(now < target){
left++;
}else{
return now;
}
}
}
}
return ans;
}
}