forked from Google-DSC-TMSL/ProjectAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sumclosest.java
More file actions
30 lines (27 loc) · 844 Bytes
/
3sumclosest.java
File metadata and controls
30 lines (27 loc) · 844 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
26
27
28
29
30
class Solution {
public int threeSumClosest(int[] nums, int target){
// idea is to have 2 pointers in a sorted array
Arrays.sort(nums);
int ans = nums[0] + nums[1] + nums[2];
for(int i=0; i<nums.length-2; i++){
int a = i+1;
int b = nums.length-1;
while(a<b){
int curr = nums[i] + nums[a] + nums[b];
if(curr > target){
b--;
}
else if(curr < target){
a++;
}
else{
return curr;
}
if(Math.abs(ans-target) > Math.abs(curr-target)){
ans = curr;
}
}
}
return ans;
}
}