Skip to content

Commit 21cb592

Browse files
committed
update 0016 Solution for Java
1 parent 71fc222 commit 21cb592

File tree

1 file changed

+37
-11
lines changed

1 file changed

+37
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,43 @@
11
class Solution {
22
public int threeSumClosest(int[] nums, int target) {
3-
int result = nums[0]+nums[1]+nums[2];
43
Arrays.sort(nums);
5-
for(int i = 0;i<nums.length-2;i++){
6-
int start = i+1,end=nums.length-1;
7-
while(start<end){
8-
int cache = nums[i]+nums[start]+nums[end];
9-
if(Math.abs(cache-target)<Math.abs(result-target)) result = cache;
10-
if(cache < target ) start++;
11-
else if(cache > target) end--;
12-
else return result;
4+
int bestAns = 100000;
5+
for (int i = 0;i + 2 < nums.length;i++) {
6+
if (i != 0 && nums[i] == nums[i - 1]) {
7+
continue;
8+
}
9+
int j = i + 1, k = nums.length - 1;
10+
while (j < k) {
11+
int sum = nums[i] + nums[j] + nums[k];
12+
if (sum == target) {
13+
return sum;
14+
}
15+
if (Math.abs(target - bestAns) > Math.abs(target - sum)) {
16+
bestAns = sum;
17+
}
18+
if (sum > target) {
19+
int k0 = k - 1;
20+
while (j < k0 && nums[k] == nums[k0]) {
21+
k0--;
22+
}
23+
if (j == k0) {
24+
break;
25+
} else {
26+
k = k0;
27+
}
28+
} else {
29+
int j0 = j + 1;
30+
while (j0 < j && nums[j] == nums[j0]) {
31+
j0++;
32+
}
33+
if (j0 == k) {
34+
break;
35+
} else {
36+
j = j0;
37+
}
38+
}
1339
}
1440
}
15-
return result;
41+
return bestAns;
1642
}
17-
}
43+
}

0 commit comments

Comments
 (0)