AC --Java using HashMap


  • -2
    H

    public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
    if(nums==null||nums.length<=1||k<=0)
    return false;
    HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
    int n=nums.length;
    for(int i=0;i<n;i++){
    if(map.get(nums[i])==null)
    map.put(nums[i],i);
    else{
    if(i-map.get(nums[i])<=k)
    return true;
    else
    map.put(nums[i],i);//特别注意这里,当二个相同的数字下标只差大于k的时候,要更新map
    }
    }
    return false;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.