LeetCode 697. 陣列的度(C++、python)
阿新 • • 發佈:2018-11-21
給定一個非空且只包含非負數的整數陣列 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範圍內的整數。
C++
class Solution { public: int findShortestSubArray(vector<int>& nums) { int n=nums.size(); map<int,vector<int>> tmp; for(int i=0;i<n;i++) { tmp[nums[i]].push_back(i); } int count=0; int res=INT_MAX; map<int,vector<int>>::iterator it; for(it=tmp.begin();it!=tmp.end();it++) { int m=it->second.size(); if(m>count) { count=m; res=it->second[m-1]-it->second[0]+1; } if(m==count) { res=min(res,it->second[m-1]-it->second[0]+1); } } return res; } };
python
class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ dic={} count=0 n=len(nums) res=n for i in range(n): if nums[i] not in dic: dic[nums[i]]=[i] else: dic[nums[i]].append(i) for key in dic: m=len(dic[key]) if m>count: count=m res=dic[key][m-1]-dic[key][0]+1 if m==count: res=min(res,dic[key][m-1]-dic[key][0]+1) return res