代码随想录:四数相加 II

代码随想录:四数相加 II

我还以为会有更快的速度呢。。没想到最佳答案就是n^2

不过值得一提的,这题一开始可能会想到用multiset来解决重复出现的元素,但实际上,multiset的查询速度是logn,是不如用哈希表的,所以用unordered_map,用键值对的值来表示元素出现的次数。

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3,
                     vector<int>& nums4) {
        unordered_map<int, int> a;
        unordered_map<int, int> b;

        int count = 0;

        for (int num1 : nums1) {
            for (int num2 : nums2) {
                auto it = a.find(num1 + num2);
                if (it == a.end()) {
                    a.insert(make_pair(num1 + num2, 1));
                } else {
                    it->second++;
                }
            }
        }

        for (int num3 : nums3) {
            for (int num4 : nums4) {
                int sum = num3+num4;
                auto it = a.find(-sum);
                if(it!=a.end()){
                    count+=it->second;
                }
            }
        }

        return count;
    }
};
posted @ 2024-11-26 22:15  huigugu  阅读(3)  评论(0)    收藏  举报