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做比较。

  1. class Solution {  
  2. public:  
  3.     int findShortestSubArray(vector<int>& nums) {  
  4.         if(nums.size()==0) return 0;  
  5.         unordered_map<int,int> store;  
  6.         int max_digit=0;  
  7.         vector<int> digit;  
  8.         for(int i=0;i<nums.size();i++){  
  9.             store[nums[i]]++;  
  10.               
  11.             if(store[nums[i]]>max_digit) max_digit = store[nums[i]];  
  12.         }  
  13.         if(max_digit == 1) return 1;  
  14.         for(unordered_map<int,int>::iterator iter= store.begin();iter!=store.end();iter++){  
  15.             if((*iter).second == max_digit) digit.push_back((*iter).first);  
  16.         }  
  17.         int min_distance = 99999;  
  18.         for(int i=0;i<digit.size();i++){  
  19.             //找最小间距  
  20.             int index1=0;  
  21.             int index2=0;  
  22.             for(int j=0;j<nums.size();j++){        
  23.                if(nums[j] == digit[i]) {index1 =j;break;}  
  24.             }  
  25.             for(int j=nums.size()-1;j>=0;j--){        
  26.                if(nums[j] == digit[i]) {index2 =j;break;}  
  27.             }  
  28.             if(index2-index1<min_distance) min_distance=index2-index1;  
  29.               
  30.         }  
  31.         return min_distance+1;  
  32.           
  33.     }  
  34. };  

 

以上是关于697. Degree of an Array的主要内容,如果未能解决你的问题,请参考以下文章

697. Degree of an Array

697. Degree of an Array

697. Degree of an Array

[leetcode]Array-697. Degree of an Array

leetcode-697-Degree of an Array

697. Degree of an Array