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

C++:
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int result;
        if (nums.size() < 3)
            return -1;
        sort(nums.begin(), nums.end());
        int abs_diff = INT_MAX;
        for (int i = 0; i < nums.size() - 2; i++){
            for (int j = i + 1, k = nums.size() - 1; j < k;){
                int sum = nums[i] + nums[j] + nums[k];
                if (abs_diff>abs(target - sum)){
                    abs_diff = abs(target - sum);        //更新最小绝对值差
                    result=sum;
                }
                if (sum < target){
                    while (nums[++j] == nums[j - 1] && j < k);
                }
                else{
                    while (nums[--k] == nums[k + 1] && j < k);
                }
            }
        }
        return result;
    }
};

 

posted @ 2018-09-03 11:44  康托漫步  阅读(80)  评论(0编辑  收藏  举报