594. Longest Harmonious Subsequence
题目描述
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的数字个数。列表方法:
list.count(obj) #统计元素obj在列表中出现的次数
(2)将各个‘和谐’序列的长度存储在字典中,然后按照属性值values的大小进行排序。
只能使用sorted方法,因为sort方法只能用于列表的排序。
sorted_dic=sorted(dic.items(),key=lambda x: x[1], reverse=True)
dic.items()将字典的‘键值对’按照元组的方式存储,key规定按照元组的第二个元素即属性值values来排序,reverse=True表示按照降序排序。
使用上述方法,耗用大量时间和空间,提交答案时会出现运行时间超出上界的错误。
正确解法
collections模块的Counter类:为hashable的对象计数,是字典的子类。可以统计字符出现的个数。
Counter类的创建Python
>>> c = Counter() # 创建一个空的Counter类
>>> c = Counter('gallahad') # 从一个可iterable对象(list、tuple、dict、字符串等)创建
>>> c = Counter({'a': 4, 'b': 2}) # 从一个字典对象创建
>>> c = Counter(a=4, b=2) # 从一组键值对创建
(1)生成计数字典
cnt=collections.Counter(nums) #统计nums中各个数字出现的次数
(2)统计最大个数
for n in cnt:
if n+1 in cnt: #若比该元素大1的值出现了,则统计
ans=max(ans,cnt[n]+cnt[n+1])
上述代码可以精简至一行
ans=max(cnt[n]+cnt[n+1] if n+1 in cnt for n in cnt)
(3)多加一个判断条件,若nums为空,直接返回0
return ans if nums else 0
整合上述代码
class Solution(object):
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt=collections.Counter(nums)
return max(cnt[n]+cnt[n+1] if n+1 in cnt else 0 for n in nums)if nums else 0