Java O(n) time O(n) space


  • 0
    J

    class Solution {
    public int findShortestSubArray(int[] nums) {
    HashMap<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();

        int max = 0;
        int min = Integer.MAX_VALUE;
        
        for(int i = 0; i < nums.length; i++){
            int tmp = nums[i];
            if(map.containsKey(tmp)){
                map.get(tmp).add(i);
                max = Math.max(max,map.get(tmp).size());
            }else{
                List<Integer> tmplist = new ArrayList<Integer>();
                tmplist.add(i);
                map.put(tmp,tmplist);
                max = Math.max(max,1);
            }
        }
        
        //System.out.println(max);
        
        for(List<Integer> tmp : map.values()){
           // System.out.println(tmp.size());
            if(tmp.size() == max){
                min = Math.min(min, tmp.get(tmp.size()-1) - tmp.get(0) + 1);
            }
        }
        
        return min;
    }
    

    }


Log in to reply
 

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