[LintCode/LeetCode] Contains Duplicate II

Problem

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 absolute difference between i and j is at most k.

Example

Given nums = [1,2,1], k = 0, return false.

Solution

public class Solution {
    /**
     * @param nums: the given array
     * @param k: the given number
     * @return:  whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // Write your code here
        if (nums.length < 2 || k < 1) return false;
        Set set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            // i - (i-k-1) > k
            if (i > k) set.remove(nums[i-k-1]);
            if (set.contains(nums[i])) return true;
            set.add(nums[i]);
        }
        return false;
    }
}

也可以用HashMap的简单解法

你可能感兴趣的:(LintCode,java,hashset)