LeetCode - 4Sum

来源:互联网 发布:Mac 不能共享文件夹 编辑:程序博客网 时间:2024/05/18 22:41

题目描述:

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

这道题和3Sum类似,固定两个数,然后用两个指针进行扫描,时间复杂度为O(n^3)。

#include<iostream>#include<algorithm>#include<vector>using namespace std;class Solution {public:    vector<vector<int> > fourSum(vector<int>& nums, int target) {sort(nums.begin(),nums.end());vector<vector<int> > result;if(nums.size()<4) return result;for(int i=0;i<nums.size()-3;i++){while(i>0&&nums[i]==nums[i-1]) i++;for(int l=i+1;l<nums.size()-2;l++){while(l>(i+1)&&(nums[l]==nums[l-1])) l++;for(int j=l+1,k=nums.size()-1;j<k;){if((nums[i]+nums[l]+nums[j]+nums[k])==target){cout<<nums[i]<<" "<<nums[l]<<" "<<nums[j]<<" "<<nums[k]<<endl;vector<int> x;x.push_back(nums[i]);x.push_back(nums[l]);x.push_back(nums[j]);x.push_back(nums[k]);result.push_back(x);j++;while(nums[j]==nums[j-1]&&j<k) j++;}else if((nums[i]+nums[l]+nums[j]+nums[k])<target){j++;while(nums[j]==nums[j-1]&&j<k) j++;}else if((nums[i]+nums[l]+nums[j]+nums[k])>target){k--;while(nums[k]==nums[k+1]&&j<k) k--;}}}}        return result;    }};


0 0
原创粉丝点击