LeetCode15-求最接近目标的三数之和

image-20230312215508028

求解:

三层for循环 接近的sub的值、

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
class Solution{

public int threeSumClosest(int[] nums, int target) {
// 保存和目标的差值
int sub = Integer.MAX_VALUE;
// 定义保存之和
int sum =0;

int length = nums.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
for(int k=j+1;k<length;k++){
if(Math.abs(nums[i]+nums[j]+nums[k]-target) < sub){
// 更新target 值
sum = nums[i]+nums[j] + nums[k];
sub = Math.abs(nums[i]+nums[j] + nums[k] -target);
}
}
}
}

return sum;
}

}
// 双指针的思想
public int threeSumClosest2(int[] nums, int target) {
Arrays.sort(nums);
int nearNum = nums[0] + nums[1] + nums[2];
// 保证最右边的数组不越界
for(int i=0;i< nums.length-2;i++){
int l = 0; int r = nums.length-1;
while(l<r){
int targetNum = nums[l]+nums[i]+nums[r];
if(Math.abs(targetNum - target ) < Math.abs(nearNum -target )){
nearNum = targetNum;
}
// 大于
if(targetNum > target){
r--;
}else if (targetNum < target){
l++;
}else{
// 相等则是最接近的值
return target;
}
}
}
return nearNum;


}



}

__END__