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.
给定一个数组及一个目标值,找出三个数,使它们的和与目标值的差值最小,输出它们的和。

解法

与上一题3Sum一样,遍历第一个数,然后用双指针算法遍历剩下两个数,随时比较它们与目标值的差值。

class Solution 
{
public:
    int threeSumClosest(vector<int>& nums, int target)
    {
	    sort(nums.begin(),nums.end());

	    int	diff = 0x7fffffff;
	    int	ans = 0;

	    for(int i = 0;i < nums.size();i ++)
	    {
		    int	j = i + 1;
		    int	k = nums.size() - 1;

		    while(j < k)
		    {
			    int	sum = nums[i] + nums[j] + nums[k];
			    if(abs(sum - target) < diff)
			    {
				    diff = abs(sum - target);
				    ans = sum;
			    }

			    if(sum < target)
				    j ++;
			    else
				    k --;
		    }
	    }
	    return	ans;
    }
};

相关文章:

  • 2021-11-29
  • 2021-08-08
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
  • 2022-12-23
猜你喜欢
  • 2021-10-01
  • 2021-10-16
  • 2022-01-07
  • 2022-02-25
  • 2021-05-24
  • 2021-05-31
  • 2022-02-25
相关资源
相似解决方案