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

相关内容

热门资讯

“江湖”好物出征草原 拉满赛场... 5月30日,通辽体育中心体育场,东北超第二轮鸡西对阵通辽的比赛还没开球,赛场外已经先“热”了起来。 ...
原创 告... 编辑:[太阳] 我们现在吃到的很多西红柿,早就不是老味道里的那颗西红柿了,它看着更红、更圆、更硬、更...
原创 中... 说句掏心窝子的话,豆腐脑这玩意儿,是中国人餐桌上最"吵架"的食物,没有之一。 你要是敢在网上发一句"...
张铁林的嘴有多刁?吃月饼只吃品... 吃五仁的。还真是五仁的,我就喜欢吃五仁的。老派,我吃自来红(月饼),西安叫水晶饼。那是我的命,就喜欢...
原创 高... 高考前期,这6道“益智菜”常做给孩子吃,补脑又解压,助力金榜题名! 距离高考只剩最后冲刺阶段,孩子...