3Sum Closest
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类似的方法,使用三个指针,让最左边的指针l从[0,size-2]变化,对于每一个固定的最左指针l,中间指针和最右指针在[l+1,size-1]范围内移动,移动方法跟2sum一致。先初始化min_dif=INT_MAX,如果出现更小的dif,则更新min_dif以及closest sum。时间复杂度是O(n^2),空间复杂度是O(1)。
代码如下:
1 class Solution { 2 public: 3 int threeSumClosest(vector<int> &num, int target) { 4 int size = num.size(); 5 if(size < 3) return 0; 6 sort(num.begin(),num.end()); 7 int min_dif = INT_MAX; 8 int closest_sum; 9 int l = 0, mid = 1, r = size-1; 10 for(;l < size-2;l++){ 11 mid = l + 1; 12 r = size - 1; 13 while(mid < r){ 14 int sum = num[l] + num[mid] + num[r]; 15 int dif = abs(sum-target); 16 if(dif < min_dif){ 17 closest_sum = sum; 18 min_dif = dif; 19 } 20 if(sum < target) mid++; 21 else r--; 22 } 23 } 24 return closest_sum; 25 } 26 };