16. 最接近的三数之和(C++)---(排序+双指针)解题

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

示例:
输入:
nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
 

提示:

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


——题目难度:中等


 


 


这道题和15. 三数之和的解法其实差不了很多,只是在second和third的移动上有些差别。但是解题时保证不重复的核心还是先得对nums进行排序。

 

 

设delta = nums[first] + nums[second] + nums[third] - target,当delta = 0,当然就是和target最接近 直接返回即可;
当delta > 0,说明nums[first] + nums[second] + nums[third] 大于 target,那么就需要缩小 三数之和 ,因为second只能往右移动,这样会导致 三数之和 越来越大,所以只能让third往左移动;
当delta < 0,说明nums[first] + nums[second] + nums[third] 小于 target,那么就需要增大 三数之和 ,因为third只能往左移动,这样会导致 三数之和 越来越小,所以只能让second往右移动。

 




-代码如下

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
		sort(nums.begin(), nums.end());
		int n = nums.size();
		int ansSum = nums[0] + nums[1] + nums[2];
		
		for (int first = 0; first < n - 2; first++)
		{
			if (first > 0 && nums[first] == nums[first-1])
				continue;
				
			int second = first + 1;
			int third = n - 1;
			while (second < third) {
				int tmpSum = nums[first] + nums[second] + nums[third];
				if (abs(ansSum - target) > abs(tmpSum - target)) {
					ansSum = tmpSum;
				}
				
				//delta = nums[first] + nums[second] + nums[third] - target
				int delta = tmpSum - target; 
				if (delta == 0) {
					return ansSum;
				}
				else if (delta > 0) { //nums[first] + nums[second] + nums[third] > target
					third--;
				}
				else { //nums[first] + nums[second] + nums[third] < target
					second++;
				}
			}
		}
			
		return ansSum;	
    }
};


结果(有点慢呀...)



 


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章