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.

题意:给定数组和整数k,找出数组内相同元素,且两个元素距离小于等于k

解决思路:和前一个思路一样,只不过多加一个判断

代码:

public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<Integer>();
        int i = 0, j = 0;
        for (; j < nums.length; j++) {
            if (j - i > k) {
                set.remove(nums[i]);
                i++;
            }
            if (set.contains(nums[j])) return true;
            set.add(nums[j]);
        }
        return false;
    }

你可能感兴趣的:(LeetCode)