143、数组的度

给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。

你的任务是找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。

示例 1:

输入: [1, 2, 2, 3, 1]
输出: 2
解释:
输入数组的度是2,因为元素1和2的出现频数最大,均为2.
连续子数组里面拥有相同度的有如下所示:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短连续子数组[2, 2]的长度为2,所以返回2.
示例 2:

输入: [1,2,2,3,1,4,2]
输出: 6
注意:

nums.length 在1到50,000区间范围内。
nums[i] 是一个在0到49,999范围内的整数。

效率不高的代码

class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
		for (int i : nums) {
			map.put(i, map.getOrDefault(i, 0) + 1);
		}
		int max = 0;
		for (int i : map.values()) {
			if(max < i){
				max = i;
			}
		}
		int min = nums.length;
		for (int i : map.keySet()) {
			if(map.get(i) == max){
				int start = 0;
				int end = nums.length - 1;
				while (nums[start] != i) {
					start ++;
				}
				while (nums[end] != i) {
					end --;
				}
				min = Math.min(min, end - start +1);
			}
		}
		return min;
    }
}

排名靠前的代码

class Solution {
    public static int findShortestSubArray(int[] nums) {

        //求出nums数组中最大的数
        int maxNum = nums[0];
        for (int i = 1; i < nums.length; i++) {
            maxNum = Math.max(maxNum, nums[i]);
        }

        //用三个数组分别记录  起始位置,长度,度
        int max = 1;//最大的度

        int[] start = new int[maxNum + 1];//起始位置
        int[] length = new int[maxNum + 1];//长度
        int[] count = new int[maxNum + 1];//度

        for (int i = 0; i < nums.length; i++) {
            count[nums[i]]++;
            if (count[nums[i]] == 1) {//记录第一次出现的位置
                start[nums[i]] = i;
            } else {
                length[nums[i]] = i - start[nums[i]] + 1;//记录当前的长度
                max = Math.max(count[nums[i]], max);//最大的度
            }
        }

        if (max == 1) {
            return 1;
        }

        int degree = nums.length;//最大的度对应的最小的数组长度
        for (int i = 0; i <= maxNum; i++) {
            if (count[i] == max) {
                degree = Math.min(length[i], degree);
            }
        }

        return degree;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85489468