博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 219. Contains Duplicate II
阅读量:4449 次
发布时间:2019-06-07

本文共 1095 字,大约阅读时间需要 3 分钟。

原题链接在这里:

题目:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j]and the absolute difference between i and j is at most k.

题解:

是的进阶版题目,类似题目还有.

建立一个HashMap hm, key是nums[i], value 是 index i.

对于nums[i], 检查它时候在 hm中,若不在,就加<nums[i], i>进去. 

若是nums[i] 在 hm 中,就要看当前的i 和 hm中对应nums[i]的 value 的差值是否比k大:

若是比k 大,说明不符合条件,去掉旧的pair,添加当前pair.

若是不比k大,则return true.

这里熟练几个 HashMap functions: hm.put(key, value); hm.get(key); hm,remove(key): hm.containsKey(key).

Time Complexity: O(n). Space: O(n).

AC Java:

1 public class Solution { 2     public boolean containsNearbyDuplicate(int[] nums, int k) { 3         if(nums == null || nums.length == 0){ 4             return false; 5         } 6         HashMap
hm = new HashMap
(); 7 for(int i = 0; i
k){11 hm.put(nums[i], i);12 }else{13 return true;14 }15 }16 return false;17 }18 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825065.html

你可能感兴趣的文章
UILabel设置富文本格式显示
查看>>
[洛谷P3379]【模板】最近公共祖先(LCA)
查看>>
java程序——随机数求和
查看>>
HTML5的浏览器支持方案
查看>>
在Asp.Net MVC中使用Repeater控件
查看>>
应用程序已被安全设置阻止
查看>>
找球号(一)
查看>>
开发小计(3)
查看>>
[Codevs] 1001 舒适的路线
查看>>
Deep Learning相关
查看>>
MySQL 树形结构 根据指定节点 获取其所有父节点序列
查看>>
hdu_5773_The All-purpose Zero(LIS)
查看>>
流程控制之while循环
查看>>
JSONObject和JSONArray区别及基本用法
查看>>
java多线程例子
查看>>
目标检测网络之 YOLOv3
查看>>
python 使用pyinstaller,pywin32打包.py成.exe应用程序
查看>>
AFNetworking封装思路简析
查看>>
C# 之 批量插入数据到 SQLServer 中
查看>>
Visual Studio使用中的问题
查看>>