leetcode 18.4Sum

1.题目

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)

从一个数组中找到四个数,使这四个数的和为target,返回这四个数。

2.思路 

思路还是跟3sum 一样,先贴上我的代码,有很多的地方可以优化。

class Solution { //192ms
public:
    vector> fourSum(vector& nums, int target) {
        vector> ans;
        int len=nums.size();
        if(len<4) return {};
        sort(nums.begin(),nums.end());
        for(int i=0;i{nums[i],nums[j],nums[head],nums[tail]});
                         do{tail--;} while(nums[tail] == nums[tail+1] && head target)
                    {
                        do{tail--;} while(nums[tail] == nums[tail+1] && head
再贴上disguss中的高票答案,https://leetcode.com/discuss/67417/my-16ms-c-code

class Solution { //16ms
public:
    vector> fourSum(vector& nums, int target) {
        vector> total;
        int n = nums.size();
        if(n<4)  return total;
        sort(nums.begin(),nums.end());
        for(int i=0;i0&&nums[i]==nums[i-1]) continue; //这里,相等的数不重复检索
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;  //如果初始值都大于target,那么之后的肯定找不到了
            if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]i+1&&nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
                if(nums[i]+nums[j]+nums[n-2]+nums[n-1]target) right--;
                    else{
                        total.push_back(vector{nums[i],nums[j],nums[left],nums[right]});
                        do{left++;}while(nums[left]==nums[left-1]&&left



你可能感兴趣的:(leetcode)