hash_map unordered_map 两种哈希函数用法 leetcode454

两种hash函数第一个支持的不好,有些oj不支持,比如leetcode

用法和stl的map是一样的

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
思路就是枚举前面两个加法用hashmap存起来,后面两个也一样,然后利用hashmap判断是否存在

#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/unordered_map.hpp>
using namespace std;
class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        sort(A.begin(),A.end());
        sort(B.begin(),B.end());
        sort(C.begin(),C.end());
        sort(D.begin(),D.end());

        unordered_map<int,int> map1;
        unordered_map<int,int> map2;
        int la,lb,lc,ld;
        la=A.size();
        lb=B.size();
        lc=C.size();
        ld=D.size();

        for (int i=0;i<la;i++){
            for (int j=0;j<lb;j++){
                map1[A[i]+B[j]]++;
            }
        }
        for (int i=0;i<lc;i++){
            for (int j=0;j<ld;j++){
                map2[C[i]+D[j]]++;
            }
        }
        
        int count=0;
        for (unordered_map<int,int>::iterator it =map1.begin();it!=map1.end();it++){
            count+= it->second*(map2[- (it->first)]);
        }
        return count;
    }
};

然后如果是hashmap的话,用法如下: 插入和遍历都和上面的一样

#include <ext/hash_map>  
#include <list>
#include <map>
using namespace std;
using namespace __gnu_cxx;


int main(){hash_map<int,int> mymap;}


关于两个的效率问题

这里有一篇博客

结论是unordered_map最快,hash_map内存占用最少

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值