【Leetcode_總結】697. 陣列的度 - python
阿新 • • 發佈:2018-12-15
連結:https://leetcode-cn.com/problems/degree-of-an-array/description/
Q:
給定一個非空且只包含非負數的整數陣列 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.
思路:這個是很久前寫的 當時怎麼都不能通過 然後今天試了一下莫名其妙的就通過了,思路大概是首先建立字典,因為字典的查詢效率高,通過字典統計詞頻,Counter()有同樣的效果,然後統計詞頻最高的,計算距離,得出距離最小的值,實際上是暴力求解的感覺
class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ maxs = 0 dict_ ={} temp = [] for ele in nums: if ele in dict_: dict_[ele]+=1 else: dict_[ele] = 1 for i in dict_: if dict_[i]>maxs: maxs = dict_[i] if maxs == 1: return 1 for j in dict_: if dict_[j] == maxs: temp.append(j) res = [] for t in temp: start = nums.index(t) end = 0 for i in range(len(nums)): if t == nums[i]: end = i res.append(end-start) return min(res)+1