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

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

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;
    }
### 解题思路 LeetCode 第80题要求删除一个有序数组中出现次数超过两次的重复元素,使得每个元素最多出现两次,并返回去重后的数组。此问题可以通过双指针的方法来实现。 - 由于数组是有序的,因此相同的元素一定是连续出现的。 - 使用两个指针:一个用于遍历数组(`i`),另一个用于记录不重复部分的位置(`k`)。 - 如果当前元素 `nums[i]` 不等于 `nums[k]`,说明遇到了一个新的元素,则将其放到 `nums[k+1]` 的位置,并将 `k` 后移一位。 - 如果当前元素与前一个元素相同,则跳过该元素,直到遇到不同的元素为止。 - 最终返回 `k + 1` 作为新数组的长。 ### C语言实现 以下是针对 LeetCode 80 题的 C 语言实现代码: ```c #include <stdio.h> int removeDuplicates(int* nums, int numsSize) { if (numsSize <= 2) return numsSize; // 如果数组小于等于2,直接返回原长 int k = 1; // 指向结果数组的最后一个有效位置 for (int i = 2; i < numsSize; i++) { if (nums[i] != nums[k - 1]) { // 当前元素与结果数组倒数第二个元素不同 nums[++k] = nums[i]; // 将其加入结果数组 } } return k + 1; // 返回新数组 } ``` ### 测试代码 以下是一个简单的测试用例,用于验证上述函数是否正确工作: ```c #include <stdio.h> int main() { int nums[] = {1, 1, 1, 2, 2, 3}; int numsSize = sizeof(nums) / sizeof(nums[0]); int newLength = removeDuplicates(nums, numsSize); printf("New length: %d\n", newLength); printf("Modified array: "); for (int i = 0; i < newLength; i++) { printf("%d ", nums[i]); } printf("\n"); return 0; } ``` ### 输出示例 运行上述测试代码后,输出应为: ``` New length: 5 Modified array: 1 1 2 2 3 ``` ### 算法复杂分析 - **时间复杂**:O(n),其中 n 是数组的长。只需要一次遍历即可完成操作。 - **空间复杂**:O(1)算法在原地修改数组,没有使用额外的空间[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值