-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.java
More file actions
29 lines (25 loc) · 882 Bytes
/
Copy path3SumClosest.java
File metadata and controls
29 lines (25 loc) · 882 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
public class Solution {
public int threeSumClosest(int[] nums, int target) {
if(nums == null || nums.length < 3) throw new IllegalArgumentException("xxx");
Arrays.sort(nums);
int n = nums.length;
int minDiff = Integer.MAX_VALUE;
int candidate = 0;
for(int i = 0; i < n; i++){
int j = i+1;
int k = n-1;
while(j < k){
int t = nums[i] + nums[j] + nums[k];
if(t == target) return t;
// keep track of all potential candidates
if(Math.abs(t-target) < minDiff){
minDiff = Math.abs(t-target);
candidate = t;
}
if(t < target) j++;
else k--;
}
}
return candidate;
}
}