leetcode 016 —— 3Sum Closest

原创 2015年07月09日 10:04:48

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).
思路:设定closest,closest与target差值最小,类似贪心算法

class Solution {
public:
	int threeSumClosest(vector<int>& nums, int target) {
		int n = nums.size();
		if (n < 3) return 0;
		int closest = nums[0]+nums[1]+nums[2];
		sort(nums.begin(), nums.end());
		for (int i = 0; i < n-2; i++){
			if (i>0 && nums[i] == nums[i - 1])
				continue;
			int l = i + 1;
			int r = n - 1;
			while (l < r){
				int sum = nums[i] + nums[l] + nums[r];
				if (sum == target)
					return sum;
				else if(sum>target){
					closest = (abs(closest - target) < abs(sum - target) ? closest : sum);
					r--;					
				}
				else{
					closest = (abs(closest - target) < abs(sum - target) ? closest : sum);
					l++;
				}
			}
		}
		return closest;
	}
};



相关文章推荐

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
  • 478

【LeetCode-面试算法经典-Java实现】【016-3 Sum Closest(最接近的三个数的和)】

【016-3 Sum Closest(最接近的三个数的和)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given an array S of n integers, ...

LeetCode刷题(C++)——3Sum Closest(Medium)

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

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

【LeetCode】LeetCode——第16题:3Sum Closest

【LeetCode】LeetCode——第16题:3Sum Closest

LeetCode——3Sum & 3Sum Closest

3Sum 先对数组进行非递减排序, 确定一个数i,在对其后面的序列使用 左右游标p,q夹逼(PS:这个词确实有点)。 对num[i],num[p],num[q]三者的和sum 进行判断。 如...

LeetCode OJ算法题(十六):3Sum Closest

题目: Given an array S of n integers, find three integers in S such that the sum is closest to a ...
  • op_yu
  • op_yu
  • 2014年07月16日 20:46
  • 303

LeetCode16: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

16 . 3Sum Closest

[LeetCode] 3Sum Closest 最近的三数之和 Python

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

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