Leetcode#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.
に言及
空ではなく、配列の各項目が負ではない値を与えます.配列の度は、出現回数が最も多く、この数を含むすべての連続が最も短い長さとして定義されます.例えば、1、2、2、3、1は[2、2]、長さは2、例えば、1、2、2、3、1、4、2は2、2、3、1、4、2である.長さ6
問題解
構想:まず出現回数が最も多い数を見つける必要があり、mapで単数出現回数が最も多い数は複数の数であり、temp配列に先に存在する可能性がある.ループ配列は最短の長さを比較します.
C++コード
class Solution {
public:
    int get_len(vector<int>nums, int index){//    ,                
        int s,e;
        for(int i=0; iif(index == nums[i]){
                s = i;
                break;
            }
        }
        for(int i=nums.size()-1; i>=0; i--)
        {
            if(index == nums[i])
            {
                e = i;
                break;
            }
        }
        return e-s+1;
    }
    int findShortestSubArray(vector<int>& nums) {
        map<int,int>m;
        int mx=0, index, temp[nums.size()];
        for(int i=0; iif(mx < m[nums[i]])//         
            {
                mx = m[nums[i]];
            }
        }

        map<int,int>::iterator it;
        int k=0;
        for(it=m.begin(); it!=m.end(); it++)
        {   
            if(it->second==mx){//          temp   
                temp[k++] = it->first;
            }
        }
        int mi=50005;
        for(int i=0; i//     
        {
            mi = min(get_len(nums,temp[i]), mi);
        }
        return mi;
    }
};

pythonコード
タイムアウト...
class Solution(object):
    def get_len(self, nums, index):
        e = 0
        s = 0
        for i in range(0, len(nums)):
            if index == nums[i]:
                s = i
                break
        for i in range(len(nums)-1, -1 ,-1):
            if index == nums[i]:
                e = i
                break
        return e-s+1

    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        m = {}
        mx = 0
        for i in range(0, len(nums)):
            m[nums[i]] = 0

        for i in range(0, len(nums)):
            m[nums[i]] = m[nums[i]] + 1
            if mx < m[nums[i]]:
                mx = m[nums[i]]

        temp = []
        for key in m:
            if m[key] == mx:
                temp.append(key)
        mi = 50005
        for i in range(0, len(temp)):
            mi = min(self.get_len(nums, temp[i]), mi)
        return mi