leetcode刷题(python)--*697. Degree of an Array(to review)

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.


class Solution:
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        first, counter, res, degree = {}, {}, 0, 0
        for i, v in enumerate(nums):
            first.setdefault(v, i)
            counter[v] = counter.get(v, 0) + 1
            if counter[v] > degree:
                degree = counter[v]
                res = i - first[v] + 1
            elif counter[v] == degree:
                res = min(res, i - first[v]+1)
        return res

my answer(Wrong):

      

        temp = sorted(nums)
        i = 0
        j = 0
        freq={}
        count = 0
        while(j <len(temp)):
            if temp[i] == temp[j]:
                count += 1
                freq[str(temp[i])] = count
                j += 1
            else:
                i = j
                count = 1
                freq[str(temp[i])] = count
                j += 1
        degree = max(freq.items(), key = lambda x : x[1])[1]
        # element = int(max(freq.items(), key = lambda x : x[1])[0])
        elements = []
        for item in freq:
            if freq[item] == degree:
                elements.append(int(item))        
        flag = []
        min = 50000
        for element in elements:
            for k in range(len(nums)):
                if nums[k] == element:
                    flag.append(k)
            length = flag[-1] - flag[0] +1
            flag.clear()
            if min > length:
                min = length
        return min
(run time error)

猜你喜欢

转载自blog.csdn.net/u014180553/article/details/80166970