您的位置:首页 > 大数据 > 人工智能

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代码如下:
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;
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: