創(chuàng)建于20170308
原文鏈接:https://leetcode.com/articles/hash-table/
1 把數(shù)組作為一個容器
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);
}
這里其實是把數(shù)組的索引下標(biāo)作為一個hash值已烤,ASCII 取值范圍0~255。每一個ASCII 都對應(yīng)一個數(shù)字唐片,正好可以作為數(shù)組的下標(biāo)。因此O(1)的時間星持,即可從數(shù)組中定位。
如果是小寫字母逻翁,則26個字母只需要26長度的數(shù)組。通過hash函數(shù)計算出字母對應(yīng)的下標(biāo)缠诅。如:
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實現(xiàn)。