优选算法——哈希表

1.哈希表简介

  1. 是什么?存储数据的容器

  2. 有啥用?"快速"查找某个元素

  3. 什么时候用哈希表?频繁的查找某一个数的时候

  4. 怎么用哈希表?

    1. 容器(哈希表)

    2. 用数组模拟简易哈希表

2.两数之和

2.1题目解析

2.2算法原理

解法一:暴力解法

  1. 先固定其中一个数
  2. 一次与该数之前的数相加

解法二:使用哈希表来做优化

2.3代码实现

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> hash=new HashMap<>();// <nums[i],i>
        for(int i=0;i<nums.length;i++){   // 固定一个数
            int x=target-nums[i];
            if(hash.containsKey(x)){
                return new int[]{i,hash.get(x)};
            }
            hash.put(nums[i],i);
        }
        return new int[]{-1,-1};

    }
}

2.判断是否互为字符重排

2.1题目解析

2.2算法原理

解法:利用哈希表

使用数组模拟哈希表,使用两个哈希表,然后判断两个哈希表是否相等即可

优化:只使用一个哈希表

2.3代码实现

java 复制代码
class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        if(s1.length()!=s2.length()) {
            return false;
        }  
        
        int[] hash=new int[26];
        // 先把第一个字符串的信息统计到哈希表中
        for(int i=0;i<s1.length();i++){
            char ch=s1.charAt(i);
            hash[ch-'a']++;
        }
        // 遍历第二个字符串,判断是否可以重排
        for(int i=0;i<s2.length();i++){
            char ch=s2.charAt(i);
            //将哈希表的中值--
            hash[ch-'a']--;
            if(hash[ch-'a']<0){
                return false;
            }
        }
        return true;
    }
}

3.存在重复元素I

3.1题目解析

3.2算法原理

解法:哈希表(同两数之和)

3.3代码实现

java 复制代码
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> hash=new HashSet<>();
        for(int x:nums){
            if(hash.contains(x)) return true;
            hash.add(x);
        }
        return false;
    }
}

4.存在重复元素II

4.1题目解析

4.2算法原理

解法:哈希表

4.3代码实现

java 复制代码
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,Integer> hash=new HashMap<>();// nums[i],i
        for(int i=0;i<nums.length;i++){
            if(hash.containsKey(nums[i])){
                int index=hash.get(nums[i]);
                if((i-index)<=k) return true;
            }
            hash.put(nums[i],i);
        }
        return false;


    }
}

5.字母异位词

5.1题目解析

5.2算法原理

解法:哈希表

  1. 判断两个字符串是否是异位词 -->排序
  2. 如何分组

5.3代码实现

java 复制代码
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> hash = new HashMap<>();

        // 1. 先把所有的字母异位词分组
        for (String s : strs) {
            char[] tmp = s.toCharArray(); // 将字符串转为字符数组
            Arrays.sort(tmp);             // 排序字符数组
            String key = new String(tmp); // 排序后的字符串作为 key

            if (!hash.containsKey(key)) { // 如果 key 不存在,初始化一个空列表
                hash.put(key, new ArrayList<>());
            }

            List<String> list= hash.get(key);
            list.add(s); // 将原始字符串 s 加入对应 key 的列表中
        }

        // 2. 提取结果
        return new ArrayList(hash.values());
    }
}

5.4模拟执行过程

输入: strs = "eat", "tea", "tan", "ate", "nat", "bat"

输出: \["bat","nat","tan","ate","eat","tea"]

  1. 初始化 hash={} (空哈希表)
  2. 遍历第一个字符串 "eat"
    1. s = "eat"
    2. tmp = ['e', 'a', 't']
    3. Arrays.sort(tmp) 后,tmp = ['a', 'e', 't']
    4. key = "aet"
    5. 检查 hash 是否包含 "aet":不包含。
    6. 初始化:hash.put("aet", new ArrayList<>()) → hash = {"aet": []}
    7. 将 "eat" 加入列表:hash.get("aet").add("eat") → hash = {"aet": ["eat"]}
  3. 遍历第二个字符串 "tea"
    1. s = "tea"
    2. tmp = ['t', 'e', 'a'] → 排序后 ['a', 'e', 't']
    3. key = "aet"
    4. 检查 hash 是否包含 "aet":包含。
    5. 直接取列表并添加:hash.get("aet").add("tea") → hash = {"aet": ["eat", "tea"]}
  4. 遍历第三个字符串
    1. s = "tan"
    2. tmp = ['t', 'a', 'n'] → 排序后 ['a', 'n', 't']
    3. key = "ant"
    4. 检查 hash 是否包含 "ant":不包含。
    5. 初始化:hash.put("ant", new ArrayList<>()) → hash = {"aet": ["eat", "tea"], "ant": []}
    6. 添加:hash.get("ant").add("tan") → hash = {"aet": ["eat", "tea"], "ant": ["tan"]}
  5. 遍历第四个字符串
    1. s = "ate"
    2. tmp = ['a', 't', 'e'] → 排序后 ['a', 'e', 't']
    3. key = "aet"
    4. 包含 "aet",添加:hash.get("aet").add("ate") → hash = {"aet": ["eat", "tea", "ate"], "ant": ["tan"]}
  6. 遍历第五个字符串
    1. s = "nat"
    2. tmp = ['n', 'a', 't'] → 排序后 ['a', 'n', 't']
    3. key = "ant"
    4. 包含 "ant",添加:hash.get("ant").add("nat") → hash = {"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"]}
  7. 遍历第六个字符串
    1. s = "bat"
    2. tmp = ['b', 'a', 't'] → 排序后 ['a', 'b', 't']
    3. key = "abt"
    4. 不包含 "abt",初始化并添加:hash = {"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"], "abt": ["bat"]}
  8. 提取结果
    1. hash.values() 得到三个列表:
      • ["eat", "tea", "ate"]
      • ["tan", "nat"]
      • ["bat"]
    2. 将它们放入一个新的 ArrayList 中,顺序可能因哈希表实现略有不同,但内容一致。
  9. 最终输出: [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]] (或任意顺序的分组组合)
相关推荐
BK贝壳42 分钟前
初始化一亿个全 True 或全 False:bool-hybrid-array 的 TruesArray/FalsesArray 占位构造本机实测
开发语言·数据结构·python·性能优化·numpy
郝学胜-神的一滴1 小时前
Effective STL 条款 17:用 swap 技巧去掉多余容量
c语言·开发语言·数据结构·c++·算法·rpc
傲世仙尊3 小时前
环形链表找入环点-从相遇到等距的最后一推
数据结构·链表
我是伪码农6 小时前
11.21程序设计
数据结构·算法
羊在吃青草7 小时前
C语言之数组
c语言·数据结构
灯澜忆梦7 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
专注仿真8 小时前
达梦数据库 SQL 优化实战:从执行计划到索引、统计信息与参数调优
数据结构·数据库·数据库开发·数据库架构
Shaoshing8 小时前
LeetCode100 155.最小栈
java·数据结构·算法
杜 硕9 小时前
从零开始的C++生活——第十六讲
开发语言·数据结构·c++·生活