[leetcode]16. 3Sum Closest

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w5688414/article/details/86530959

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

分析

  • 这道题对一开始上手的人来说,可能思维不难,但是代码写好的话,就有点困难,比如在寻找之前先从小到大排序,用diff来记录目标和最近的差值,然后遍历寻找。
  • for(){
    while(left<right){
    }
    }
    这种模式在leetcode的其他几个题中会遇见,这可以作为这一类题目的通用解法。
  • 解法有点暴力

代码

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

参考文献

[LeetCode] 3Sum Closest 最近三数之和

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/86530959
今日推荐