LeetCode-Degree of an Array

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

Example 2:

Input: [1,2,2,3,1,4,2]
Output: 6

Note:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.

题意:给定一个非空且元素非负的一维数组,定义数组的最大频率为元素重复出现的最大次数;现要求找出数组的一个子数组满足其最大频率和原数组相同,并且要求找到的子数组长度最短;

解法:如果[num]为数组中出现次数最多的元素,假设出现次数为[t],那么所找的符合要求的子数组中[num]出现的次数也应当为[t];那么我们可以为每个元素标记他从数组首部开始最早出现的下标位置[leftIndex]和从数组尾部开始最早出现的下标位置[rightIndex],由这两个位置构成的数组的长度为[rightIndex - leftIndex + 1];

class Solution {
    public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> leftIndex = new HashMap<>();
        Map<Integer, Integer> rightIndex = new HashMap<>();
        Map<Integer, Integer> count = new HashMap<>();
        int maxFrequency = 0;

        for(int i=0; i<nums.length; i++) {
            if (leftIndex.get(nums[i]) == null) {
               leftIndex.put(nums[i], i); 
            }
            rightIndex.put(nums[i], i);
            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
            maxFrequency = Math.max(maxFrequency, count.get(nums[i]));
        }

        int result = nums.length;

        for(int num : nums) {
            if (count.get(num) == maxFrequency) {
                result = Math.min(result, rightIndex.get(num) - leftIndex.get(num) + 1);
            }   
        }

        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值