java using one map solution


  • 0
    J

    public int findShortestSubArray(int[] nums) {

        if (nums.length == 1)   return 1;
        Map<Integer, int[]> map = new HashMap<>(); // int[] : count, first index, last index
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], new int[]{1, i, i});
            } else {
                int count = map.get(nums[i])[0] + 1;
                int j = map.get(nums[i])[1];
                map.put(nums[i], new int[]{count, j, i});
            }
        }
        int minLen = map.get(nums[0])[2] - map.get(nums[0])[1] + 1;
        int maxCount = map.get(nums[0])[0];
        for (int i = 1; i < nums.length; i++) {
            if (map.get(nums[i])[0] > maxCount) {
                maxCount = map.get(nums[i])[0];
                minLen = map.get(nums[i])[2] - map.get(nums[i])[1] + 1;
            }
            else if (map.get(nums[i])[0] == maxCount) {
                minLen = Math.min(minLen, map.get(nums[i])[2] - map.get(nums[i])[1] + 1);
            }
        }
        
        return minLen;
    }

Log in to reply
 

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