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

相关内容

热门资讯

原创 立... 天气一热,不少人都提不起食欲,饭菜摆在面前也没胃口。家里长辈和小朋友更是明显,整日恹恹的,正餐也吃得...
原创 李... “来李庄不吃三绝,等于白来!”老茶馆里飘出的这句话,道出了古镇美食的灵魂。白肉薄如蝉翼,白糕软糯化渣...
原创 建... 每天早上纠结吃啥,想必是不少人的小烦恼,既想做得省事,又盼着吃得营养。一日三餐里,早餐真的不能敷衍,...
原创 初... 一、清热祛湿汤品 1. 冬瓜薏米排骨汤 食材:排骨300g、冬瓜400g、薏米50g、姜片、盐 做...