Two HashMap solution, 63ms


  • 0
    S
    public int findShortestSubArray(int[] nums) {
            HashMap<Integer, Integer> maps1 = new HashMap<Integer, Integer>();
            HashMap<Integer, int[]> maps2 = new HashMap<Integer, int[]>();
            int max = 0;
            for(int i=0; i<nums.length; i++){
                if(!maps1.containsKey(nums[i])){
                    maps1.put(nums[i], 1);
                    maps2.put(nums[i], new int[]{i,i});
                }else{
                    maps1.put(nums[i], maps1.get(nums[i])+1);
                    maps2.get(nums[i])[1] = i;
                }
                if(max < maps1.get(nums[i])){
                    max = maps1.get(nums[i]);
                }
            }
            int result = nums.length+2;
            for(Map.Entry<Integer, Integer> entry: maps1.entrySet()){
                int val = entry.getValue();
                if(val == max){
                    int[] curt = maps2.get(entry.getKey());
                    result = Math.min(result, curt[1] - curt[0] + 1);
                }
            }
            return result;
        }
    

Log in to reply
 

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