share my java solution!


  • 0
    T
    class Solution {
        public int findShortestSubArray(int[] nums) {
            Map<Integer,Integer> count = new HashMap<>();
            int max = 0;
            for(int i=0;i<nums.length;i++){
                count.put(nums[i],count.getOrDefault(nums[i],0)+1);
                max = Math.max(count.get(nums[i]),max);
            }
            
            Map<Integer,Integer> map = new HashMap<>();
            int lenMin = nums.length;
            int start = 0;
            for(int i=0;i<nums.length;i++){
                map.put(nums[i],map.getOrDefault(nums[i],0)+1);
                int cnt = map.get(nums[i]);
                if(cnt>=max){
                    while(map.get(nums[i])==max){
                        lenMin = Math.min(lenMin,i-start+1);
                        map.put(nums[start],map.getOrDefault(nums[start],0)-1);
                        start++;
                    }
                }
            }
            
            return lenMin;
        }
    }
    

Log in to reply
 

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