Punch card question 12

#左耳音风 ARST check-in activity restart#

Table of contents

 1. Problems

2. Problem solving method one

 3. Problem solving method 2


Interpretation of ARTS - Complete one ARTS per week:
● Algorithm: Do at least one LeetCode algorithm problem per week
● Review: Read and comment on at least one English technical article
● Tips: Learn at least one technical skill
● Share: Share one Technical articles with opinions and thoughts

It is hoped that through this event, a wave of people who love technology can be gathered, and the spirit of curiosity, exploration, practice, and sharing can be continued.
 


 1. Problems

Given a non-empty integer array nums containing only non-negative numbers, the degree of the array is defined as the maximum frequency of occurrence of any element in the array.

Your task is to find the shortest contiguous subarray in nums that has the same degree as nums and return its length.

Example 1:

Input: nums = [1,2,2,3,1]
Output: 2
Explanation:
The degree of the input array is 2, because elements 1 and 2 have the highest frequency of occurrence, both are 2.
The consecutive subarrays with the same degree are as follows:
[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 subarray [2, 2] is 2, so return 2.

Example 2: 

Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree of the array is 3 because element 2 repeats 3 times.
So [2,2,3,1,4,2] is the shortest subarray, so 6 is returned.
 

hint:

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

2. Problem solving method one

def findShortestSubArray(nums):
    # 统计每个数字出现的频数和第一次出现的位置
    count = {}
    first_occurrence = {}
    max_degree = 0
    
    for i, num in enumerate(nums):
        if num not in count:
            count[num] = 1
            first_occurrence[num] = i
        else:
            count[num] += 1
        
        # 更新最大度
        if count[num] > max_degree:
            max_degree = count[num]
    
    # 找到与最大度相同的数字的最短连续子数组长度
    min_length = float('inf')
    
    for num in count:
        if count[num] == max_degree:
            length = i - first_occurrence[num] + 1
            if length < min_length:
                min_length = length
    
    return min_length

This code implements a function `findShortestSubArray`, which is used to find the length of the shortest contiguous subarray corresponding to the most frequently occurring number in a given array.

The specific implementation process is as follows:

  1. First, three dictionary variables are defined: `count`, `first_occurrence` and `max_degree`, which are used to count the frequency of occurrence of each number, the position of the first occurrence and the maximum degree (that is, the number of occurrences of the largest number) The number of occurrences).

  2. Then traverse the input array `nums`, for each number `num`, if it is not in `count`, add it to `count` and record its first occurrence position; otherwise, put it Increment the number of occurrences by one. At the same time, if the number of occurrences of the current number is greater than the previous maximum degree, update the maximum degree.

  3. Then traverse each number in `count`, if the number of occurrences of a number is equal to the maximum degree, then calculate the length of the shortest continuous sub-array corresponding to the number. Specifically, first calculate the difference between the last position of the number and the first position plus one, which is the length of the sub-array corresponding to the number; then compare this length with the shortest continuous sub-array calculated before Lengths are compared, and the smaller value is taken as the new shortest continuous subarray length.

  4. Finally, return the calculated length of the shortest continuous subarray.

It should be noted that when calculating the length of the shortest continuous sub-array, the variable `i` needs to be used to record the current traversed position, so `i` needs to be initialized to 0 before the loop starts.

 3. Problem solving method 2

def findShortestSubArray(nums):
# 使用哈希表记录每个数字出现的次数和位置
count = {}
for i, num in enumerate(nums):
if num not in count:
count[num] = [1, i]
else:
count[num][0] += 1

# 按照出现次数从大到小排序
sorted_count = sorted(count.items(), key=lambda x: x[1][0], reverse=True)

# 找到出现次数最多的数字所对应的最短连续子数组长度
max_degree = sorted_count[0][1][0]
min_length = float('inf')

for num, (degree, _) in enumerate(sorted_count):
    if degree == max_degree:
        length = nums[_] + nums[_ + degree] + 1
        if length < min_length:
            min_length = length

return min_length

 This implementation is similar to the previous implementation, but uses a hash table to record the number and position of each number, avoiding multiple calculations of the number of occurrences when traversing the array. At the same time, sorting the elements in the hash table according to the number of occurrences from large to small can reduce the complexity of subsequent searches. Finally, by traversing the sorted hash table, find the length of the shortest contiguous subarray corresponding to the most frequently occurring number.

Guess you like

Origin blog.csdn.net/m0_49914128/article/details/132015372