zoukankan      html  css  js  c++  java
  • [leetcode-18-4Sum]

    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.
    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求和,然后在过程中及时约束,判断是否可以提前跳出循环来优化。

    vector<vector<int>> fourSum(vector<int>& nums, int target)
        {
            vector<vector<int>>result;
            const int size = nums.size();
            if (size < 4) return result;
            sort(nums.begin(), nums.end());
            vector<int>temp;
            for (int i = 0; i < size - 3; i++)
            {
                if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;//及时跳出循环
                if (nums[i] + nums[size - 3] + nums[size - 2] + nums[size - 1] < target)continue;
                
                for (int j = i + 1; j < size-2; j++)
                {
                    if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;//及时跳出循环
                    if (nums[i] + nums[j] + nums[size - 2] + nums[size - 1] < target)continue;
                     
                    int left = j + 1;
                    int right = size - 1;
                    while (left < right)
                    {
                        int sum = nums[i] + nums[j] + nums[left] + nums[right];
                        if (sum < target)left++;
                        else if (sum > target) right--;
                        else
                        {
                            temp = {nums[i],nums[j],nums[left],nums[right]};//新学一招,类似数组赋值
                            result.push_back(temp);
                            while (left < right && nums[left] == temp[2])left++;
                            while (left < right && nums[right] == temp[3])right--;
                        }         
                    }
                    while (j + 1 < size && nums[j + 1] == nums[j])j++;
                }
                while (i + 1 < size && nums[i + 1] == nums[i])i++;
            }
            return result;
        }

    参考:

    http://cs-cjl.com/2016/07_04_leetcode_18_4sum

  • 相关阅读:
    Leetcode100.相同的树
    Leetcode53. 最大子序列和
    Leetcode35. 搜索插入位置
    Leetcode27.移除元素
    Leetcode 26. 删除排序数组中的重复项
    Leetcode. 1290 二进制链表转整数
    Leetcode.234 回文链表
    Leetcode206.反转链表
    课本 求素数
    循环法求素数 1306 循环求素数10.1.5.253 ====== 1313 筛选法求素数10.1.5.253
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6531103.html
Copyright © 2011-2022 走看看