-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloseThreeNumberNum.java
More file actions
31 lines (30 loc) · 1.02 KB
/
CloseThreeNumberNum.java
File metadata and controls
31 lines (30 loc) · 1.02 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
import java.util.Arrays;
import java.util.concurrent.CompletionStage;
public class CloseThreeNumberNum {
public static void main(String[] args){
int[] nums = new int[]{1,2,4,8,16,32,64,128};
int target = 82;
int result = threeSumClosest(nums, target);
System.out.println(result);
}
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int result = nums[0] + nums[1] + nums[2];
for(int i = 0; i< nums.length-2; i++) {
int l = i+1;
int r = nums.length - 1 ;
while( l < r) {
int threeNum = nums[i] + nums[l] +nums[r];
if(Math.abs(threeNum - target) < Math.abs(result - target)) {
result = threeNum;
}
if(threeNum < target) {
l++;
} else if(threeNum > target) {
r--;
} else return target;
}
}
return result;
}
}