-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTwoSumClosest.java
More file actions
42 lines (38 loc) · 1.05 KB
/
TwoSumClosest.java
File metadata and controls
42 lines (38 loc) · 1.05 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
import java.util.*;
public class TwoSumClosest {
public int twoSumCloset(int[] nums, int target) {
if (nums == null || nums.length < 2) {
return -1;
}
if (nums.length == 2) {
return target - nums[0] - nums[1];
}
Arrays.sort(nums);
int pl = 0;
int pr = nums.length - 1;
int minDiff = Integer.MAX_VALUE;
while (pl < pr) {
int sum = nums[pl] + nums[pr];
int diff = Math.abs(sum - target);
if (diff == 0) {
return 0;
}
if (diff < minDiff ) {
minDiff = diff;
}
if (sum > target) {
pr--;
} else {
pl++;
}
}
return minDiff;
}
public static void main(String[] args) {
int[] nums = new int[] {-1, 2, 1, -4};
int target = 4;
TwoSumClosest sol = new TwoSumClosest();
int mindif = sol.twoSumCloset(nums, target);
System.out.println(mindif);
}
}