第1.4節(jié) HASH表

創(chuàng)建于20170308
原文鏈接:https://leetcode.com/articles/hash-table/

1 把數(shù)組作為一個(gè)容器

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í)是把數(shù)組的索引下標(biāo)作為一個(gè)hash值,ASCII 取值范圍0~255。每一個(gè)ASCII 都對(duì)應(yīng)一個(gè)數(shù)字,正好可以作為數(shù)組的下標(biāo)。因此O(1)的時(shí)間,即可從數(shù)組中定位。

如果是小寫(xiě)字母,則26個(gè)字母只需要26長(zhǎng)度的數(shù)組。通過(guò)hash函數(shù)計(jì)算出字母對(duì)應(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實(shí)現(xiàn)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容