Skip to content

Commit 8111ad1

Browse files
[N-0] refactor 16
1 parent 2b9e70c commit 8111ad1

File tree

1 file changed

+33
-28
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+33
-28
lines changed

src/main/java/com/fishercoder/solutions/_16.java

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,45 +3,50 @@
33
import java.util.Arrays;
44

55
/**
6-
* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
6+
* 16. 3Sum Closest
7+
*
8+
* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
9+
* Return the sum of the three integers. You may assume that each input would have exactly one solution.
710
* For example, given array S = {-1 2 1 -4}, and target = 1.
811
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
912
*/
1013

1114
public class _16 {
1215

13-
public int threeSumClosest(int[] nums, int target) {
14-
if (nums == null || nums.length == 0) {
15-
return 0;
16-
}
17-
Arrays.sort(nums);
18-
int len = nums.length;
19-
if (len < 3) {
20-
int sum = 0;
21-
for (int i : nums) {
22-
sum += i;
16+
public static class Solution1 {
17+
public int threeSumClosest(int[] nums, int target) {
18+
if (nums == null || nums.length == 0) {
19+
return 0;
2320
}
24-
return sum;
25-
}
26-
int sum = nums[0] + nums[1] + nums[2];
27-
for (int i = 0; i < nums.length - 2; i++) {
28-
int left = i + 1;
29-
int right = nums.length - 1;
30-
while (left < right) {
31-
int thisSum = nums[i] + nums[left] + nums[right];
32-
if (Math.abs(target - thisSum) < Math.abs(target - sum)) {
33-
sum = thisSum;
34-
if (sum == target) {
35-
return sum;
21+
Arrays.sort(nums);
22+
int len = nums.length;
23+
if (len < 3) {
24+
int sum = 0;
25+
for (int i : nums) {
26+
sum += i;
27+
}
28+
return sum;
29+
}
30+
int sum = nums[0] + nums[1] + nums[2];
31+
for (int i = 0; i < nums.length - 2; i++) {
32+
int left = i + 1;
33+
int right = nums.length - 1;
34+
while (left < right) {
35+
int thisSum = nums[i] + nums[left] + nums[right];
36+
if (Math.abs(target - thisSum) < Math.abs(target - sum)) {
37+
sum = thisSum;
38+
if (sum == target) {
39+
return sum;
40+
}
41+
} else if (target > thisSum) {
42+
left++;
43+
} else {
44+
right--;
3645
}
37-
} else if (target > thisSum) {
38-
left++;
39-
} else {
40-
right--;
4146
}
4247
}
48+
return sum;
4349
}
44-
return sum;
4550
}
4651

4752
}

0 commit comments

Comments
 (0)