[easy+][Array][遍历时存储信息]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.

思路:

遍历的过程中,存储我们想要的信息:
该元素是否出现的次数最多,在出现最多的前提下,它的最左最右出现的index差是否最小。
用一个dict数据结构来存储这些信息。

代码是:

class Solution:
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dicts = {}
        degreeEle = -1
        degree = 0
        minDiff = 0
        for i in range(len(nums)):
            if nums[i] not in dicts:
                dicts[nums[i]] = [1,i,i] 
                #key-value :  元素 ,[次数,最左index,最右index]
            else :
                dicts[nums[i]][0] += 1
                dicts[nums[i]][2] = i
                
            if dicts[nums[i]][0] > degree: #在遍历中更新最值
                degree = dicts[nums[i]][0]
                degreeEle = nums[i]
                minDiff = dicts[nums[i]][2] - dicts[nums[i]][1] + 1
            elif dicts[nums[i]][0] == degree and dicts[nums[i]][2] - dicts[nums[i]][1] + 1 < minDiff:
                degree = dicts[nums[i]][0]
                degreeEle = nums[i]
                minDiff = dicts[nums[i]][2] - dicts[nums[i]][1] + 1
        
        print(degreeEle)
        return minDiff

Python dict类型的基础:


[easy+][Array][遍历时存储信息]697.Degree of an Array_第1张图片
Screen Shot 2017-11-22 at 11.56.15 PM.png

你可能感兴趣的:([easy+][Array][遍历时存储信息]697.Degree of an Array)