【英文题目】(学习英语的同时,更能理解题意哟~)
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.
【中文题目】
和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
示例 1:
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
【思路】
对所有元素进行计数,对大小相邻的元素其计数进行求和,取得最大值。
【代码】
python版本
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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有