-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreeSumClosest.java
More file actions
28 lines (27 loc) · 834 Bytes
/
threeSumClosest.java
File metadata and controls
28 lines (27 loc) · 834 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
package array;
import java.util.*;
public class threeSumClosest {
public int Solution(int[] nums, int target) {
Arrays.sort(nums);
int sum = Integer.MAX_VALUE;
int maxDiff = Integer.MAX_VALUE;
// int temp=nums[0] ;
for (int i = 0; i < nums.length-2; i++) {
int lo=i+1,hi=nums.length-1;
while(lo<hi) {
int tempSum= nums[i] + nums[lo]+nums[hi];
int tempDiff= Math.abs(tempSum - target);
if (tempDiff<maxDiff) {
maxDiff=tempDiff;
sum = tempSum;
}
if(tempSum > target) hi--;
else if (tempSum <target) lo++;
else{
return target;
}
}
}
return sum;
}
}