[LeetCode 解題報告]016. 3Sum Closest

Description:

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

 思路:與3Sum思想一致

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        
        long res = INT_MAX;

        sort(nums.begin(), nums.end());
        
        for(int i = 0; i < nums.size(); i ++) {
            
            int left = i+1, right = nums.size()-1;
            while(left < right) {
                
                int sum = nums[i] + nums[left] + nums[right];
                if(sum == target) 
                    return target;
                else if(sum > target) 
                    right --;
                else
                    left ++;
                
                if(abs(sum-target) < abs(res-target))
                    res = sum;
            }
        }
        return (int)res;
    }
};

 

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