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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python https://leetcode.com/problems/degree-of-an-array/description/相关的知识,希望对你有一定的参考价值。

# 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
        

以上是关于python https://leetcode.com/problems/degree-of-an-array/description/的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-003无重复字符的最长子串--python

leetcode练习笔记2022年9月

leetcode413

20-05-01

两数之和(LeetCode)

leetcode刷题两数之和