18. 4Sum

作者: yunmengze | 来源:发表于2018-09-16 23:22 被阅读0次

Given an array nums of n integers and an integer target, are there elements a, b, c, 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.


使用三重for循环,在最后一层使用哈希表,复杂度为O(n^3),为了避免重复的解,使用set存储得到的vector

class Solution {
public:
    vector<vector<int> > fourSum(vector<int>& nums, int target) {
        int len = nums.size();
        set<vector<int>> data;
        unordered_map<int, int> data_map;
        sort(nums.begin(), nums.end());
        for(int i=0;i<len;i++){
            data_map[nums[i]] = i;
        }
        for(int i = 0; i < len-3; i++){
            for(int j=i+1; j<len-2; j++){
                for(int k=j+1; k<len-1; k++)
                {
                    int findNum = target - nums[i] - nums[j] - nums[k];
                    if(data_map.find(findNum) != data_map.end() && data_map[findNum] > k){
                        vector<int> temp = {nums[i], nums[j], nums[k], findNum};
                        data.insert(temp);
                    }
                }
            }
        }
        return vector<vector<int>>(data.begin(), data.end());
    }
};

相关文章

  • LeetCode #18 2018-07-28

    18. 4Sum Given an array nums of n integers and an integer...

  • 力扣每日一题:18.四数之和

    18.四数之和 https://leetcode-cn.com/problems/4sum/[https://le...

  • 18.四数之和

    18.四数之和 题目链接:https://leetcode-cn.com/problems/4sum/[https...

  • leetcode 18. 4Sum

    leetcode 18. 4Sum 题目,但是其解题思路可以延伸到 ksum 参考:1 ksum

  • 18. 4Sum

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum

    Description Given an array S of n integers, are there ele...

  • 18. 4Sum

    在3Sum基础上,固定第一个数对剩下的数进行3Sum计算,复杂度为O(n^3)

  • 18. 4Sum

    题目描述:给定一个有n个整数的数组S和目标值target,找到其中所有由四个数a、b、c、d组成,使得a + b ...

  • 18. 4Sum

    题目 Given an array S of n integers, are there elements a, ...

网友评论

      本文标题:18. 4Sum

      本文链接:https://www.haomeiwen.com/subject/napqnftx.html