Skip to content

Commit 51a5bbd

Browse files
committed
Added task 16.
1 parent 687801f commit 51a5bbd

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package s0016.three.sum.closest;
2+
3+
import java.util.Arrays;
4+
5+
public class Solution {
6+
public int threeSumClosest(int[] nums, int target) {
7+
if (nums == null || nums.length < 3) return 0;
8+
if (nums.length == 3) return nums[0] + nums[1] + nums[2];
9+
Arrays.sort(nums);
10+
int n = nums.length;
11+
int sum = nums[0] + nums[1] + nums[2];
12+
for (int i = 0; i < n - 2; i++) {
13+
if (nums[i] + nums[n - 1] + nums[n - 2] < target) {
14+
sum = nums[i] + nums[n - 1] + nums[n - 2];
15+
continue;
16+
}
17+
if (nums[i] + nums[i + 1] + nums[i + 2] > target) {
18+
int temp = nums[i] + nums[i + 1] + nums[i + 2];
19+
return lessGap(sum, temp, target);
20+
}
21+
int j = i + 1;
22+
int k = n - 1;
23+
while (j < k) {
24+
int temp = nums[i] + nums[j] + nums[k];
25+
if (temp == target) return target;
26+
if (temp < target) {
27+
j++;
28+
sum = lessGap(sum, temp, target);
29+
} else {
30+
k--;
31+
sum = lessGap(sum, temp, target);
32+
}
33+
}
34+
}
35+
return sum;
36+
}
37+
38+
private int lessGap(int sum, int temp, int target) {
39+
return Math.abs(sum - target) < Math.abs(temp - target) ? sum : temp;
40+
}
41+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package s0016.three.sum.closest;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.Test;
7+
8+
public class SolutionTest {
9+
@Test
10+
public void threeSum() {
11+
assertThat(new Solution().threeSumClosest(new int[] {-1, 2, 1, -4}, 1), equalTo(2));
12+
}
13+
}

0 commit comments

Comments
 (0)