-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumCloset.java
More file actions
42 lines (33 loc) · 1.17 KB
/
Copy pathThreeSumCloset.java
File metadata and controls
42 lines (33 loc) · 1.17 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
package LeetcodePractice;
import java.util.Arrays;
public class ThreeSumCloset {
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closestSum = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (Math.abs(sum - target) < Math.abs(closestSum - target)) {
closestSum = sum;
}
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
return sum;
}
}
}
return closestSum;
}
public static void main(String[] args) {
int[] nums1 = {-1, 2, 1, -4};
int target1 = 1;
System.out.println("Closest Sum: " + threeSumClosest(nums1, target1));
int[] nums2 = {0, 0, 0};
int target2 = 1;
System.out.println("Closest Sum: " + threeSumClosest(nums2, target2));
}
}