LeetCode 4Sum

4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, abcd)
  • The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)

A naive solution, can only pass small data!
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        //check: num.size()
		vector<vector<int> > ret;
		if(num.size() < 4)
			return ret;
		//sort
		sort(num.begin(), num.end());
		//
		for(int i = 0; i < num.size(); ++i)
			for(int j = i + 1; j < num.size(); ++j)
				for(int k = j + 1; k < num.size(); ++k)
					for(int x = k + 1; x < num.size(); ++x)
					{
						if(target == num[i] + num[j] + num[k] + num[x])
						{
							ret.push_back(vector<int>());
							ret.back().push_back(num[i]);
							ret.back().push_back(num[j]);
							ret.back().push_back(num[k]);
							ret.back().push_back(num[x]);
						}
					}

		sort(ret.begin(), ret.end());
		ret.resize(unique(ret.begin(), ret.end()) - ret.begin());
		return ret;
    }
};


Optimize it! 一次搞定优化的版本。
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        //check: num.size()
		vector<vector<int> > ret;
		if(num.size() < 4)
			return ret;
		//sort
		sort(num.begin(), num.end());
		//
		for(int i = 0; i < num.size(); ++i)
		{
			for(int j = i + 1; j < num.size(); ++j)
			{
				int left = j + 1;
				int right = (int)num.size() - 1;
				int sum = 0;
				while(left < right)
				{
					sum = num[i] + num[j] + num[left] + num[right];
					if(target == sum)
					{
						ret.push_back(vector<int>());
						ret.back().push_back(num[i]);
						ret.back().push_back(num[j]);
						ret.back().push_back(num[left]);
						ret.back().push_back(num[right]);
						++left;
						--right;
					}
					else if(sum > target)
					{
						--right;
					}
					else
					{
						++left;
					}
				}
			}
		}

		sort(ret.begin(), ret.end());
		ret.resize(unique(ret.begin(), ret.end()) - ret.begin());
		return ret;
    }
};





你可能感兴趣的:(c,优化,IE,Class)