-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.最接近的三数之和.java
63 lines (56 loc) · 1.64 KB
/
16.最接近的三数之和.java
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
52
53
54
55
56
57
58
59
60
61
62
import java.util.Arrays;
/*
* @lc app=leetcode.cn id=16 lang=java
*
* [16] 最接近的三数之和
*/
class Solution {
public int threeSumClosest(int[] nums, int target) {
if(nums == null || nums.length == 0){
return 0;
}
Arrays.sort(nums);
return nCloesetSum(nums, 0, target, 3);
}
public int nCloesetSum(int [] nums, int startIndex, int target, int n){
if(n == 2){
return twoClosestSum(nums, startIndex, target);
}else{
int closest = 0;
for(int i = startIndex; i < n; i++){
closest += nums[i];
}
int temp = 0;
for(int i = startIndex; i < nums.length-n+1; i++){
temp = nums[i]+ nCloesetSum(nums, i+1, target-nums[i], n-1);
if(Math.abs(temp-target) < Math.abs(closest - target)){
closest = temp;
}
}
return closest;
}
}
public int twoClosestSum(int[] nums, int startIndex, int target){
if(nums == null || nums.length == 0){
return 0;
}
int left = startIndex;
int right = nums.length -1;
int closest = nums[left] + nums[right];
int temp = 0;
while(left < right){
temp = nums[left] + nums[right];
if(temp > target){
right --;
}else if(temp < target){
left++;
}else{
return temp;
}
if(Math.abs(temp - target) < Math.abs(closest - target)){
closest = temp;
}
}
return closest;
}
}