# Leetcode 697. Degree of an Array

## 2. Solution

• Version 1
```from collections import Counter
class Solution:
def findShortestSubArray(self, nums):
stat = Counter(nums)
degree = 0
result = len(nums)
for key, value in stat.items():
if value > degree:
degree = value

for key, value in stat.items():
if value == degree:
left = 0
right = len(nums) - 1
while nums[left] != key or nums[right] != key:
if nums[left] != key:
left += 1
if nums[right] != key:
right -= 1
sub_length = right - left + 1
if result > sub_length:
result = sub_length
return result```
• Version 2
```from collections import Counter
class Solution:
def findShortestSubArray(self, nums):
stat = Counter(nums)
degree = 0
result = len(nums)
for key, value in stat.items():
if value > degree:
degree = value

for index, value in enumerate(nums):
if value in stat and stat[value] == degree:
end = len(nums) - 1
while nums[end] != value:
end -= 1
sub_length = end - index + 1
del stat[value]
if result > sub_length:
result = sub_length
return result```
• Version 3
```class Solution:
def findShortestSubArray(self, nums):
degree = 0
result = len(nums)
stat = {}
for index, value in enumerate(nums):
if value in stat:
stat[value]['degree'] += 1
stat[value]['end'] = index
else:
stat[value] = {'degree': 1, 'start': index, 'end': index}

sub_length = stat[value]['end'] - stat[value]['start'] + 1
if stat[value]['degree'] > degree:
degree = stat[value]['degree']
result = sub_length
if stat[value]['degree'] == degree and sub_length < result:
result = sub_length

return result```
• Version 4
```class Solution:
def findShortestSubArray(self, nums):
degree = 0
result = len(nums)
stat = {}
for index, value in enumerate(nums):
if value in stat:
stat[value]['degree'] += 1
else:
stat[value] = {'degree': 1, 'start': index}

sub_length = index - stat[value]['start'] + 1
if stat[value]['degree'] > degree:
degree = stat[value]['degree']
result = sub_length
elif stat[value]['degree'] == degree and sub_length < result:
result = sub_length

return result```

## Reference

1. https://leetcode.com/problems/degree-of-an-array/

0 条评论

• ### LWC 54：697. Degree of an Array

LWC 54：697. Degree of an Array 传送门：697. Degree of an Array Problem: Given a non...

• ### Golang Leetcode 697. Degree of an Array.go

更多内容请移步我的repo：https://github.com/anakin/golang-leetcode

• ### ［LeetCode］Degree of an Array 数组的度 ［LeetCode］Degree of an Array 数组的度

链接：https://leetcode.com/problems/degree-of-an-array/description/ 难度：Easy 题目：69...

• ### LeetCode 697. 数组的度

给定一个非空且只包含非负数的整数数组 nums 数组的度的定义是指数组里任一元素出现频数的最大值

• ### LeetCode Weekly Contest 33解题思路

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...

• ### Leetcode 421. Maximum XOR of Two Numbers in an Array

版权声明：博客文章都是作者辛苦整理的，转载请注明出处，谢谢！ https://blog.csdn....

• ### Swift Shuffle an Array - LeetCode

给定两个有序整数数组 nums1 和 nums2，将 nums2 合并到 nums1 中，使得 num1 成为一个有序数组。