两种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内存占用最少