-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path16. 3Sum Closest.java
More file actions
37 lines (33 loc) · 1.05 KB
/
16. 3Sum Closest.java
File metadata and controls
37 lines (33 loc) · 1.05 KB
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 class Solution {
public int threeSumClosest(int[] nums, int target) {
//sort array
Arrays.sort(nums);
int result = 0;
int pfront;
int pback;
//max value
int diff = Integer.MAX_VALUE;
for(int i = 0; i < nums.length - 2; i++){
//set pointers
pfront = i + 1;
pback = nums.length - 1;
while(pfront < pback){
int sum = nums[i] + nums[pfront] + nums[pback];
if(sum == target){
return target;
}else if(Math.abs(target - sum) < diff){
//update closest value and diff
diff = Math.abs(target - sum);
result = sum;
}
//move pointers
if(sum < target){
pfront++;
}else{
pback--;
}
}
}
return result;
}
}