【LeetCode】数组——hashmap的妙用

embedded/2024/9/25 23:23:07/

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

1.两数之和

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. 存在重复元素 

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. 好数对的数目
 

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];}
}


 


http://www.ppmy.cn/embedded/40665.html

相关文章

开源免费的定时任务管理系统:Gocron

Gocron&#xff1a;精准调度未来&#xff0c;你的全能定时任务管理工具&#xff01;- 精选真开源&#xff0c;释放新价值。 概览 Gocron是github上一个开源免费的定时任务管理系统。它使用Go语言开发&#xff0c;是一个轻量级定时任务集中调度和管理系统&#xff0c;用于替代L…

【刷爆力扣之101.对称二叉树-100.相同的树】

101.对称二叉树 1.递归法 递归三部曲 确定递归函数的参数和返回值 因为我们要比较的是根节点的两个子树是否是相互翻转的&#xff0c;进而判断这个树是不是对称树&#xff0c;所以要比较的是两个树&#xff0c;参数自然也是左子树节点和右子树节点。 返回值自然是bool类型…

使用python爬取图片

使⽤ requests 库来获取⽹⻚内容&#xff0c;并⽤ BeautifulSoup 来解析HTML&#xff0c;找到所有图⽚的URL。然后&#xff0c;可以⽤ requests 再次下载这些图⽚并将它们保存到本地。 以下是⼀个简单的图⽚下载器的⽰例代码。这个脚本会下载指定⽹⻚上的所有图⽚到⼀个名为do…

5G NR 吞吐量计算 and 4G LTE 吞吐量计算

5G NR Throughput References • 3GPP TS 38.306 V15.2.0 (2018-06) ➤J : number of aggregated component carriers in a band or band combination ➤Rmax : 948/1024 • For the j-th CC, Vlayers(j) is the maximum number of layers ➤Qm(j) : Maximum modulation orde…

C++类和对象中篇

&#x1f407; &#x1f525;博客主页&#xff1a; 云曦 &#x1f4cb;系列专栏&#xff1a;[C] &#x1f4a8;路漫漫其修远兮 吾将而求索 &#x1f49b; 感谢大家&#x1f44d;点赞 &#x1f60b;关注&#x1f4dd;评论 文章目录 &#x1f4d4;前言&#x1f4d4;1、类的六个…

自动秒收录网址导航分类目录模板

自动秒收录网址导航是一个以html5css3进行开发的免费版网址自动收录模板源码。 模板特点&#xff1a;全站响应式H5网站制作技术&#xff0c;一个网站适应不同终端&#xff0c;模板支持网址导航一键采集入库&#xff0c;免规则文章资讯智能批量采集内置伪原创&#xff0c;本地化…

理解并实现区块链智能合约

理解并实现区块链智能合约是一个涉及多个技术层面的过程。智能合约是自动执行、管理区块链上交易或协议的程序。它们在满足预设条件时自动执行合约条款&#xff0c;从而减少了中间人的需要&#xff0c;并提高了透明度和效率。下面是智能合约的基本概念和实现步骤&#xff1a; …

引入 Redis

简介 Jedis Jedis 是早期的 Redis 的 Java 实现客户端&#xff0c;提供了比较全面的 Redis 命令的支持&#xff0c;其官方网址是&#xff1a;http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.html 优点&#xff1a;支持全面的 Redis 操作特性&#xff0…