[LeetCode 16] and the number of the nearest three

Topic Link

【answer】


On a question that algorithm for the three and the number is zero, when, in fact, is a constant in approaching this problem in x = 0.
Then apply the above approach that question is.
When approaching, take a minimum value of the difference alone.

[Code]

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

Guess you like

Origin www.cnblogs.com/AWCXV/p/11808904.html