Concise Java O(n) O(n)


  • 0
    class Solution {
        public int findShortestSubArray(int[] nums) {
            int max = 0;
            Map<Integer, List<Integer>> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (!map.containsKey(nums[i])) map.put(nums[i], new ArrayList<>());
                map.get(nums[i]).add(i);
                max = Math.max(max, map.get(nums[i]).size());
            }
            if (max == 1 || max == nums.length) return max;
            int minLen = nums.length;
            for (int key : map.keySet()) {
                if (map.get(key).size() == max) {
                    minLen = Math.min(minLen, map.get(key).get(max - 1) - map.get(key).get(0));
                }
            }
            return minLen + 1;
        }
    }
    

Log in to reply
 

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