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

Contains Duplicate II

2015-05-31 21:33 429 查看
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.

思路:

 hash表

我的代码:

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums==null || nums.length==0 || k<0 ) return false;
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++)
{
if(hash.containsKey(nums[i]))
{
if(i-hash.get(nums[i]) <= k) return true;
hash.put(nums[i], i);
}
else
hash.put(nums[i], i);
}
return false;
}
}


View Code
学习之处:

在数组里面的坐标问题可以考虑用hashtable进行存储,用空间换时间是一个常用的策略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: