My java solution a little bit different


  • 1
    N
    public int findShortestSubArray(int[] nums)
    {
        HashMap<Integer, Integer> left = new HashMap();
        HashMap<Integer, Integer> right = new HashMap();
        HashMap<Integer, Integer> degree = new HashMap();
        int res = 50000, maxDegree = 0;
        
        for(int i = 0; i < nums.length; i++)
        {
            if(!left.containsKey(nums[i]))
            {
                left.put(nums[i] , i);
                right.put(nums[i] , i);
                degree.put(nums[i], 1);
            }
            else
            {
                right.put(nums[i] , i);
                degree.put(nums[i] , degree.get(nums[i]) + 1);
            }
            maxDegree = Math.max(maxDegree, degree.get(nums[i]));
        }
        
        Set set = degree.entrySet();
        Iterator it = set.iterator();
        while(it.hasNext())
        {
            Map.Entry entry = (Map.Entry)it.next();
            if(entry.getValue().equals(maxDegree))
            {
                int temp = (int)entry.getKey();
                res = Math.min(res , right.get(temp) - left.get(temp) + 1);
            }
        }
        
        return res;
    }

Log in to reply
 

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