16. 3Sum Closest(重要)

来源:互联网 发布:网站数据库放在哪里 编辑:程序博客网 时间:2024/06/07 06:58

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).

Subscribe to see which companies asked this question

两个数和和目标值最接近很容易解决,用双指针。

先排序;

三个数,先固定一个数i从0-len-2遍历,i后面的数用双指针遍历。

时间复杂度O(N^2).

class Solution {public:int threeSumClosest(vector<int>& nums, int target) {int len=nums.size();sort(nums.begin(),nums.end());int res=nums[0]+nums[1]+nums[len-1];for(int i=0;i<len-2;i++){int left=i+1,right=len-1;while(left<right){int sum=nums[i]+nums[left]+nums[right];if(abs(sum-target)<abs(res-target)){res=sum;}if(sum==target){return sum;}else if(sum<target){left++;}else{right--;}}}return res;}};


0 0
原创粉丝点击