697. Degree of an Array@python

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:

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.

原题地址: Degree of an Array

难度: Easy

题意: 先找出包含数量最多的值的子数组,返回最短的子数组长度.如上面例子,数量最多的数是1和2,包含1数字的子数组长度为5,包含2数字的子数组长度为2,所以返回2

思路:

(1)遍历数组,记录每个数值的数量已经最左边和最右边的索引值

(2)找出数量最多的数,返回长度

class Solution(object):
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l, r = {}, {}  # 记录数字最左边和最右边的索引
        d = {}        #  记录每个数字的数量
        for i, num in enumerate(nums):
             if num not in l:
                 l[num] = i
              r[num] = i
              d[num] = d.get(num, 0) + 1
        degree = max(d.values())    # 找出值最大的数量
        res = len(nums)
        for i in d:
              if  d[i] == degree:
                   res = min(res, r[i] - l[i] + 1)
        return res

时间复杂度: O(n)

空间复杂度: O(n)

猜你喜欢

转载自www.cnblogs.com/chimpan/p/9727183.html