Contains Duplicate II
2015-07-01 18:57
627 查看
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.题目大意是:在一个数组中是否存在nums[i]==nums[j](假设i<j),且j-i<=k思路和以前有个题目类似,借助HashMap来保存nums[i]和i,这样后面判断是否重复出现的只需查找map即可。如果重复出现,那就查键对应的值之差是否小于等于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.题目大意是:在一个数组中是否存在nums[i]==nums[j](假设i<j),且j-i<=k思路和以前有个题目类似,借助HashMap来保存nums[i]和i,这样后面判断是否重复出现的只需查找map即可。如果重复出现,那就查键对应的值之差是否小于等于k代码如下:
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(nums[i])){ int j = map.get(nums[i]); if(i-j<=k){ return true; }else{ //i-j>k //移除之前的,接着执行13行代码,把第二次重复出现的数的位置保存map中 //作为新的键值对 map.remove(nums[i]); } } map.put(nums[i],i); } return false; } }
相关文章推荐
- 数据挖掘十大经典算法学习之Naive Bayes朴素贝叶斯
- 如何使用KeyChain保存和获取UDID
- 慎用ArrayList的contains方法,使用HashSet的contains方法代替
- BaiduMap---百度地图官方Demo之多地图展示(在一个Activity中创建多个地图展示)
- BaiduMap---百度地图官方Demo之MapFragment使用(创建一个基于Fragment的地图框架)
- BaiduMap---百度地图官方Demo之基本地图功能(创建一张百度地图并管理地图的生命周期)
- Rails应用开发点滴
- SAP BW – Implementing Delta Updates in the Financial Domain
- BaiduMap---百度地图官方Demo
- leetcode Submission Details
- Obtain Diesel engine Designer watches can be bought in the many most up-to-date styles and designs
- svn:cleanup failed previous operation has not finished; run cleanup if it was interrupted
- svn:cleanup failed previous operation has not finished; run cleanup if it was interrupted
- windows安装Apache,注册服务出现“(OS 5)拒绝访问。 : AH00369: Failed to open the WinNT service manager..."错误 [转]
- xcode6错误提醒:Failed to code sign "某某Tests".
- svn cleanup failed-previous operation has not finished; run cleanup if it was interrupted
- Matrix-chain product 矩阵链乘积
- main函数总结
- 扎克伯格:我们为何要研究人工智能和虚拟现实
- 扎克伯格:我们为什么要研究人工智能与虚拟现实?