LeetCode18. 4Sum

2sum->3sum->4sum

1. Description

  • 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.

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

2. Hashmap

参考文章

  1. 【算法】2SUM/3SUM/4SUM问题
  2. 2sum,3sum,4sum问题总结
  3. [C++]LeetCode: 71 4Sum && kSum总结

我们使用hashmap, 用空间换时间,先循环两次,找出两个数所有可能的和,存到map里(这里可以unordered_map)。平均时间复杂度为 O ( n 2 ) O(n^2) O(n2), 最差时间复杂度 O ( n 4 ) O(n^4) O(n), 空间复杂度 O ( n 2 ) O(n^2) O(n2)

cpp code :

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;  // the final result
        unordered_map<int, vector<pair<int, int>>> cache;  // using hashmap 
        sort(nums.begin(), nums.end());  // sort nums, attention usage: begin and end pointer
        // store the two sums by using hashmap
        for(int a = 0; a < nums.size(); ++a){
            for(int b = a + 1; b < nums.size(); ++b){
                cache[nums[a] + nums[b]].push_back(make_pair(a, b));
            }
        }
        for(int c = 0; c < nums.size(); ++c){
            for(int d = c + 1; d < nums.size(); ++d){
                const int key = target - nums[c] - nums[d];
                if(!cache.count(key))  // not find the expected value
                    continue;  // loop 
                else{  // find the expected value 
                    const auto& vec = cache[key];  // store the temp value like this [(?, ?), (?, ?), .]
                    for (int k = 0; k < vec.size(); ++k){
                        if ( c > vec[k].second)  // only if the third index > the second index 
                            result.push_back({nums[vec[k].first], 
                                              nums[vec[k].second], nums[c], nums[d]});
                    }
                }
            }
        }
     sort(result.begin(), result.end());  // first sort 
     result.erase(unique(result.begin(), result.end()), result.end());
     return result;   
    }
};

代码说明:

  1. if ( c > vec[k].second) 表示我们的第二个map的比第一个map的下标要大,这样的话我们可以排除重复的元素啦。
  2. result.erase(unique(result.begin(), result.end()), result.end()) 这个代码是去掉相邻重复的元素。
    在这里插入图片描述
    在这里插入图片描述

这里的时间复杂度和空间复杂度都不是很理想,后期可能需要进行优化~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值