我们定义一个和谐数组是一个数组,其最大值和最小值之间的差值恰好为1。
现在,给定一个整数数组,你需要在其所有可能的子序列中找出其最长的和谐子序列的长度。注意,和谐数组不一定要求连续
1.
class Solution(object):
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict1 = {}
x = 0
b = 0
for i in range(len(nums)):
dict1[nums[i]] = dict1.get(nums[i],0) + 1
for v in dict1:
if v + 1 in dict1:
b = dict1[v] + dict1[v+1]
if b > x:
x = b
return x
2.Counter 集成于 dict 类,因此也可以使用字典的方法,此类返回一个以元素为 key 、元素个数为 value 的 Counter 对象集合
>>> from collections import Counter
>>> s = "hello pinsily"
>>> d = Counter(s)
>>> d
Counter({'l': 3, 'i': 2, 'h': 1, 'e': 1, 'o': 1, ' ': 1, 'p': 1, 'n': 1, 's': 1, 'y': 1})
class Solution(object):
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
c = collections.Counter(nums)
for x in c:
if x+1 in c:
ans = max(ans,c[x]+c[x+1])
return ans