-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq016_ThreeSumClosest.java
More file actions
51 lines (37 loc) · 1.2 KB
/
q016_ThreeSumClosest.java
File metadata and controls
51 lines (37 loc) · 1.2 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
43
44
45
46
47
48
49
50
51
package leetcode_algorithm;
import java.util.Arrays;
/**
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.
*/
public class q016_ThreeSumClosest {
public static void main(String[] args) {
System.out.println(threeSumClosest(new int[]{1 , 2 , -1 , -4} , 2) );
}
/**
* ½â·¨1
*
* @param nums
* @param target
* @return
*/
public static int threeSumClosest(int[] nums, int target) {
int result = nums[0] + nums[1] + nums[nums.length - 1];
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2;i++) {
int start = i + 1, end = nums.length - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
if (sum > target) {
end--;
}else {
start ++;
}
}
}
return result;
}
}