LeetCode知识点总结 - 376
admin
2024-01-19 07:08:10

LeetCode 376. Wiggle Subsequence

考点难度
DPMedium
题目

A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.

For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.

Given an integer array nums, return the length of the longest wiggle subsequence of nums.

思路

O(n) time, O(1) space

答案
class Solution:def wiggleMaxLength(self, nums):if not nums:return 0length = 1up = None # current is increasing or notfor i in range(1, len(nums)):if nums[i] > nums[i - 1] and up != True:length += 1up = Trueif nums[i] < nums[i - 1] and up != False:length += 1up = Falsereturn length

相关内容

热门资讯

导游强逼旅客购物,香港严惩旅游... 来源:环球时报【环球时报综合报道】香港特区政府严惩旅游业“害群之马”,又有两家旅行代理商以及一名导游...
沙虫酸奶拉高股价?燕塘乳业回应... 产品口味颠覆性创新,正成为区域乳企突围的新尝试。 近日,广东老牌乳企燕塘乳业旗下子公司推出的沙虫、生...
13道 风味热卖菜 百宴技为先、修得方成艺——马涛! 我是马涛,深耕酒店、餐饮一线工作至今30年,致力于酒店、餐饮经营有...
扬州人在上海大厦当主厨,把大闸... 外白渡桥畔,苏州河与黄浦江在此交汇。上海大厦在一旁已矗立近百年,二楼藏着一家叫“Le Reflet”...