首页 > 代码库 > 3Sum Closest
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 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。