LeetCode -- Contains Duplicate II

Question:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

 

Analysis:

给出一个整数数组和一个整数K,找出在K的范围内是否有重复数字。

思路一:刚开始是想用一个滑动窗口,然后在每段窗口内用一个HashMap来判断是否有重复数字,但是后面发现越想情况越多,无法用一个通用的coding解决问题,因此换了一种思路。

思路二:只遍历数组一遍,用HashMap保存key为数组数据,value保存数组下标,当map中出现相同的数字时判断下标范围是否在k之内。

 

Answer:

public class Solution {
   public static boolean containsNearbyDuplicate(int[] nums, int k) {
            if(nums.length == 0 || nums.length == 1)
                return false;
            
            HashMap<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;
                    else
                        map.put(nums[i], i);
                }
                else
                    map.put(nums[i], i);
            }
            return false;
    }
}

 

posted @ 2015-09-18 20:34  江湖小妞  阅读(134)  评论(0编辑  收藏  举报