码迷,mamicode.com
首页 > 其他好文 > 详细

697. Degree of an Array

时间:2018-04-13 16:22:41      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:put   保存   data   int   second   input   define   integer   push   

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

标签:put   保存   data   int   second   input   define   integer   push   

原文地址:https://www.cnblogs.com/liangyc/p/8820479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!