697. Degree of an Array
Posted 一日一更
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
.
Example 1:
Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2.
Example 2:
Input: [1,2,2,3,1,4,2] Output: 6
Note:
nums.length
will be between 1 and 50,000.nums[i]
will be an integer between 0 and 49,999.
解题思路:
把数组出现最多的保存到一个数字,对每个数字找头尾最先出现的序列,与min_distance做比较。
- class Solution {
- public:
- int findShortestSubArray(vector<int>& nums) {
- if(nums.size()==0) return 0;
- unordered_map<int,int> store;
- int max_digit=0;
- vector<int> digit;
- for(int i=0;i<nums.size();i++){
- store[nums[i]]++;
- if(store[nums[i]]>max_digit) max_digit = store[nums[i]];
- }
- if(max_digit == 1) return 1;
- for(unordered_map<int,int>::iterator iter= store.begin();iter!=store.end();iter++){
- if((*iter).second == max_digit) digit.push_back((*iter).first);
- }
- int min_distance = 99999;
- for(int i=0;i<digit.size();i++){
- //找最小间距
- int index1=0;
- int index2=0;
- for(int j=0;j<nums.size();j++){
- if(nums[j] == digit[i]) {index1 =j;break;}
- }
- for(int j=nums.size()-1;j>=0;j--){
- if(nums[j] == digit[i]) {index2 =j;break;}
- }
- if(index2-index1<min_distance) min_distance=index2-index1;
- }
- return min_distance+1;
- }
- };
以上是关于697. Degree of an Array的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode]Array-697. Degree of an Array