算法分析与设计——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;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值