16. 最接近的三数之和

Posted 朴素贝叶斯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了16. 最接近的三数之和相关的知识,希望对你有一定的参考价值。

题目描述:

Given an array S of n integers, find three integers in S
such that the sum is closest to a given number, target.
Return the sum of the three integers. You may assume that
each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

代码:

class Solution {
public:
    int threeSumClosest(vector<int> &nums, int target) {
        
    	int closest = nums[0] + nums[1] + nums[2];
        int diff = abs(closest - target);//循环前的初始化工作
        sort(nums.begin(), nums.end());
        //i为直接遍历枚举的三元组的第一个数下标
        for(int i = 0; i <= int(nums.size() - 3); ++i)
        {
            int left = i + 1, right = nums.size() - 1;
            while(left < right)
            {

                int sum = nums[i] + nums[left] + nums[right];
                int newDiff = abs(sum - target);
                if(newDiff < diff)
                {   
                    if(newDiff == 0)
	                return target;
                    diff = newDiff;
                    closest = sum;
                }
                if(sum < target)
                	++left;
                else
                	--right;               
            }
        }
        return closest;       
    }
};

以上是关于16. 最接近的三数之和的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode 16] 最接近的三数之和

leetcode-----16. 最接近的三数之和

LeetCode 16. 最接近的三数之和

力扣16-最接近的三数之和&力扣18-四数之和

LeetCode:最接近的三数之和16

leetcode 16:最接近的三数之和