594. Longest Harmonious Subsequence(python+cpp)

本文介绍了一种算法,用于在给定整数数组中寻找最长的和谐子序列,即两个最频繁出现且值相差为1的元素组合。通过使用Python和C++实现,展示了如何高效地解决此问题。

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

题目:

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:

Input: [1,3,2,2,5,2,3,7] 
Output: 5 
Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 

Note: The length of the input array will not exceed 20,000.

解释:
由于是subsequence,所以可以随便抽选,找到合起来个数最多的两个数字即可,subsequence的长度就是这两个数字个数的总和。
python代码:

import collections
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count =collections.Counter(nums)
        max_len=0
        for x in count:
            if x+1 in count:
                max_len=max(max_len,count[x]+count[x+1])
        return max_len
#include <map>
using namespace std;
class Solution {
public:
    int findLHS(vector<int>& nums) {
        map<int ,int >_map;
        for (auto num:nums)
            _map[num]++;
        int max_len=0;
        for(auto& item:_map)
        {
            if(_map.count(item.first+1))
                max_len=max(max_len,_map[item.first]+_map[item.first+1]);
        }
        return max_len;
    }
};

总结:
合理使用字典,恩

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值