1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int findShortestSubArray(vector<int>& nums) 
12     {
13         int sz=nums.size();
14         vector<int> firstindex(50000,-1);
15         vector<int> lastindex(50000,-1);
16         vector<int> times(50000,0);
17         int maxtimes=0;
18         
19         int minlength=INT_MAX;
20         for(int i:nums)
21         {
22             times[i]++;
23             maxtimes=max(maxtimes,times[i]);
24         }
25         
26         for(int i=0;i<sz;i++)
27         {
28             if(firstindex[nums[i]]==-1)
29                 firstindex[nums[i]]=i;
30         }
31         
32         for(int j=sz-1;j>-1;j--)
33         {
34             if(lastindex[nums[j]]==-1)
35                 lastindex[nums[j]]=j;
36         }
37         for(int k=0;k<sz;k++)
38         {
39             if(times[nums[k]]==maxtimes)
40                 minlength=min(minlength,lastindex[nums[k]]-firstindex[nums[k]]+1);
41         }
42         return minlength;
43     }
44 };

这题用map和vector都行,一个容器统计元素次数,一个容器放元素首次出现位置,一个容器放元素最后一次出现位置,然后扫描原数组,遇到最大出现次数更新最短长度即可。

posted on 2018-06-10 18:25  高数考了59  阅读(119)  评论(0)    收藏  举报