-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.java
More file actions
28 lines (23 loc) · 834 Bytes
/
Copy path3SumClosest.java
File metadata and controls
28 lines (23 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
28
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closet = 0;
int min = Integer.MAX_VALUE;
for (int i = 0; i < nums.length - 2; i++) {
int small = i + 1;
int large = nums.length - 1;
while (small < large) {
int sum = nums[i] + nums[small] + nums[large];
if (sum > target) large--;
else if (sum < target) small++;
else return target;
int diff = Math.abs(target - sum);
if (diff < min) {
min = diff;
closet = sum;
}
}
}
return closet;
}
}