[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());
    }
}
相关推荐
To_OC1 小时前
LC 22 括号生成:刷完这道题,我终于搞懂回溯剪枝了
javascript·算法·leetcode
To_OC1 小时前
LC 39 组合总和:回溯入门必刷题,我踩过的两个坑都在这了
javascript·算法·leetcode
兰令水2 小时前
hot100【acm版】【2026.7.14打卡-java版本】
java·数据结构·算法·leetcode·面试
tachibana25 小时前
hot100 课程表(207)
java·数据结构·算法·leetcode
影寂ldy6 小时前
C# 五大加密算法全套实战(AES/DES对称、RSA非对称、MD5/SHA256哈希)
开发语言·c#·哈希算法
旖-旎6 小时前
《LeetCode 646 最长数对链 || LeetCode 1143 最长公共子序列》
c++·算法·leetcode·动态规划
Frostnova丶6 小时前
(15)LeetCode 189. 轮转数组
数据结构·算法·leetcode
伊玛目的门徒18 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
旖-旎21 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
怪兽学LLM1 天前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展