前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T52-最长和谐子序列

【leetcode刷题】T52-最长和谐子序列

作者头像
木又AI帮
修改2019-07-18 10:06:56
5180
修改2019-07-18 10:06:56
举报
文章被收录于专栏:木又AI帮木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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:

代码语言:javascript
复制
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.

【中文题目】

和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。

现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

示例 1:

代码语言:javascript
复制
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].

说明: 输入的数组长度最大不超过20,000.

【思路】

对所有元素进行计数,对大小相邻的元素其计数进行求和,取得最大值。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        min0 = sys.maxsize
        max0 = -sys.maxsize
        d = {}
        for n in nums:
            d[n] = d.get(n, ) + 
            min0 = min(min0, n)
            max0 = max(max0, n)
        res = 
        for i in d.keys():
            if i+ in d:
                res = max(res, d[i] + d[i+])
        return res
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档