Share my simple Java solution


  • 0
    Z

    '''
    class Solution {

    public int findShortestSubArray(int[] nums) { 
        Map<Integer,List<Integer>> map=new HashMap<Integer,List<Integer>>();
        int degree=0;
    
        for(int i=0;i<nums.length;i++)
        {   
            if(!map.containsKey(nums[i]))
                map.put(nums[i],new ArrayList<Integer>());
            map.get(nums[i]).add(i);
            if(map.get(nums[i]).size() > degree)
            {
                degree=map.get(nums[i]).size();
            }
         }
    
         int result=Integer.MAX_VALUE;
         for(int num:map.keySet())
         {
               if (map.get(num).size()==degree)
               {  
                  List<Integer> list =map.get(num);
                  int diff=list.get(list.size()-1) - list.get(0);
                  if(diff+1 < result)
                      result= diff+1;
                }
         }          
    return result;
    }
    

    }

    '''


Log in to reply
 

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