[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());
    }
}
相关推荐
Navigator_Z7 小时前
LeetCode //C - 1250. Check If It Is a Good Array
c语言·算法·leetcode
圣保罗的大教堂13 小时前
leetcode 3483. 不同三位偶数的数目 简单
leetcode
mmmmath_313 小时前
LeetCode.018.四数之和
数据结构·算法·leetcode
圣保罗的大教堂16 小时前
leetcode 836. 矩形重叠 简单
leetcode
土司大王16 小时前
LeetCode hot100——394.字符串解码:Java 双栈模拟
java·算法·leetcode
a1879272183116 小时前
【算法】双指针与滑动窗口(三):相向双指针——比较、排除、收缩
算法·leetcode·双指针·滑动窗口·原理·相向双指针·算法讲解
数据知道16 小时前
LDAP 与 AD 安全深度剖析——注入、弱绑定、权限配置错误
网络安全·密码学·哈希算法
6Hzlia17 小时前
【Classic 150 刷题计划】 LeetCode 14. 最长公共前缀 | C++ 纵向扫描法与防越界细节
c++·算法·leetcode
Tisfy1 天前
LeetCode 0836.矩形重叠:xy两方向分别看
数学·leetcode·题解·模拟
青山木1 天前
Hot 100 --- 最长递增子序列
java·数据结构·算法·leetcode·动态规划