leetcode 16. 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

跟 15 的做法很类似:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int sz=nums.size();
        int res=INT_MAX;
        for(int i=0;i<sz-2;i++){
            int j=i+1,k=sz-1;
            while(j<k){
                int cur=nums[i]+nums[j]+nums[k];
                if(cur==target)return target;
                else if(cur<target){
                    if(target-cur<abs(res))res=cur-target;
                    while(j<k&&nums[j+1]==nums[j])j++;j++;
                }
                else if(cur>target){
                    if(cur-target<abs(res))res=cur-target;
                    while(j<k&&nums[k-1]==nums[k])k--;k--;
                }
            }
        }
        return target+res;
    }
};
posted @ 2020-05-19 19:17  winechord  阅读(56)  评论(0编辑  收藏  举报