# Time: O(n) where n = len(nums)
# Space: O(n)
# 697. Degree of an Array
class Solution2(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
freq = {}
degree = 1
answer = 1
for i, n in enumerate(nums):
if n not in freq:
freq[n] = [1,i]
else:
freq[n][0] += 1
if freq[n][0] > degree:
degree = freq[n][0]
answer = i - freq[n][1] + 1
elif freq[n][0] == degree:
answer = min(answer, i - freq[n][1] + 1)
return answer
# Time: O(2n) where n = len(nums)
# Space: O(3n)
# 697. Degree of an Array
class Solution1(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right, count = {}, {}, {}
for i, n in enumerate(nums):
if n not in left:
left[n] = i
right[n] = i
count[n] = count.get(n, 0) + 1
res = len(nums)
degree = max(count.values())
for n in count:
if count[n] == degree:
res = min(res, right[n]-left[n]+1)
return res
# Time: O(nlogn)
# Space:O(n)
# 697. Degree of an Array
class Solution0(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.Counter(nums)
freq = sorted(count, key=count.get, reverse=True)
degree = count[freq[0]]
i = 0
wait = set()
while i < len(freq) and count[freq[i]] == degree:
wait.add(freq[i])
i += 1
result = {}
for i in range(len(nums)):
if nums[i] in result:
result[nums[i]][0] = i - result[nums[i]][1] + 1
else:
if nums[i] in wait:
result[nums[i]] = [1,i]
end = result[sorted(result, key=result.get, reverse=True)[-1]][0]
return end