Java中哈希在算法中的10大經(jīng)典用法
哈希的本質(zhì)是用空間換時間,把查找從 O(n) 降到 O(1) 平均。
HashSet
存不存在 / 去重,用于判斷某元素是否出現(xiàn)過、數(shù)組去重、集合交集
Set<Integer> set = new HashSet<>(); set.add(3); ? ? ? ? ?// 添加元素 set.add(3); ? ? ? ? ?// 重復(fù)元素不會加入 set.contains(3); ? ? // 判斷是否存在 set.remove(3); ? ? ? // 刪除元素
典型題:兩數(shù)之和、數(shù)組去重、判斷重復(fù)元素、兩數(shù)組交集
HashMap
計數(shù) / 映射,用于字符統(tǒng)計、頻率統(tǒng)計、值到索引映射
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
? ? // 如果 n 不存在,默認(rèn)返回 0,然后 +1
? ? map.put(n, map.getOrDefault(n, 0) + 1);
}兩個Integer代表泛型,指key 和 value 都是整數(shù),map.put(n, map.getOrDefault(n, 0) + 1);這行代碼是哈希計數(shù)的經(jīng)典寫法,意思是給n做出現(xiàn)次數(shù)統(tǒng)計。map.getOrDefault(n, 0)去map里取n的值,如果n不存在,就返回默認(rèn)值0map是指數(shù)組)。因為我們要統(tǒng)計出現(xiàn)次數(shù),每遇到一次就加1。map.put(n, ...)代表把更新后的次數(shù)放回map里,如果n原來不存在,會自動創(chuàng)建。
典型題:字母異位詞、出現(xiàn)次數(shù)最多的元素、前綴和 + 哈希、兩數(shù)之和
TreeMap / TreeSet
有序哈希,用于需要自動排序、范圍查詢
Set<Integer> set = new TreeSet<>(); Map<Integer, Integer> map = new TreeMap<>();
基本用法:
TreeSet<Integer> set = new TreeSet<>(); ? ? ? ? set.add(5); ? ? ? ? set.add(3); ? ? ? ? set.add(8); ? ? ? ? set.add(3); // 重復(fù)元素不會加入 ? ? ? ? System.out.println(set); // [3, 5, 8] 自動升序
TreeMap<Integer, String> map = new TreeMap<>();
? ? ? ? map.put(3, "C");
? ? ? ? map.put(1, "A");
? ? ? ? map.put(2, "B");
? ? ? ? map.put(2, "BB"); // key=2 更新 value
? ? ? ? System.out.println(map); // {1=A, 2=BB, 3=C} 自動按 key 排序LinkedHashMap / LinkedHashSet
保序哈希,用于保持插入順序 + 哈希效率
Map<Integer, Integer> map = new LinkedHashMap<>(); Set<Integer> set = new LinkedHashSet<>();
基本用法:
?Set<Integer> set = new LinkedHashSet<>();
? ? ? ? set.add(3);
? ? ? ? set.add(1);
? ? ? ? set.add(5);
? ? ? ? set.add(1); // 重復(fù)元素不會加入
? ? ? ? System.out.println(set); // [3, 1, 5] 插入順序保持
? Map<Integer, String> map = new LinkedHashMap<>();
? ? ? ? map.put(3, "C");
? ? ? ? map.put(1, "A");
? ? ? ? map.put(2, "B");
? ? ? ? map.put(2, "BB"); // key=2 更新 value
? ? ? ? System.out.println(map); // {3=C, 1=A, 2=BB} 插入順序保持哈希在算法中的 10 大經(jīng)典用法
判斷元素是否存在
Set<Integer> set = new HashSet<>();
if (set.contains(x)) {}去重
Set<Integer> set = new HashSet<>();
for (int n : nums) {
? ? set.add(n); ? ?// HashSet 自動去重
}統(tǒng)計頻率
Map<Integer, Integer> map = new HashMap<>(); for (int n : nums) ? ? map.put(n, map.getOrDefault(n, 0) + 1);
字符串計數(shù)(異位詞)
int[] cnt = new int[26]; for (char c : s.toCharArray()) cnt[c - 'a']++;
兩數(shù)之和(值 → 下標(biāo))
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
? ? int need = target - nums[i];
? ? if (map.containsKey(need)) return new int[]{map.get(need), i};
? ? map.put(nums[i], i);
}前綴和 + 哈希(子數(shù)組和為 k)
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int sum = 0, res = 0;
for (int n : nums) {
? ? sum += n;
? ? res += map.getOrDefault(sum - k, 0);
? ? map.put(sum, map.getOrDefault(sum, 0) + 1);
}兩數(shù)組交集
Set<Integer> set = new HashSet<>(); for (int n : nums1) set.add(n); Set<Integer> res = new HashSet<>(); for (int n : nums2) if (set.contains(n)) res.add(n);
判斷重復(fù)元素
Set<Integer> set = new HashSet<>(); for (int n : nums) ? ? if (!set.add(n)) ????????return true;
分組(分類)
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
? ? String key = sort(s);
? ? map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}最近最少使用緩存(LRU)
class LRUCache extends LinkedHashMap<Integer, Integer> {
? ? protected boolean removeEldestEntry(Map.Entry eldest) {
? ? ? ? return size() > capacity;
? ? }
}數(shù)組哈希 vs Map 哈希
當(dāng) key 范圍固定?。ㄈ?a-z):
int[] hash = new int[26]; hash[c - 'a']++;
當(dāng) key 范圍大或不連續(xù):
Map<Integer, Integer> map = new HashMap<>();
總結(jié)
到此這篇關(guān)于Java中哈希在算法中的10大經(jīng)典用法的文章就介紹到這了,更多相關(guān)Java哈希用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA創(chuàng)建Maven項目一直顯示正在加載的問題及解決
這篇文章主要介紹了IDEA創(chuàng)建Maven項目一直顯示正在加載的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
SpringCloud Gateway實現(xiàn)限流功能詳解
SpringCloud Gateway 是 Spring Cloud 的一個全新項目,它旨在為微服務(wù)架構(gòu)提供一種簡單有效的統(tǒng)一的 API 路由管理方式。這篇文章主要介紹了SpringCloud Gateway實現(xiàn)限流,需要的朋友可以參考下2022-11-11
Java通過Modbus簡單實現(xiàn)數(shù)采的示例代碼
本文介紹了Java通過Modbus簡單實現(xiàn)數(shù)采,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-11-11
springboot中@Async默認(rèn)線程池導(dǎo)致OOM問題
這篇文章主要介紹了springboot中@Async默認(rèn)線程池導(dǎo)致OOM問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Java中@RequiredArgsConstructor使用詳解
這篇文章主要介紹了Java中@RequiredArgsConstructor使用的相關(guān)資料,@RequiredArgsConstructor是Lombok庫提供的一個注解,用于自動生成一個包含所有final字段和非空字段的構(gòu)造函數(shù),需要的朋友可以參考下2025-05-05
使用Spring Cache和Redis實現(xiàn)查詢數(shù)據(jù)緩存
在現(xiàn)代應(yīng)用程序中,查詢緩存的使用已經(jīng)變得越來越普遍,它不僅能夠顯著提高系統(tǒng)的性能,還能提升用戶體驗,在這篇文章中,我們將探討緩存的基本概念、重要性以及如何使用Spring Cache和Redis實現(xiàn)查詢數(shù)據(jù)緩存,需要的朋友可以參考下2024-07-07

