Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize the degree of Array by leetcode

Shulou Source: shulou.com Published: 2022-06-01 13:21:24 10月02日 Update

Editor to share with you how to achieve the degree of leetcode array, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

I. the content of the topic

Given an array of integers nums that is not empty and contains only non-negative numbers, the degree of the array is defined as the maximum occurrence frequency of any element in the exponential group.

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

Example 1:

Enter: [1, 2, 2, 3, 1]

Output: 2

Explanation:

The degree of the input array is 2, because elements 1 and 2 have the highest occurrence frequency, both 2. 5%.

The ones that have the same degree in a continuous subarray 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 it returns 2.

Example 2:

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

Output: 6

Tip:

Nums.length is in the range of 1 to 50000.

Nums [I] is an integer in the range of 0 to 49999.

Second, the way to solve the problem

Record the position of each number, then get the maximum length (the maximum degree), and finally record the shortest continuous subarray when the degree is maximum.

Code class Solution: def findShortestSubArray (self Nums: list)-> int: nums_dict = {} for i in range (len (nums)): if nums [I] not in nums_dict: nums_ [nums [I]] = [I] else: nums_ [nums [I]] .append (I) max_length = 0 for num in nums_dict : max_length = max (max_length Len (nums_ cycles [num]) min_length = len (nums) for num in nums_dict: if len (nums_ cycles [num]) = max_length: min_length = min (min_length, nums_ cycles [num] [- 1]-nums_ cycles [num] [0] + 1) return min_lengthif _ name__ ='_ main__': s = Solution () nums = [1PUR 2 Ans = s.findShortestSubArray (nums) print (ans) are all the contents of the article "how to achieve the degree of an array by leetcode" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Array maximum content article length input same element degree integer example range frequency output not so code task location interval size Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Redmi vpn MariaDB macOS