zoukankan      html  css  js  c++  java
  • 18. 4Sum

    Given an array nums of n integers and an integer target, are there elements abc, and d in nums 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.

    Example:

    Given array nums = [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]
    ]

    AC code:

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            int len = nums.size();
            vector<vector<int>> v;
            if (len < 4) return v;
            sort(nums.begin(), nums.end());
            for (int i = 0; i < len-3; ++i) {
                if (i > 0 && nums[i] == nums[i-1]) continue;
                if (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;
                if (nums[i] + nums[len-1] + nums[len-2] + nums[len-3] < target) continue;
                for (int j = i+1; j < len -2; ++j) {
                    if (j > 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[len-2] + nums[len-1] < target) continue;
                    int left = j + 1;
                    int right = len - 1;
                    while (left < right) {
                        int sum = nums[i] + nums[j] + nums[left] + nums[right];
                        if (sum > target) {
                            right--;
                        } else if (sum < target) {
                            left++;
                        } else {
                            v.push_back(vector<int>{nums[i], nums[j], nums[left], nums[right]});
                            // don't use while statement.
                            do {
                                left++;
                            } while (left < right && nums[left] == nums[left-1]);
                            
                            do {
                                right--;
                            } while (left < right && nums[right] == nums[right+1]);
                        }
                    }
                }
            }
            return v;
        }
    };
    

    Runtime: 20 ms, faster than 75.88% of C++ online submissions for 4Sum.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    python-实现选择排序
    python-实现冒泡排序
    python-实现双端队列
    python-实现队列结构
    python-实现单向循环链表
    类型转换
    uint64_t类型输出为十六进制格式
    python文件的写入与读出
    linux系统中安装虚拟机
    IPv4和IPv6地址的存取
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9738737.html
Copyright © 2011-2022 走看看