My easy 2-pass java solution


  • 0
    Y

    Using an array to record the frequency, first appeared position and the last appeared position of each integer.

    class Solution {
        public int findShortestSubArray(int[] nums) {
            int degree = 0;
            int res = Integer.MAX_VALUE;
            Map<Integer, int[]> map = new HashMap<>();
            for(int i = 0; i < nums.length; i ++) {
                if(!map.containsKey(nums[i])) {
                    map.put(nums[i], new int[]{1, i, i});
                }
                else {
                    int[] c = map.get(nums[i]);
                    c[0] ++;
                    c[2] = i;
                }
                if(map.get(nums[i])[0] > degree) degree = map.get(nums[i])[0];
            }
            for(int key : map.keySet()) {
                if(map.get(key)[0] == degree) {
                    res = Math.min(res, map.get(key)[2] - map.get(key)[1] + 1);
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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