第1.4节 HASH表
2017-03-08 本文已影响0人
比特阳
创建于20170308
原文链接:https://leetcode.com/articles/hash-table/
1 把数组作为一个容器
private static void printFreq(char[] str) {
int[] freq = new int[256];
for (int i = 0; i < str.length; i++) {
freq[str[i]]++;
}
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
System.out.println("[" + (char)(i) + "] = " + freq[i]);
}
}
}
public static void main(String[] args) {
char[] str = "Hello world".toCharArray();
printFreq(str);
}
这里其实是把数组的索引下标作为一个hash值,ASCII 取值范围0~255。每一个ASCII 都对应一个数字,正好可以作为数组的下标。因此O(1)的时间,即可从数组中定位。
如果是小写字母,则26个字母只需要26长度的数组。通过hash函数计算出字母对应的下标。如:
index=str[i] - 'a'
2 使用HASH表
A better method is to use a hash table, in Java it's called HashMap, in C++ it's called unordered_map, and in Python it's called dict.
我一般用python的dict实现。