[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());
    }
}
相关推荐
语戚1 小时前
力扣 3161. 块放置查询:线段树解法(Java 实现)
java·算法·leetcode·面试·线段树·力扣·
8Qi83 小时前
LeetCode 23. 合并 K 个升序链表 —— 小顶堆(PriorityQueue)
数据结构·算法·leetcode·链表·
Lsk_Smion5 小时前
力扣实训 _ [200].岛屿数量
算法·leetcode·深度优先
Lsk_Smion6 小时前
力扣实训 _ [543].二叉树的直径 _ [23].合并K个升序列表
数据结构·算法·leetcode
凯瑟琳.奥古斯特7 小时前
力扣1235:加权区间调度最优解
java·python·算法·leetcode·职场和发展
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题 第89题】【Mysql篇】第19题:Hash 索引和 B+ 树索引的区别?它们在使用方面的区别?
java·数据库·mysql·面试·哈希算法
memcpy08 小时前
LeetCode 2144. 打折购买糖果的最小开销【贪心】
算法·leetcode·职场和发展
散峰而望10 小时前
【算法练习】算法练习精选:陶陶摘苹果(基础+升级)、Music Notes、字串变换,你能AC几道?
数据结构·c++·算法·leetcode·贪心算法·github·动态规划
8Qi810 小时前
LeetCode 148. 排序链表 —— 解法一:自顶向下递归(分治 + 归并)
数据结构·算法·leetcode·链表·递归·分治·归并
菜菜的顾清寒11 小时前
力扣HOT100(50)动态规划-零钱兑换
算法·leetcode·动态规划