• 18. 4Sum


    Problem statement:

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

    Solution:

    No, it is the 4sum problem, more dimension than 3sum. But, they are the same idea.

    Time complexity O(n * n * n)

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            // divide it into two sum problem
            int size = nums.size();
            vector<vector<int>> quadruplets;
            sort(nums.begin(), nums.end());
            for(int i = 0; i < size - 3; i++){
                for(int j = i + 1; j < size - 2; j++){
                    int left = j + 1;
                    int right = size - 1;
                    while(left < right){
                        if(nums[i] + nums[j] + nums[left] + nums[right] == target){
                            quadruplets.push_back({nums[i], nums[j], nums[left], nums[right]});
                            while(left < right && nums[right - 1] == nums[right]){
                                right--;
                            }
                            right--;
                            while(left < right && nums[left] == nums[left + 1]){
                                left++;
                            }
                            left++;
                        } else if (nums[i] + nums[j] + nums[left] + nums[right] > target) {
                            while(left < right && nums[right - 1] == nums[right]){
                                right--;
                            }
                            right--;
                        } else {
                            while(left < right && nums[left] == nums[left + 1]){
                                left++;
                            }
                            left++;
                        }
                    }
                    while(j + 1 < size && nums[j] == nums[j + 1]){
                        j++;
                    }
                }
                while(i + 1 < size && nums[i] == nums[i + 1]){
                    i++;
                }
            }
            return quadruplets;
        }
    };
  • 相关阅读:
    登乐游原
    遇到Tomcat端口占用怎么办
    tensorflow cnn+rnn基本结构
    linux bash 入门
    python 装饰器
    php 后端开发学习
    图像增强方法
    git 使用
    斯坦福机器学习课程笔记
    django学习笔记
  • 原文地址:https://www.cnblogs.com/wdw828/p/6883932.html
Copyright © 2020-2023  润新知