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

题目大意:取三个数,求出与给的目标值最接近的三个数的和。

题目分析:主要思路与第15题差不多,只需要在其原有代码基础上稍作修改就行

代码1:运行时间12ms

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        
        sort(nums.begin(), nums.end());//先排序
        
        int i,j,k,ans,sum,differ=INT_MAX,tempdiff;
        for(i=0;i<nums.size()-1;i++){
            if(i>0&&nums[i-1]==nums[i])//去除重复
                continue;
                
            j=i+1;k=nums.size()-1;
            while(j<k){
                sum=nums[i]+nums[j]+nums[k];
                tempdiff=abs(sum-target);//记录当前差
                if(tempdiff<differ){
                    ans=sum;
                    differ=tempdiff;//differ记录最小差
                }
                
                if(sum==target)
                    return target;
                else if(sum<target){
                    while(j++<k&&nums[j-1]==nums[j]);//去除重复
                }else{
                    while(j<--k&&nums[k]==nums[k+1]);//去除重复
                }
            }
        }
        
        return ans;
    }
};
代码2:下面试discuss里面的代码,思路一样的,写的更加简便易懂,不过运行时间稍长 28ms
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int res = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.size() - 2; i++){
            int j = i + 1, k = nums.size() - 1;
            while(j < k){
                int num = nums[i] + nums[j] + nums[k];
                if(abs(num - target) < abs(res - target)) res = num;
                if(num < target) j++;
                else k--;
            }
        }
        return res;
    }
};


你可能感兴趣的:(LeetCode,C++,closest,双指针,3Sum)