leetcode 376 摆动序列
def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 diff=[] for i in range(1,len(nums)): if nums[i]-nums[i-1]>0: diff.append(1) elif nums[i]-nums[i-1]<0: diff.append(2) if not diff: return 1 #处理相等的数的情况 ans=1 for i in range(1,len(diff)): if diff[i]!=diff[i-1]: ans+=1 return ans+1
def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ diffs=[a-b for a,b in zip([float('nan')]+nums,nums+[float('nan')]) if a-b] return sum(not a*b>0 for a,b in zip(diffs,diffs[1:])) #not是为了排除nan的情况
方法二:
def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ # dp solution if not nums: return 0 down,up=1,1 for i in range(1,len(nums)): if nums[i]>nums[i-1]: up=down+1 elif nums[i]<nums[i-1]: down=up+1 return max(down,up)