【leetcode 簡單】 第一百四十六題 最長和諧子序列
阿新 • • 發佈:2018-08-31
key 數組長度 元素 bsp etc from leet num fin
和諧數組是指一個數組裏元素的最大值和最小值之間的差別正好是1。
現在,給定一個整數數組,你需要在所有可能的子序列中找到最長的和諧子序列的長度。
示例 1:
輸入: [1,3,2,2,5,2,3,7] 輸出: 5 原因: 最長的和諧數組是:[3,2,2,2,3].
說明: 輸入的數組長度最大不超過20,000.
from collections import Counter class Solution: def findLHS(self, nums): """ :type nums: List[int] :rtype: int""" new_nums=Counter(nums) tmp = 0 lastkey,lastvalue=None,None for key,value in sorted(new_nums.items()): if lastkey is not None and lastkey +1 ==key: tmp = max(tmp,value+lastvalue) lastkey,lastvalue=key,value return tmp
【leetcode 簡單】 第一百四十六題 最長和諧子序列