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

16. 3Sum Closest

    My Submissions
Question Editorial Solution
Total Accepted: 76085  Total Submissions: 261853  Difficulty: Medium

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

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
















题目的大概意思是:给定一个数组nums和一个整数target,从数组中找出三个数,使它们的和最接近target,并返回这个和值。

这道题难度等级:中等

思路:

1、与题目3Sum类似,也是先将数组进行排序,然后枚举和夹逼,用minSum来记录最接近target的值;

2、从左往右枚举,枚举位置为i(0,左、右分别用lr来表示,且lr>i,从两边往中间夹逼(这里的中间指的是枚举位置);

3、tmp=nums[l]+nums[i]+nums[r],若abs(tmp-target)<(minSum-target),说明找到个更接近的,要记录下来。并且,若tmp>target,则说明和值偏大,此时--r;若tmp,说明和值偏小,则++l;若tmp==target,说明找到个无偏差的,直接return了。

代码如下:

class Solution {
public:
    int threeSumClosest(vector& nums, int target) {
        sort(nums.begin(), nums.end());
		int minSum = 99999999;
		int l, r, tmp;
		for (int i = 1; i < nums.size() - 1; ++i){
			l = 0;r = nums.size() - 1;
			while(l < i && r > i){
				tmp = nums[l] + nums[i] + nums[r];
				if (tmp == target){return target;}
				(tmp > target) ? (--r) : (++l);
				if (abs(minSum - target) > abs(tmp - target)){
					minSum = tmp;
				}
			}
		}
		return minSum;
    }
};
提交代码后,顺利AC掉该题,Runtime: 12 ms

还有另外一种能AC该题的办法,当然跟上面的差不多,只不过在夹逼的时候,是从中间往两边发散。

代码如下:

class Solution {
public:
	int threeSumClosest(vector& nums, int target) {
		sort(nums.begin(), nums.end());
		int minSum = 99999999;
		int l, r, tmp;
		for (int i = 1; i < nums.size() - 1; ++i){
			l = i - 1;
			r = i + 1;
			while(l >= 0 && r < nums.size()){
				tmp = nums[l] + nums[i] + nums[r];
				if (tmp == target){return target;}
				(tmp > target) ? (--l): ++r;
				if (abs(tmp - target) < abs(minSum - target)){
					minSum = tmp;
				}
			}
		}
		return minSum;
	}
};
Runtime: 16 ms

你可能感兴趣的:(LeetCode,LeedCode)