package com.fishercoder.solutions;

import java.util.HashMap;
import java.util.Map;

/**219. 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.*/
public class _219 {

    //pretty straightforward, use a hashmap, key is the number itself, value is the last index that this value appeared in the array
    //we can keep updating the value as we move forward, since if the current index minus the last index cannot be smaller than k, then
    //the later indices won't even do either. So, we only need to keep one index in the value of the HashMap. Cheers!
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                if (i - map.get(nums[i]) <= k) {
                    return true;
                } else {
                    map.put(nums[i], i);
                }
            } else {
                map.put(nums[i], i);
            }
        }
        return false;
    }
}

@@ -112,11 +112,10 @@
  II%0A
- *
 %0A
+ 
 Give
@@ -154,16 +154,17 @@
 teger k,
+%0A
  find ou
@@ -214,16 +214,17 @@
 and j in
+%0A
  the arr
@@ -302,16 +302,18 @@
  most k.
+%0A 
 */%0Apubli
@@ -336,391 +336,44 @@
     
-//pretty straightforward, use a hashmap, key is the number itself, value is the last index that this value appeared in the array%0A    //we can keep updating the value as we move forward, since if the current index minus the last index cannot be smaller than k, then%0A    //the later indices won't even do either. So, we only need to keep one index in the value of the HashMap. Cheers!%0A
+public static class Solution1 %7B%0A    
     
@@ -440,16 +440,20 @@
         
+   
+ 
 Map%3CInte
@@ -495,16 +495,20 @@
         
+    
 for (int
@@ -547,24 +547,28 @@
             
+ 
+   
 if (map.cont
@@ -583,24 +583,28 @@
 nums%5Bi%5D)) %7B%0A
+    
             
@@ -656,24 +656,28 @@
             
+    
 return true;
@@ -685,32 +685,36 @@
                 
+   
+ 
 %7D else %7B%0A       
@@ -698,32 +698,36 @@
        %7D else %7B%0A
+    
                 
@@ -759,34 +759,42 @@
                 
-%7D%0A
+    %7D%0A    
             %7D el
@@ -806,32 +806,36 @@
                 
+    
 map.put(nums%5Bi%5D,
@@ -843,32 +843,36 @@
 i);%0A            
+    
 %7D%0A        %7D%0A    
@@ -857,32 +857,36 @@
       %7D%0A        
+ 
+   
 %7D%0A        return
@@ -875,24 +875,28 @@
   %7D%0A        
+ 
+   
 return false
@@ -897,16 +897,26 @@
  false;%0A
+        %7D%0A
     %7D%0A%7D%0A

refactor 219