Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

题目和15题的要求几乎一样,只不过是4Sum.
思路和15题一模一样,但仍要注意去重.

自己思路:

有了3sum的经验这个就好做了,思想和3sum没有区别
先排序;
固定i, 固定j, move lo and hi;
We'll come across 3 cases(sum == ta, sum > ta, sum < ta) and deal with them.

自己代码:
\(O(n^3)\) time, \(O(1)\) extra space.

vector<vector<int>> fourSum(vector<int>& A, int ta) {
	const int n = A.size();
	vector<vector<int>> res;
	sort(A.begin(), A.end());

	// 有了3sum的经验这个就好做了,思想和3sum没有区别
	// 固定i, 固定j, move lo and hi
	// we'll come across 3 cases(sum==ta, sum>ta, sum<ta) and deal with them
	for (int i = 0; i < n - 3; i++) {
		if (i > 0 && A[i] == A[i - 1]) continue; //去重
		for (int j = i + 1; j < n - 2; j++) {
			if ((j > i + 1) && (A[j] == A[j - 1])) continue; //去重
			int lo = j + 1, hi = n - 1;

			while (lo < hi) {// lo <= hi 不可以
				int sum = A[i] + A[j] + A[lo] + A[hi];
				if (sum == ta) {
					
					res.push_back({A[i], A[j], A[lo], A[hi]});

					while (lo < hi && A[hi] == A[hi - 1]) hi--; //去重
					while (lo < hi && A[lo] == A[lo + 1]) lo++; //去重
					lo++; // 只有lo++或 只有hi--也可 他俩都没有就无限循环了
					hi--;

				} else if (sum > ta) {
					while (lo < hi && A[hi] == A[hi - 1]) hi--; //去重
					hi--;
				} else { // sum < ta
					while (lo < hi && A[lo] == A[lo + 1]) lo++; //去重
					lo++;
				}
			}
		}
	}
	return res;
}
posted on 2017-08-22 12:12  英雄与侠义的化身  阅读(95)  评论(0编辑  收藏  举报