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 这个颜色好像芋泥 嘻嘻

  • 相关阅读:
    echarts圆套圆
    两个对象深度比较,借鉴,记录
    js异步加载的方式
    elementUI使用el-card高度自适应
    如何在页面上实现一个圆形的可点击区域
    清除浮动
    水平垂直居中的几种方式
    BFC原理
    正则表达式
    Vue项目中难点问题
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10007343.html
Copyright © 2011-2022 走看看