Leetcode 219 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 i and j is at most k.

Hash基本操作,纪录每个值对应的位置,然后对于每个新检测到的值,检查该数是否之前已经有在hash中存在的下标,且当前下标与hash中存储的下标差小于k。否则更新hash中的下标。

if(h.hasOwnProperty(nums[i]) && i-h[nums[i]]<=k)

为了防止直接使用 h[nums[i]],使得下标0被判定为false,所以使用h.hasOwnProperty。

var containsNearbyDuplicate = function(nums, k) {
    var h = {}
    for(var i=0;i<nums.length;i++){
        if(h.hasOwnProperty(nums[i]) && i-h[nums[i]]<=k)
            return true
        else
            h[nums[i]] = i
    }
    return false
}

 

posted @ 2015-06-30 10:56  lilixu  阅读(121)  评论(0编辑  收藏  举报