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 
#include 
#include 
#include 
using namespace std;
class Solution {
public:
    int fourSumCount(vector& A, vector& B, vector& C, vector& D) {
        sort(A.begin(),A.end());
        sort(B.begin(),B.end());
        sort(C.begin(),C.end());
        sort(D.begin(),D.end());

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

        for (int i=0;i::iterator it =map1.begin();it!=map1.end();it++){
            count+= it->second*(map2[- (it->first)]);
        }
        return count;
    }
};

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

#include   
#include 
#include 
using namespace std;
using namespace __gnu_cxx;


int main(){hash_map mymap;}


关于两个的效率问题

这里有一篇博客

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

你可能感兴趣的:(Acm算法相关)