【力扣日记】596 最长和谐子序列 | 哈希

题目描述

和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

!子序列就是包含在数组中,不需要相连,但不能改变数组元素顺序的子数组。

算法思路

class Solution:
    def findLHS(self, nums: List[int]) -> int:
        d={}
        for i in nums:
            d[i]=d.get(i,0)+1
        ls=list(d.items())
        ls.sort()
        # print(ls)
        MAX=0
        for idx in range(len(ls)-1):
            if ls[idx][0]==ls[idx+1][0]-1:
                MAX=max(MAX,ls[idx][1]+ls[idx+1][1])
        return MAX

用字典计数,将字典化作列表:ls=list(d.items()),排序,然后遍历求和即可。

执行用时 :412 ms, 在所有 Python3 提交中击败了48.55%的用户
内存消耗 :15.8 MB, 在所有 Python3 提交中击败了5.66%的用户

发布了210 篇原创文章 · 获赞 20 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Heart_for_Ling/article/details/104839280