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

/*
leetcode 16. 3Sum Closest
时间复杂度: N^2
该题如果用暴力搜索,三重循环,时间复杂度是N^3,这样很可能
会超时,所以考虑先排序所有的元素,然后对三个变量也按照一定
的前后顺序排列,有方向的搜索解(三个元素的和比较target来确定
搜索方向)
*/

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int a=0,b=0,c=0;
		int sum=nums[0]+nums[1]+nums[2];
        sort(nums.begin(),nums.end());
		for(a=0;a<nums.size()-2;a++)
		{
			b=a+1;
			c=nums.size()-1;
			while(b<c)
			{
				if(abs(target-sum)>abs(target-(nums[a]+nums[b]+nums[c])))
					sum=nums[a]+nums[b]+nums[c];
				if(nums[a]+nums[b]+nums[c]>target)
					c--;
				else
					b++;
			}
		}
		return sum;
    }
};


int main() {
	int a[]={0,0,0};
	vector<int> nums(a,a+sizeof(a)/sizeof(int));
	for(int i=0;i<nums.size();i++)
		cout<<nums[i]<<" ";
	cout<<endl;
	int target=1;
	Solution s;
	cout<<s.threeSumClosest(nums,target);
	getchar();
	return 0;
}



原文地址:https://www.cnblogs.com/gremount/p/5768003.html