链接:https://leetcode.com/problems/wiggle-subsequence/
解题思路:其实只需要比较a[n+1]-a[n]和a[n]-a[n-1]的正负性即可,定义变量flag记录上一次的正负性,current记录上一个的值,count记录满足要求的总和,于是有以下代码:
class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 current = nums[0] count = 1 flag = None for num in nums[1:]: if flag == None: if num == current: continue if num < current: flag = False else: flag = True count += 1 current = num elif flag == True: if num < current: flag = False count += 1 current = num else: if num > current: flag = True count += 1 current = num return count
有几点需要注意的是:
1,初始情况是先向上走还是先向下走是未定的,不论哪种情况,都要将计数器+1
2,初始情况有可能是连续相等的值,此时情况仍未定