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; } }
学习之处:
- 在数组里面的坐标问题可以考虑用hashtable进行存储,用空间换时间是一个常用的策略。