HashMap solution


  • 0
    D
       ```
        
        Map<Integer,List<Integer>> mp = new HashMap<>();
        
        List<Integer> ls = new ArrayList<>();
        
        for(int i =0;i<nums.length;i++)
        {
            
            if(mp.containsKey(nums[i]))
            {
               mp.get(nums[i]).add(i);
             
                
                mp.put(nums[i],mp.get(nums[i]));
            }
            else
            {
                ls.add(i);
                mp.put(nums[i], new ArrayList(ls));
                
            }
          ls.clear();  
        }
        
        for(Map.Entry<Integer,List<Integer>> am: mp.entrySet())
        {
            if(am.getValue().size()>1)
            {
                for(int i=0;i<am.getValue().size()-1;i++)
                if((am.getValue().get(i+1)-am.getValue().get(i))<=k)
          {  
            return true;
              
              
          }
            }
        }
        return false;
        
    ```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.