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.

给定一个数组判断数组中是否存在两个相同的数,它们之间的差最大为k。我们借助HashMap, key中存放数组的元素nums[i],value中存放对应的下标i。如果遇到相同的key,就对比当前元素的下标i与key中value的值与k的大小,如果i - get(key) 小于等于k就说明存在,返回true。代码入下:
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums == null || nums.length < 2) return false;
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(hm.containsKey(nums[i])) {
                if(i - hm.get(nums[i]) <= k)
                    return true;
            }
            hm.put(nums[i], i);
        }
        return false;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2277655