[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());
    }
}
相关推荐
nianniannnn2 小时前
力扣 3.无重复字符的最长子串
c++·算法·leetcode
不吃蘑菇!4 小时前
LeetCode Hot 100-1(两数之和)
java·数据结构·算法·leetcode·哈希表
老四啊laosi5 小时前
[双指针] 4. 力扣--盛最多水的容器
算法·leetcode·装水最多的容器
XiYang-DING6 小时前
【LeetCode】206. 反转链表
算法·leetcode·链表
wangchunting6 小时前
数据结构-散列表
java·数据结构·散列表
_深海凉_6 小时前
LeetCode热题100-合并两个有序链表
算法·leetcode·链表
会编程的土豆6 小时前
【leetcode hot 100】依旧二叉树
算法·leetcode·职场和发展
浅念-7 小时前
LeetCode 双指针题型 C++ 解题整理
开发语言·数据结构·c++·笔记·算法·leetcode·职场和发展
Mr_Xuhhh7 小时前
LeetCode hot 100(C++版本)
c++·leetcode·哈希算法