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

    https://leetcode.com/problems/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]
    ]

    代码:

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            set<vector<int>> ans;
            int n = nums.size();
            for(int i = 0; i < n - 3; i ++) {
                for(int j = i + 1; j < n - 2; j ++) {
                    int num = nums[i] + nums[j];
                    int find = target - num;
                    int l = j + 1, r = n - 1;
                    while(l < r) {
                        if(nums[l] + nums[r] == find) {
                            ans.insert({nums[i], nums[j], nums[l], nums[r]});
                            while(l < r && nums[l] == nums[l + 1]) l ++;
                            while(l < r && nums[r] == nums[r - 1]) r --;
                        
                            l ++;
                            r --;
                        }
                        else if(nums[l] + nums[r] > find) r --;
                        else l ++;
                    }
                }
            }
            return vector<vector<int>>(ans.begin(), ans.end());
        }
    };

    这个和之前的 3Sum 还有 3Sum Closest 一样的 时间复杂度是 $O(n ^ 3)$ 不知道还有没有更简单的方法 

    emmmm 这个颜色好像芋泥 嘻嘻

  • 相关阅读:
    进程池和线程池
    GIL和互斥锁
    GIL全局解释器锁
    线程锁
    关于迭代器的一些总结
    python在linux上的GUI无法弹出界面
    import Tkinter的时候报错
    检查字符串中的结束标记
    关于模块的使用
    python中pip的安装
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10007343.html
Copyright © 2011-2022 走看看