Advertisement
wyx0311

电宇智控视觉组第一题

May 15th, 2024
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | Source Code | 0 0
  1. import random
  2. from collections import defaultdict
  3.  
  4. # 生成长度为10的非负数的整数数组
  5. nums = [random.randint(0, 10) for _ in range(10)]
  6. print(f"数组 nums = {nums}")
  7.  
  8. def findShortestSubArray(nums):
  9.     left, right, count = {}, {}, defaultdict(int)
  10.     for i, x in enumerate(nums):
  11.         if x not in left:
  12.             left[x] = i
  13.         right[x] = i
  14.         count[x] += 1
  15.    
  16.     degree = max(count.values())
  17.     min_length = len(nums)
  18.    
  19.     for x in count:
  20.         if count[x] == degree:
  21.             min_length = min(min_length, right[x] - left[x] + 1)
  22.    
  23.     return min_length
  24.  
  25. # 计算并输出最短连续子数组的长度
  26. result = findShortestSubArray(nums)
  27. print(f"{result}")
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement