Leikou Brushing Notes: 697. Degree of Array (Classic Hash Table Questions, Detailed Solution Ideas and Code Notes)

topic:

697. The degree of the array
Given a non-empty integer array nums that only contains non-negative numbers, the degree of the array is defined as the maximum value of any element in the exponent group.

Your task is to find the shortest continuous sub-array in nums with the same degree as nums and return its length.

Example 1:

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The degree of the input array is 2, because the frequency of elements 1 and 2 is the largest, both of which are 2. The
continuous sub-arrays with the same degree are as follows Shows:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The length of the shortest continuous sub-array [2, 2] is 2, so it returns 2.

Example 2:

Input: [1,2,2,3,1,4,2]
Output: 6

prompt:

nums.length is in the range of 1 to 50,000.
nums[i] is an integer in the range of 0 to 49,999.

Problem solution ideas:

1. Each key of the hash table is set to the value of nums[i], and values ​​is set to the index value of this value, which is convenient for calculating the length of the degree.
2. Find the degree of the array, and then find the element that has the same size as the degree, and calculate the shortest sub-array length according to the first and last positions of the element.

Note: There may be more than one element that is consistent with the degree, and it needs to be updated cyclically. In addition, the shortest sub-array length must be the difference between the first and last position indexes of the element

Note that when defining the dictionary type, you need to use the collection.defaultdict(list) function, because ordinary dict() does not allow the addition of keys that are not predefined by d[].append.

Problem solution python code:

class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        d = collections.defaultdict(list)
        for i in range(len(nums)):
            d[nums[i]].append(i)  # 哈希表每个key设置为nums[i]的值,values设置为该值的索引值,方便计算度的长度
        # 按出现次数排序
        t = sorted(d, key=lambda x: len(d[x]), reverse=True)
        # 确定度
        degree = len(d[t[0]])
        # 找到满足度为degree的最短子数组
        ans = 50000
        for i in t:  # 设置这个循环是为了排序有多个出现都为degree的值,如示例1中的1和2
            if len(d[i])==degree:
                ans = min(ans, d[i][-1]-d[i][0]+1)
            else:
                break
        # print(t, d)
        return ans

Insert picture description here

Author: a-qing-ge
Links: https://leetcode-cn.com/problems/degree-of-an-array/solution/ha-xi-biao-su-du-hen-kuai-by-a-qing -ge-vme9/
Source: LeetCode (LeetCode) https://leetcode-cn.com/problems/degree-of-an-array/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/113881244