[LeetCode]Contains Duplicate II

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])) {
                map.put(nums[i], i);
            } else {
                int pre = map.get(nums[i]);
                if (i - pre <= k) {
                    return true;
                }
                map.put(nums[i], i);
            }
        }
        return false;
    }
}

 

posted @ 2015-12-01 15:48  Weizheng_Love_Coding  阅读(120)  评论(0编辑  收藏  举报