【Leetcode】697. 数组的度(Degree of an Array)

博客围绕Leetcode - 697 Degree of an Array (Easy)题目展开。该题要求在数组中找到长度最小且度与原数组相同的子数组,数组的度指出现次数最多元素的出现次数。解题思路是定义三个map,分别存储元素出现次数、首次出现位置和最后出现位置。

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

Leetcode - 697 Degree of an Array (Easy)

题目描述:数组的度是指数组中出现次数最多的元素的出现次数,例如数组 [1,2,2,2,1] 的度为 3,要求找到长度最小的子数组且该子数组的度与原数组的度相同。

Input: [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.

解题思路:定义三个 map,分别存储数组中元素的出现次数、元素第一次出现的位置与元素最后一次出现的位置。

public int findShortestSubArray(int[] nums) {
    HashMap<Integer, Integer> count = new HashMap<>();
    HashMap<Integer, Integer> left = new HashMap<>();
    HashMap<Integer, Integer> right = new HashMap<>();
    
    for (int i = 0; i < nums.length; i++) {
        if (!left.containsKey(nums[i])) {
            left.put(nums[i], i);
        }
        right.put(nums[i], i);
        count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
    }
    
    int ans = nums.length;
    int degree = Collections.max(count.values());
    for (int x : count.keySet()) {
        if (count.get(x) == degree) {
            ans = Math.min(ans, right.get(x) - left.get(x) + 1);
        }
    }
    return ans;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值