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

思路:

3-sum問題的簡化版

代碼:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        if(nums.size() == 0)return 0;

        sort(nums.begin(), nums.end());

        int min_sum, min_dis = INT_MAX, cur_dis;

        for(int i = 0; i < nums.size()-2; ++i){
            for(int j=i+1, k=nums.size()-1; j < k; ){
                int sumv =  nums[i]+nums[j]+nums[k];
                int res = sumv-target;
                cur_dis = abs(res);

                if(res == 0)
                    return sumv;
                else if(res < 0)
                    ++j;
                else
                    --k;

                if(cur_dis < min_dis){
                    min_dis = cur_dis;
                    min_sum = sumv;
                }
            }
        }

        return min_sum;
    }
};

結果:


這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章