【Leetcode】697. Degree of an Array

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.

class Solution(object):

    def findShortestSubArray(self, nums):

        """

        :type nums: List[int]

        :rtype: int

        """

        first, counter, res, degree = {}, {}, 0, 0

        for i, v in enumerate(nums):

            first.setdefault(v, i)

            counter[v] = counter.get(v, 0)+1

            if counter[v]>degree:

                degree = counter[v]

                res = i-first[v]+1

            elif counter[v]==degree:

                res = min(res, i-first[v]+1)

        return res

1 首先得到array的degree,调用collections.Counter().most_common(1)

2 怎么有效地去遍历各个subarray

3 因为涉及到index和value,所以用enumerate

4 设置两个dictionary,第一个first记录v第一次出现的index,counter记录出现的次数

5 依次遍历array,得到每一个字符的first index和count,同时记录返回长度

6 当遍历到后面,degree是一样的时候,需要返回最小的长度

7 first.setdefault(v, i) 如果v在dict中,就直接返回初始index就行,如果不在dict中,把当前的index写进去

8 counter[v] = counter.get(v, 0)+1, 这和first不同在于,counter是需要每次加1的,所以此处不用first.setdefault(v, i),只是每次在get到的值的基础上加1,初始化为0

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。 你的任务是找...
    vcancy阅读 549评论 0 0
  • 题目描述: 简单翻译下题意,给定一个非负非空整型数组,它的degree(度)指的是它中的任意一个出现频率最高的元素...
    DDB_CS阅读 583评论 1 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,461评论 0 10
  • 以前, 在外面总觉得受了委屈, 可以回家, 家可以给你依靠, 给你温暖, 可是现在, 当自己经历过, 才会明白,不...
    路过miss阅读 193评论 0 1
  • 坐在第一排,同桌是个男生,脸圆圆的,眼睛小小的。好几次我侧过头去,都看到他左手拖着腮帮子,看着我,笑眯眯地,眼睛都...
    藤木同学阅读 674评论 0 0