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].
找出最长的最大最小差为1的子数列。
当然作为一个菜鸟还是做好自己的基本功:暴力解法。
直接双循环
class Solution(object):
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxnum=0
n=len(nums)
for i in range(n):
sub=0
count=0
for j in range(n):
if nums[i]-nums[j] == 1:
sub +=1
if nums[i]-nums[j] == 0:
count +=1
sub +=1
if sub == count: sub=0
if sub > maxnum: maxnum=sub
return maxnum
构造一个变量maxnum存放最大的数量,再构造一个每次遍历找到的数量,为什么要加一个count呢,是因为需要计数防止出现都是同一个元素。
好了献丑完就可以,进入大神们炫技时间:
让一让python大法来了:
class Solution(object):
def findLHS(self,nums):
c=collections.Counter(nums)
return max([c[i]+c[i+1] for i in c if i+1 in c],[0])
这个解法就是运用了字典来一一对应,减少了大量的运算。
完整版是这样的
class Solution(object);
def findLHS(self,nums):
d={}
for i in nums:
if i not in d:
d[i]=1
else:
d[i]+=1
res=0
for i in d:
if i+1 in d:
res=max(res,d[i]+d[i+1])
return res

本文介绍了一种寻找数组中最长和谐子序列的方法,和谐子序列定义为最大值与最小值之差恰好为1的子序列。通过两种不同的解法进行讨论,一种是直接使用双循环的暴力解法,另一种则是利用Python的collections.Counter来提高效率。

被折叠的 条评论
为什么被折叠?



