【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];
    }
}
相关推荐
寂静山林1 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway1 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No72 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区2 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫2 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****2 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者3 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶
程序员大雄学编程4 小时前
「深度学习笔记4」深度学习优化算法完全指南:从梯度下降到Adam的实战详解
笔记·深度学习·算法·机器学习
小O的算法实验室4 小时前
2022年ASOC SCI2区TOP,基于竞争与合作策略的金字塔粒子群算法PPSO,深度解析+性能实测,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
南莺莺5 小时前
邻接矩阵的基本操作
数据结构·算法··邻接矩阵