[Java 算法] 哈希表(1)

练习一 : 两数之和

1. 两数之和 - 力扣(LeetCode)

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

练习二 : 存在重复元素

217. 存在重复元素 - 力扣(LeetCode)

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

练习三 : 存在重复元素 2

219. 存在重复元素 II - 力扣(LeetCode)

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

练习四 : 字母异位词分组

49. 字母异位词分组 - 力扣(LeetCode)

java 复制代码
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> hash = new HashMap<>();
        for(int i = 0;i<strs.length;i++){
            char[] ch = strs[i].toCharArray();
            Arrays.sort(ch);
            String tmp = new String(ch);
            if(!hash.containsKey(tmp)){
                hash.put(tmp,new ArrayList<String>());
            }
            hash.get(tmp).add(strs[i]);
        }
        return new ArrayList<>(hash.values());
    }
}
相关推荐
星星码️14 小时前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
S1998_1997111609•X15 小时前
哈希树阻断正常系统通信工程进行函数钩子解析
安全·百度·缓存·哈希算法·量子计算
Kiyra17 小时前
Agent 的记忆不是存数据库就行:上下文预算与轻量记忆的设计实战
数据库·人工智能·后端·面试·职场和发展·哈希算法
sheeta199818 小时前
LeetCode 每日一题笔记 日期:2026.05.10 题目:2770. 达到末尾下标所需的最大跳跃次数
笔记·算法·leetcode
shehuiyuelaiyuehao19 小时前
算法21,搜索插入位置
python·算法·leetcode
夏日听雨眠19 小时前
数据结构(哈希函数)
数据结构·算法·哈希算法
_深海凉_19 小时前
LeetCode热题100-回文链表
算法·leetcode·链表
小雅痞20 小时前
[Java][Leetcode middle] 54. 螺旋矩阵
java·leetcode·矩阵
pursuit_csdn20 小时前
力扣周赛 501
算法·leetcode·职场和发展
AbandonForce20 小时前
LeetCode 滑动窗口个人思路详解
算法·leetcode·职场和发展