LeetCode--Python解析【Longest Harmonious Subsequence】(594)

题目:


方法:

首先创建一个dict,将nums中的数字遍历至dict中,key为数字,value为数字出现的次数

然后在dict的key值中查看是否存在差值为1的另一个key值

如若存在证明nums中存在差值为1的数组,计算其长度

最后返回长度最长的和谐子序列

class Solution:
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dict1 = {}
        x = 0
        b = 0
        for i in range(len(nums)):
            dict1[nums[i]] = dict1.get(nums[i],0) + 1
        for v in dict1:
            if v + 1 in dict1:
                b = dict1[v] + dict1[v+1]
                if b > x:
                    x = b
        return x

猜你喜欢

转载自blog.csdn.net/zjrn1027/article/details/80208329