Skip to content

Commit c6f4a2a

Browse files
authored
Update 3Sum Closest.java
1 parent 457dda2 commit c6f4a2a

File tree

1 file changed

+18
-23
lines changed

1 file changed

+18
-23
lines changed

Medium/3Sum Closest.java

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,22 @@
11
class Solution {
2-
public int threeSumClosest(int[] nums, int target) {
3-
int sum = Integer.MAX_VALUE;
4-
Arrays.sort(nums);
5-
6-
for (int i=0; i<nums.length; i++) {
7-
int j = i + 1;
8-
int k = nums.length - 1;
9-
10-
while (j < k) {
11-
int tempSum = nums[i] + nums[j] + nums[k];
12-
if (sum == Integer.MAX_VALUE || Math.abs(sum - target) > Math.abs(target - tempSum)) {
13-
sum = tempSum;
14-
}
15-
16-
if (tempSum > target) {
17-
k--;
18-
}
19-
else {
20-
j++;
21-
}
22-
}
2+
public int threeSumClosest(int[] nums, int target) {
3+
Arrays.sort(nums);
4+
int closestDiff = Integer.MAX_VALUE;
5+
for (int i = 0; i < nums.length; i++) {
6+
int start = i + 1;
7+
int end = nums.length - 1;
8+
while (start < end) {
9+
int currSum = nums[i] + nums[start] + nums[end];
10+
if (Math.abs(target - currSum) < Math.abs(closestDiff)) {
11+
closestDiff = target - currSum;
2312
}
24-
25-
return sum;
13+
if (currSum < target) {
14+
start++;
15+
} else {
16+
end--;
17+
}
18+
}
2619
}
20+
return target - closestDiff;
21+
}
2722
}

0 commit comments

Comments
 (0)