2023年9月6日 星期三

9/6 每日一題(返回最短的連續子數組)

 

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: nums = [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: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation: 
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.

 

Constraints:

  • nums.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.
class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
       
        ele_times=Counter(nums)
        print(ele_times)
        max_freq=max(ele_times.values())
        #檢查是否存在最大重複次數是否有相同的其他元素
        my_dict={}
        for k,v in ele_times.items():
            if v == max_freq:
                my_dict[k]=v
        print(my_dict)
        #ex: my_dict={1: 6, 2: 6}
        res={} #打造一個key是重複最高,valu是他對應的索引
        for n,i in enumerate(nums):
            if i in my_dict :
                if i not in res:
                    res[i]=[n]
                else:
                    res[i].append(n)
       
        #ex, res={1: [0, 3, 5, 6, 7, 8], 2: [1, 2, 4, 9, 10, 11]}
        min_len=float('inf')
        for i in res.values():
            min_len=min(min_len,i[-1]-i[0]+1)
        return min_len
   
     #思考方向
1.找出重複次數, 將其中重複平率最高的元素拉出來, 所以用字典 或 List
2.利用找到的最高重複元素, 其記錄該元素的第一次出現索引值,以及最後一次出現的索引值,
找出之間的最短長度




               








       


標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁