16. 3Sum Closest

https://leetcode.com/problems/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 1:

  • Input: nums = [-1,2,1,-4], target = 1
  • Output: 2
  • Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Constraints:

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4

算法思路:

如果当前数组不排序,那么取其中任意三个得到curSum,与target比较,C(n,3)=n*(n-1)*(n-2)/6,时间复杂度是O(n^3),不用想肯定超时,所以和前面twoSum等问题类似,先排序( O(n logn) ),然后先固定一个,另外两个使用双指针技术,使得时间复杂度降为O(n^2)。

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        
        int left=0;
        int right=nums.size()-1;
        int diff=INT_MAX;
        int res=INT_MAX;
        int curSum=0;
        
        for(int i=0;i<nums.size()-2;i++){ //O(n^2)
            left=i+1;
            right=nums.size()-1;
            while(left<right){
                curSum=nums[i]+nums[left]+nums[right];
                if(curSum==target){
                    return target;  
                }
                if(curSum>target){
                    if(diff>curSum-target){
                        diff=curSum-target;
                        res=curSum;
                    }
                    right--;
                }else{ //curSum<target
                    if(diff>target-curSum){
                        diff=target-curSum;
                        res=curSum;
                    }
                    left++;
                }
            }
        }
        return res;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值