3Sum Closest

原创 2016年08月29日 15:45:50
class Solution {
public:
	int threeSumClosest(vector<int>& nums, int target) {
		int result = nums[0] + nums[1] + nums[2];
		int gap = abs(result - target);
		//if(nums.size()<3) return result;
		sort(nums.begin(), nums.end());
		//vector<int> tmp;
		for (int i = 0; i<nums.size() - 2; i++){

			twoSumClosest(nums, i + 1, target - nums[i], result, gap);

		}
		return result;
	}

	void twoSumClosest(vector<int>& nums, int start, int target, int& result, int& gap){
		//vector<int> result;
		int left = start, right = nums.size() - 1;
		while (left<right){
			if (abs(nums[left] + nums[right] - target)<gap){
				gap = abs(nums[left] + nums[right] - target);
				result = nums[left] + nums[right] + nums[start - 1];
			}
			if (nums[left] + nums[right]<target){
				left++;
			}
			else if (nums[left] + nums[right]>target){
				right--;
			}
			else{
				gap = 0;
				result = nums[left] + nums[right] + nums[start - 1];
				break;
			}
		}

	}
};

LeetCodet题解--16. 3Sum Closest(离给定值最近的三数之和)

链接 LeetCode题目:https://leetcode.com/problems/3sum-closest/ GitHub代码:https://github.com/gatieme...
  • gatieme
  • gatieme
  • 2016年04月04日 16:22
  • 1308

leetcode.16----------3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...

LeetCode #16 - 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...
  • LawFile
  • LawFile
  • 2016年10月13日 09:05
  • 125

16. 3Sum Closest LeetCode题解

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...

[LeetCode16]3Sum Closest

3Sum Closest Given an array S of n integers, find three integers in S such that the sum is closest t...
  • sbitswc
  • sbitswc
  • 2014年06月05日 04:51
  • 576

3Sum Closest

题目 Given an array S of n integers, find three integers in S such that the sum is closest to a gi...
  • Boyhou
  • Boyhou
  • 2013年07月21日 14:24
  • 1950

[leetcode: Python]16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...
  • NXHYD
  • NXHYD
  • 2017年05月18日 16:39
  • 125

LeetCode 016 3Sum Closest

题目 Given an array S of n integers, find three integers in S such that the sum is ...
  • seawade
  • seawade
  • 2014年02月13日 22:46
  • 496

leetcode 16 3Sum Closest

问题https://leetcode.com/problems/3sum-closest/解法class Solution { public: int threeSumClosest(vect...

【leetcode】Array——3Sum Closest(16)

题目: Given an array S of n integers, find three integers in S such that the sum is closest to a gi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:3Sum Closest
举报原因:
原因补充:

(最多只允许输入30个字)