simple java solution O(n) Time


  • 0
    M
        public int findShortestSubArray(int[] nums) {
              Hashtable<Integer, ArrayList<Integer>> hashTable = new Hashtable<>();
        	  int result = 0;
        	  int degree = 0;
        	  for(int i = 0; i < nums.length; i++) {
        		  ArrayList<Integer> indices;
        		  if(hashTable.containsKey(nums[i])) {
        			  indices = hashTable.get(nums[i]);
        			  if(degree < indices.size() + 1) {
        				  result = i-indices.get(0)+1;
                                      degree = indices.size() + 1;
        			  }else if(degree == indices.size() + 1) {
        				  result = Math.min(result, i-indices.get(0)+1);
        			  }
        		  }else {
        			  indices = new ArrayList<>();
                              result = Math.max(result, 1);
        		  }
    		  indices.add(i);
    		  hashTable.put(nums[i], indices);
        	  }
        	  return result;
        }
    

Log in to reply
 

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