leetcode 697. Degree of an Array(数组的度)

本文介绍如何通过HashMap和两个辅助哈希表,快速找到给定整数数组中度(出现次数最多的元素次数)相等的最短连续子数组。使用计数和起始索引跟踪,实现一次遍历即可求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: nums = [1,2,2,3,1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

给出一个数组,数组的度即为出现最多的数字出现的次数,让找出一个子数组和原数组的度一样

思路:
如果只计算数组的度,那么用majority element的投票法就能解决,但是现在要找出一个最短的子数组和原数组的度一样。
而且现在不知道哪个数字出现的次数最多,也可能几个出现次数一样多的要选择一个能使子数组最短的。因此需要一个hashMap来保存每个数字出现的次数。

而且要找到子数组的长度需要知道start index和end index,把每个数字第一次出现的index保存为start index,end index就是现在遍历到的index。
因此另外需要一个hashMap保存start index

当当前遍历到的数字出现的次数等于degree时,就取现有的作为结果的子数组长度和当前index - start index +1中较小的
当遍历到的数字出现的次数>degree时,直接将结果更新到index - start index + 1

这样只要遍历一次就可以了

    public int findShortestSubArray(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        HashMap<Integer, Integer> count = new HashMap<>();
        HashMap<Integer, Integer> startIdx = new HashMap<>();
        
        int degree = 0;
        int result = Integer.MAX_VALUE;
        int n = nums.length;
        
        for(int i = 0; i < n; i++) {
            int tmp = count.getOrDefault(nums[i], 0);
            if(tmp == 0) {
                startIdx.put(nums[i], i);
            }
            count.put(nums[i], tmp+1);
            int cnt = count.get(nums[i]);
            if(cnt > degree) {
                degree = cnt;
                result = i-startIdx.get(nums[i]) + 1;
            } else if(cnt == degree) {
                result = Math.min(result, i-startIdx.get(nums[i]) + 1);
            }
        }
        
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值