題目:
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.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
題解:
這道題也是3sum的變體,這裡找到的不僅使3sum==target,同時如果沒有找到==target的3sum要返回最接近target的值。
於是,這就需要在使用二分查詢法時遍歷陣列的時候,維護一個最接近target值min,這樣當完全遍歷完陣列扔沒找到與target相等的3sum時,可以返回維護的這個min值。
這道題比3sum和4sum簡單的地方就是不需要判斷重複問題,因為題目給我們減輕了去重的壓力,have exactly one solution。
即便要求去重,使用之前說過的兩個方法:HashSet和挪動指標法,也可以很容易就去重了。
這裡要注意,判斷closest的方法是採取target-sum的絕對值與min相比,很容易理解,無論這個closest是在target左還是右,離target最近的就是最closest的。
實現程式碼如下:
1 public int threeSumClosest(int[] num, int target) {
2 if(num==null || num.length<3)
3 return 0;
4
5 int min = Integer.MAX_VALUE;
6 int val = 0;
7 Arrays.sort(num);
8 for(int i = 0; i<=num.length-3;i++){
9 int low = i+1;
10 int high = num.length-1;
11 while(low<high){
12 int sum = num[i]+num[low]+num[high];
13 if(Math.abs(target-sum)<min){
14 min = Math.abs(target-sum);
15 val = sum;
16 }
17
18 if(target==sum){
19 return val;
20 }else if(target>sum){
21 low++;
22 }else{
23 high--;
24 }
25 }
26 }
27 return val;
28 }
2 if(num==null || num.length<3)
3 return 0;
4
5 int min = Integer.MAX_VALUE;
6 int val = 0;
7 Arrays.sort(num);
8 for(int i = 0; i<=num.length-3;i++){
9 int low = i+1;
10 int high = num.length-1;
11 while(low<high){
12 int sum = num[i]+num[low]+num[high];
13 if(Math.abs(target-sum)<min){
14 min = Math.abs(target-sum);
15 val = sum;
16 }
17
18 if(target==sum){
19 return val;
20 }else if(target>sum){
21 low++;
22 }else{
23 high--;
24 }
25 }
26 }
27 return val;
28 }