【LeetCode】LeetCode——第18题:4Sum


18. 4Sum

    My Submissions
Total Accepted: 71353  Total Submissions: 300185  Difficulty: Medium

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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)

















题目的大概意思是:给定一个数组nums和一个整数target,在nums中找出四个数,使它们的和为target,找出所有这样的不重复的组合。

这道题难度等级:中等

思路:做法跟Two Sum3 Sum3 Sum Closest类似,也是使用枚举和夹逼。由于是4个数之和,复杂度会高一些O(n^3)

1、先将数组排序(升序),再从第一个数开始枚举,遇到相同的跳过,直到最后一个,用k表示枚举第k个数;

2、从第k个枚举后面的数开始,用i表示后面的数;

3、左右夹逼:lr表示从第i个数开始左右夹逼的下标。

4、在整个枚举和夹逼的过程中l<r始终成立,且要注意跳过一些已经处理过的数,不然会造成结果重复。

代码如下

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
		sort(nums.begin(), nums.end());
		vector<vector<int> > res;
		vector<int> tmp(4, 0);
		int l, r, m;
		for (int k = 0; k < nums.size(); ++k){				//从第1个数开始枚举
			if (k == 0 || nums[k] != nums[k - 1]){			//相同的跳过
				for (int i = k + 1; i < nums.size(); ++i){	//从下一个数开始
					l = i + 1; r = nums.size() - 1;		//左右夹逼
					while (l < r){
						while (l < r && nums[k] + nums[i] + nums[l] + nums[r] > target){--r;}//限制右边界
						if (l < r && nums[k] + nums[i] + nums[l] + nums[r] == target){
							tmp[0] = nums[k]; tmp[1] = nums[i]; tmp[2] = nums[l]; tmp[3] = nums[r];
							res.push_back(tmp);
							while(l < r && nums[l] == tmp[2]){++l;}
						}
						else{++l;}
					}
					m = i;
					while (nums[i] == tmp[1]){
					    m = i++;
					}
					i = m;
				}
			}
		}
		return res;
    }
};
提交代码 ,AC时间为Runtime: 128ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值