爱程序网

[LeetCode] Contains Duplicate II

来源: 阅读:

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.

     这道题还是很简单的。没啥可说的。直接用hashmap就可以做了,借助containsKey(),get()还有put()。

     代码如下。~

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
    Map<Integer,Integer>test=new HashMap<>();
    for(int i=0;i<nums.length;i++){
        if(test.containsKey(nums[i])){
            int diff=i-test.get(nums[i]);
            if(diff<=k){
                return true;
            }
        }
        test.put(nums[i],i);
    }
    return false;
        
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助