【LeetCode】数组——hashmap的妙用

在遇到一类题目时,通过双for循环也可暴力破解,但我们可以通过用hashmap来代替一次for循环节约时间开支,在算法上属于用空间换时间,也能帮助我们更好的理解hashmap这一种重要数据结构,并熟悉hashmap的重要方法。

1.两数之和

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}

两数之和hashtable.containsKey更像一次隐藏的for循环

219. 存在重复元素219. 存在重复元素

java 复制代码
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; ++i){
        if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k){
            return true;
        }
        map.put(nums[i], i);
    }
    return false;
    }
}

1512. 好数对的数目

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}
相关推荐
I_LPL4 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱5 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073215 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_831824966 小时前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you7 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018727 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563247 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920748 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703318 小时前
上机练习第51天
数据结构·c++·算法
ArturiaZ8 小时前
【day60】
算法·深度优先·图论