zoukankan      html  css  js  c++  java
  • 18. 4Sum -- 找到数组中和为target的4个数

    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]
    ]
    
    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            int l = nums.size(), sum, left, right, i, j;
            vector<vector<int>> ans;
            if (l<4)
                return ans;
            sort(nums.begin(), nums.end());
            for (i = 0; i<l - 3; i++)
            {
                if(i && nums[i] == nums[i-1])
                    continue;
                for (j = i + 1; j<l - 2; j++)
                {
                    if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)
                        break;
                    if(nums[i]+nums[j]+nums[l-2]+nums[l-1]<target)
                        continue;
                    if (j>i + 1 && nums[j] == nums[j - 1])
                        continue;
                    sum = nums[i] + nums[j];
                    left = j + 1;
                    right = l - 1;
                    while (left < right)
                    {
                        if (sum + nums[left] + nums[right] == target)
                            ans.push_back({ nums[i], nums[j], nums[left++], nums[right--] });
                        else if (sum + nums[left] + nums[right] < target)
                            left++;
                        else
                            right--;
                        while (left>j+1 && nums[left] == nums[left - 1])
                            left++;
                        while(right<l-1 && nums[right] == nums[right + 1])
                            right--;
                    }
                }
            }
            return ans;
        }
    };
  • 相关阅读:
    理解AI的角度
    如何提升分享信息的价值
    大数据和你想的不一样
    《卓有成效的程序员》笔记
    Mac下安装和使用GunPG(GPG)
    hive界面工具SQL Developer的安装;使用sql developer连接hive;使用sql developer连接mysql
    mac os安装jdk、卸载
    前端模板inspinia
    squirrelsql安装
    GOPATH设置
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5804043.html
Copyright © 2011-2022 走看看