【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,調(diào)用collections.Counter().most_common(1)

2 怎么有效地去遍歷各個subarray

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

4 設(shè)置兩個dictionary,第一個first記錄v第一次出現(xiàn)的index,counter記錄出現(xiàn)的次數(shù)

5 依次遍歷array,得到每一個字符的first index和count,同時記錄返回長度

6 當(dāng)遍歷到后面,degree是一樣的時候,需要返回最小的長度

7?first.setdefault(v, i) 如果v在dict中,就直接返回初始index就行,如果不在dict中,把當(dāng)前的index寫進(jìn)去

8?counter[v] = counter.get(v, 0)+1, 這和first不同在于,counter是需要每次加1的,所以此處不用first.setdefault(v, i),只是每次在get到的值的基礎(chǔ)上加1,初始化為0

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 給定一個非空且只包含非負(fù)數(shù)的整數(shù)數(shù)組 nums, 數(shù)組的度的定義是指數(shù)組里任一元素出現(xiàn)頻數(shù)的最大值。 你的任務(wù)是找...
    vcancy閱讀 575評論 0 0
  • 題目描述: 簡單翻譯下題意,給定一個非負(fù)非空整型數(shù)組,它的degree(度)指的是它中的任意一個出現(xiàn)頻率最高的元素...
    DDB_CS閱讀 602評論 1 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,869評論 0 10
  • 以前, 在外面總覺得受了委屈, 可以回家, 家可以給你依靠, 給你溫暖, 可是現(xiàn)在, 當(dāng)自己經(jīng)歷過, 才會明白,不...
    路過miss閱讀 211評論 0 1
  • 坐在第一排,同桌是個男生,臉圓圓的,眼睛小小的。好幾次我側(cè)過頭去,都看到他左手拖著腮幫子,看著我,笑瞇瞇地,眼睛都...
    藤木同學(xué)閱讀 743評論 0 0

友情鏈接更多精彩內(nèi)容