1. 程式人生 > >【python3】leetcode 697. Degree of an Array(easy)

【python3】leetcode 697. Degree of an Array(easy)

697. Degree of an Array(easy)

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

題目:一個array的度degree就是數字出現的最高的頻率 

求頻率相同的subarray的最小長度

-》可以get到的資訊:1 要先求degree,且要知道每個數字的degree -》max degree

                                   2 頻率相同的subarray一定是包含maxdegree的數字的,所以只針對度為maxdegree的數字去找subarray就好,要求最小長度,說明這個數字作為subarray的開頭和結尾

1 slow slow slow method ( 遍歷很容易超時

利用了collections.Counter求每個數字出現的頻率,返回的是一個字典dict{num:count}

得到max degree和度為maxdegree的數字

遍歷得到的數字求min length

class Solution:
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        度相同的最小子列長度
        """
        length = len(nums)
        if length == 1:return 1
        count = collections.Counter(nums)
        sortCount = list(count.values())
        sortCount.sort()
        maxD = sortCount[-1]
        degreeList = [key for key,val in count.items() if val == maxD]
        revNum = nums.copy()
        revNum.reverse()
        minL = length
        for x in degreeList:
            # if nums.count(x) == maxD:
            count1 = nums.index(x)
            count2 = revNum.index(x)
            minL = min(minL,length - count2 - count1)

        return minL

Runtime: 756 ms, faster than 8.13% of Python3