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


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums = sorted(nums)
        cur_diff = float('inf')
        if len(nums) <3:
            return []
        cur_sum = sum(nums[:3])
        for i in range(len(nums)-1):
            lo = i+1
            hi = len(nums)-1
            while lo < hi:
                cur_sum = nums[i]+nums[lo]+nums[hi]
                if abs(cur_sum-target) < cur_diff:
                    cur_diff = abs(cur_sum-target)
                    res = cur_sum
                if cur_sum >target:
                    hi -=1
                elif cur_sum < target:
                    lo +=1
                else:
                    return target
        return res

 




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

 


 

 

 

 

posted @ 2018-07-15 15:35  乐乐章  阅读(233)  评论(0编辑  收藏  举报