1. 程式人生 > >leetcode-697-Degree of an Array

leetcode-697-Degree of an Array

暴力 example 元素 fine lan 代碼 empty because 分享

題目描述:

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.

要完成的函數:

int findShortestSubArray(vector<int>& nums)

說明:

1、給定一個非空vector,裏面含有非負數,vector的程度定義為“其眾數出現的頻率”,想找到一個盡可能短的連續子vector,使得該子vector的程度和vector的程度一樣。

2、直接的想法,使用unordered_map遍歷一遍vector,統計vector中元素出現的次數,然後再遍歷一遍unordered_map找到出現最多次的元素(可能有多個),然後在vector中找到該元素的首次出現index和最後一次的index,得到長度。如果有多個元素,這裏要求出最短的長度。

暴力解決,代碼如下:(附解釋)

    int findShortestSubArray(vector<int>& nums) 
    {
        unordered_map<int,int>chuxian;
        vector<int
>elem; int s1=nums.size(); int max1=0; for(int i=0;i<s1;i++)//存儲各個元素的出現次數 { if(chuxian.count(nums[i])) chuxian[nums[i]]++; else chuxian[nums[i]]=1; } for(unordered_map<int,int>::iterator iter=chuxian.begin();iter!=chuxian.end();iter++) {//遍歷map找到出現最多次的元素,插入到新定義的vector中 if(iter->second>max1) { elem.clear(); elem.push_back(iter->first); max1=max(max1,iter->second); } else if(iter->second==max1) elem.push_back(iter->first); } int i,j,t,min1=INT_MAX,s2=elem.size(),k=0; while(k<s2)//每個元素都求出對應的長度,最後得到最短的長度 { i=0; j=s1-1; t=elem[k]; k++; while(i<s1) { if(nums[i]==t) break; i++; } while(j>=0) { if(nums[j]==t) break; j--; } min1=min(min1,j-i+1); } return min1; }

上述代碼實測109ms,beats 12.33% of cpp submissions。

3、改進:

上述代碼實在太慢了,我們要先遍歷vector,找到元素和元素出現次數的對應關系

接著再遍歷map,由最大的元素出現次數找到元素

接著再遍歷vector,找到元素的首index和末index。

我們可不可以直接把第三步要做的事情在第一次遍歷中就給實現了,又不耽誤元素出現次數的統計。

我們可以把元素出現的位置,作為一個vector,插入map的second中,這樣就可以了。

代碼如下:(附解釋)

    int findShortestSubArray(vector<int>& nums) 
    {
        unordered_map<int,vector<int>> m1;//第二項是個vector
        for(int i=0;i<nums.size();i++) 
            m1[nums[i]].push_back(i); //統計元素的出現位置
        int max1=INT_MIN;
        for(auto iter=m1.begin();iter!=m1.end();iter++) //遍歷map找到出現的最多次數
            max1=max(max1,int(iter->second.size()));//degree就是max1
        int min1=INT_MAX;
        for(auto iter=m1.begin();iter!=m1.end();iter++)//遍歷map找到對應的元素,計算最短長度
        {
            if(iter->second.size()==max1)//
                min1=min(min1,iter->second.back()-iter->second[0]+1);
        }
        return min1;
    }

上述代碼實測33ms,beats 97.23% of cpp submissions。

這裏要感謝leetcode用戶@sguox002在討論區分享的代碼,提供了新的思路。

leetcode-697-Degree of an Array