Contains Duplicate II
2015-06-05 22:52
239 查看
https://leetcode.com/problems/contains-duplicate-ii/
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
解题思路:
简单的新题,在前题 Contains Duplicate 的基础上,用map来记录数字对应的index。遇到map中有的数字就去比较他们的下标,小于等于k就返回true,否则更新下标。
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
解题思路:
简单的新题,在前题 Contains Duplicate 的基础上,用map来记录数字对应的index。遇到map中有的数字就去比较他们的下标,小于等于k就返回true,否则更新下标。
public 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])) { if(i - map.get(nums[i]) <= k) { return true; } } map.put(nums[i], i); } return false; } }
相关文章推荐
- windows内核情景分析之—— KeRaiseIrql函数与KeLowerIrql()函数
- 严重: StandardServer.await: create[8005]:
- WorldWind源码剖析系列:地形访问器类TerrainAccessor
- WorldWind源码剖析系列:地形瓦片类TerrainTile和地形瓦片服务类TerrainTileService
- RAID
- pthread_cond_wait
- 端口状态说明 LISTENING、ESTABLISHED、TIME_WAIT及CLOSE_WAIT
- Opencv研习笔记:haartraining程序之cvCreateCARTClassifier函数详解(CART树状弱分类器创建)
- NSSearchPathForDirectoriesInDomains用法(转)
- OnPaint()中图片绘制位置的选择
- VC编译错误: Nafxcwd.lib(dllmodul.obj) : error LNK2005: _DllMain@12已经在dllmain.obj 中定义
- X-Cache and X-Cache-Lookup headers explained
- aix学习笔记
- 在Flex中用Validator检测数字、字符串、Email、电话号码等 .
- MongoDB assertion: 18 { code: 18, ok: 0.0, errmsg: "auth fails" }
- MongoDB assertion: 18 { code: 18, ok: 0.0, errmsg: "auth fails" }
- 关于 wait_event_interruptible() 和 wake_up()的使用
- leetcode--Climbing Stairs
- 修复 FLASHMAIL 只能发不能收的问题
- JetBrain WebStorm 注册码