LeetCode 697. 数组的度
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 697. 数组的度
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 題目
給定一個(gè)非空且只包含非負(fù)數(shù)的整數(shù)數(shù)組 nums
數(shù)組的度的定義是指數(shù)組里任一元素出現(xiàn)頻數(shù)的最大值
你的任務(wù)是找到與 nums 擁有相同大小的度的最短連續(xù)子數(shù)組,返回其長(zhǎng)度。
示例 1: 輸入: [1, 2, 2, 3, 1] 輸出: 2 解釋: 輸入數(shù)組的度是2,因?yàn)樵?span id="ozvdkddzhkzd" class="token number">1和2的出現(xiàn)頻數(shù)最大,均為2. 連續(xù)子數(shù)組里面擁有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短連續(xù)子數(shù)組[2, 2]的長(zhǎng)度為2,所以返回2.示例 2: 輸入: [1,2,2,3,1,4,2] 輸出: 6注意: nums.length 在1到50,000區(qū)間范圍內(nèi)。 nums[i] 是一個(gè)在0到49,999范圍內(nèi)的整數(shù)。來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/degree-of-an-array
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
2. 解題
class Solution { public:int findShortestSubArray(vector<int>& nums) {int degree = 1, n, minlen = INT_MAX;unordered_map<int, int> m, start, end;for (int i = 0; i < nums.size(); ++i){if(m.find(nums[i]) == m.end())//沒出現(xiàn)過該數(shù){m[nums[i]] = 1;//計(jì)數(shù)start[nums[i]] = i;//數(shù)字起始位置end[nums[i]] = i;//終止位置}else//出現(xiàn)過該數(shù)字{m[nums[i]]++;//計(jì)數(shù)if(m[nums[i]] > degree)//更新最大頻數(shù)degree = m[nums[i]];end[nums[i]] = i;//更新終止位置}}for(auto it = m.begin(); it != m.end(); ++it){if(it->second == degree)//等于最大的頻數(shù){if(end[it->first]-start[it->first]+1 < minlen)//長(zhǎng)度更小minlen = end[it->first]-start[it->first]+1;}}return minlen;} };76 ms 13.8 MB
總結(jié)
以上是生活随笔為你收集整理的LeetCode 697. 数组的度的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 438. 找到字符串中
- 下一篇: LeetCode 1087. 字母切换(