【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];
    }
}
相关推荐
稚南城才子,乌衣巷风流2 小时前
ST 表(Sparse Table)算法详解:原理、实现与应用
算法
hold?fish:palm2 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle2 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木2 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
不会就选b3 小时前
算法日常・每日刷题--<归并排序>1
数据结构·算法
危桥带雨3 小时前
排序算法(快排、归并、计数、基数排序)
数据结构·算法·排序算法
啦啦啦啦啦zzzz3 小时前
算法:回溯算法
c++·算法·leetcode
IT探索3 小时前
Linux 查找文件指令总结
linux·算法
攻城狮Soar3 小时前
C++子类访问父类成员
c++·算法