[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());
    }
}
相关推荐
文丑颜不良啊9 小时前
LeetCode3041~3060题目解析
java·leetcode
文丑颜不良啊10 小时前
LeetCode3101~3120题目解析
java·leetcode
牢姐与蒯15 小时前
cpp算法之哈希
c++·算法·哈希算法
玄昌盛不会编程17 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊18 小时前
LeetCode3061~3080题目解析
java·leetcode
文丑颜不良啊20 小时前
LeetCode3081~3100题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2981~3000题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode3001~3020题目解析
java·leetcode
Pniubi2 天前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode2761~2780题目解析
java·leetcode