【中等】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.

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest

解法

方法:双指针

解题思路

三数之和是异曲同工的,固定一个位之后剩下用双指针,区别是如果找到了target就可以直接返回了

代码

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int size = nums.size();     
        int res = nums[0]+nums[1]+nums[2];
        for(int i = 0; i < size-2; ++i){
            int start = i+1, end = size-1;
            while(start<end){
                int sum = nums[i]+nums[start]+nums[end];
                if(sum == target) return target;
                res = abs(target-sum) < abs(res-target) ? sum : res;
                if(sum > target) end--;
                else start++;
            }
        }
        return res;
    }
};
posted @ 2020-04-23 16:31  陌良  阅读(93)  评论(0编辑  收藏  举报