@@ -0,0 +1,1381 @@
+package com.freetymekiyan.algorithms.level.easy;%0A%0Aimport java.util.HashMap;%0Aimport java.util.HashSet;%0Aimport java.util.Map;%0Aimport java.util.Set;%0A%0A/**%0A * Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array%0A * such that nums%5Bi%5D = nums%5Bj%5D and the difference between i and j is at most k.%0A * %3Cp%3E%0A * Tags: Array, Hash Table%0A * Similar Problems: (E) Contains Duplicate, (M) Contains Duplicate III%0A */%0Apublic class ContainsDuplicate2 %7B%0A%0A    public boolean containsNearbyDuplicate(int%5B%5D nums, int k) %7B%0A        Map%3CInteger, Integer%3E map = new HashMap%3C%3E();%0A        for (int i = 0; i %3C nums.length; i++) %7B%0A            if (map.containsKey(nums%5Bi%5D) && i - map.get(nums%5Bi%5D) %3C= k) %7B%0A                return true;%0A            %7D else %7B%0A                map.put(nums%5Bi%5D, i);%0A            %7D%0A        %7D%0A        return false;%0A    %7D%0A%0A    /**%0A     * Don't need to save number and index in a map.%0A     * Just loop through the array with a sliding window(set of size k).%0A     */%0A    public boolean containsNearbyDuplicate2(int%5B%5D nums, int k) %7B%0A        Set%3CInteger%3E set = new HashSet%3CInteger%3E();%0A        for (int i = 0; i %3C nums.length; i++) %7B%0A            if (i %3E k) %7B%0A                set.remove(nums%5Bi - k - 1%5D);%0A            %7D%0A            if (!set.add(nums%5Bi%5D)) %7B%0A                return true;%0A            %7D%0A        %7D%0A        return false;%0A    %7D%0A%7D%0A

add Contains Duplicate 2