算法分析與設計——LeetCode Problem.18 4Sum

題目鏈接


問題描述


Given an array S of n integers, are there elements abc, 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]
]

解題思路


還是跟Leetcode15題 3Sum類似,這題也是先對數組排序,然後確定兩個數,將確定的第二個數的後一個數作爲頭指針位置,數組最後一個數爲尾指針位置。

但是這題可能會出現四個數組成的vector中的所有元素相同的情況,爲了解決這個問題,可以考慮先用set來存儲vector,最後再把set中的vector轉到vector中。

代碼如下

class Solution {
public:
	vector<vector<int>> fourSum(vector<int>& nums, int target) {
		int leng = nums.size();
		vector<vector<int>> myFourSum;

		set<vector<int>> saveSum;

		if (leng < 4) return myFourSum;
		sort(nums.begin(), nums.end());
		for (int i = 0; i < leng - 3; i++) {
			for (int j = i + 1; j < leng - 2; j++) {
				int left = j + 1, right = leng - 1;
				while (left < right) {
					if (target == nums[i] + nums[j] + nums[left] + nums[right]) {
						vector<int> vec;
						vec.push_back(nums[i]);
						vec.push_back(nums[j]);
						vec.push_back(nums[left]);
						vec.push_back(nums[right]);
						//myFourSum.push_back(vec);
						saveSum.insert(vec);
						left++;
						right--;
						while (left < right && nums[left] == nums[left - 1]) left++;
						while (left < right && nums[right] == nums[right + 1]) right--;
						//at this time might variable j and the variable next to it might be equal
					}
					if (target > nums[i] + nums[j] + nums[left] + nums[right]) {
						left++;
						continue;
					}
					if (target < nums[i] + nums[j] + nums[left] + nums[right]) {
						right--;
						continue;
					}
				}
			}
		}
		set<vector<int>>::iterator it = saveSum.begin();
		for (; it != saveSum.end(); it++) {
			myFourSum.push_back(*it);
		}

		return myFourSum;
	}
};


發佈了42 篇原創文章 · 獲贊 0 · 訪問量 3515
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章