594. Longest Harmonious Subsequence --counter类

本文介绍了一种算法,用于从给定整数数组的所有可能子序列中找出最长的和谐子序列,即最大值与最小值之差为1的子序列,并提供两种实现方式:一种是通过构建字典统计元素出现次数,另一种利用Counter类简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们定义一个和谐数组是一个数组,其最大值和最小值之间的差值恰好为1。
现在,给定一个整数数组,你需要在其所有可能的子序列中找出其最长的和谐子序列的长度。注意,和谐数组不一定要求连续
1.

class Solution(object):
    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

2.Counter 集成于 dict 类,因此也可以使用字典的方法,此类返回一个以元素为 key 、元素个数为 value 的 Counter 对象集合

>>> from collections import Counter
>>> s = "hello pinsily"
>>> d = Counter(s)
>>> d
Counter({'l': 3, 'i': 2, 'h': 1, 'e': 1, 'o': 1, ' ': 1, 'p': 1, 'n': 1, 's': 1, 'y': 1})
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = 0
        c = collections.Counter(nums)
        for x in c:
            if x+1 in c:
                ans = max(ans,c[x]+c[x+1])
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值