【力扣】697.数组的度--Python实现

【题目描述】
给定一个非空且只包含非负数的整数数组 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范围内的整数

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/degree-of-an-array

【解题思路】
用哈希来解这道题,count,start,end三个数组分别用于存储该元素出现的次数,出现的起始位置和出现的终止位置。用Python实现的代码如下:

class Solution(object):
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count, start, end = [0]*50000, [-1]*50000, [-1]*50000
        digree = 0
        for i in range(len(nums)):
            idx = nums[i]
            count[idx] += 1
            digree = max(digree, count[idx])
            if start[idx] == -1:
                start[idx] = i
                end[idx] = i
            else:
                end[idx] = i

        res = 50000
        for i in range(len(count)):
            if count[i] == digree:
                tmp = end[i] - start[i] + 1
                res = min(res, tmp)
        
        return res
             
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值