LeetCode 16. 3Sum Closest

类似上一题15 3Sum

 

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int len=nums.size(),l,r,min=INT_MAX,ans;
        for (int i=0;i<len-2;i++){
            l=i+1;r=len-1;
            while(l<r){
                if (target==nums[i]+nums[l]+nums[r]) return target;
                while(nums[i]+nums[l]+nums[r]>target && l<r) {
                    if (min>nums[i]+nums[l]+nums[r]-target){
                        min=nums[i]+nums[l]+nums[r]-target;
                        ans=nums[i]+nums[l]+nums[r];
                        if (target==ans) return ans;
                    }//if
                    r--;
                }//while
                while(nums[i]+nums[l]+nums[r]<target && l<r) {
                    if (min>target-nums[i]-nums[l]-nums[r]){
                        min=target-nums[i]-nums[l]-nums[r];
                        ans=nums[i]+nums[l]+nums[r];
                        if (target==ans) return ans;
                    }//if
                    l++;
                }//while
            }//while
        }//for
        return ans;
    }
};

看到有人把代码写的很简洁,也放上来。

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

 

posted @ 2018-08-09 16:07  Travelller  阅读(93)  评论(0编辑  收藏  举报