LeetCode 376. Wiggle Subsequence 摆动子序列

原题

A sequence of numbers is called a wiggle sequence if 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 fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast,[1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

 

题目讲解

  题目叫做摆动子序列,顾名思义就是不断摆动的的点,不能连续上升也不能连续下降,只能一上一下不断摆动,接着我们要知道子序列对于原序列来说虽然不要求连续但是要求保序(子串、子数组要求连续),所以这里也就没必要排序了。

 

示例

Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.

Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].

Input: [1,2,3,4,5,6,7,8,9]
Output: 2

 

思路及代码

"""
这题的思路其实很简单:
    当三个点事连续上升(下降)时,去掉中间的那个点,因为去掉第一个点会影响之前的结果,去掉最后一个点遇到下降的可能性相对较低。
    
    如果相乘为零,则代表是折线点,那么结果加一,判断点向后推一位
    
    下面的代码最费时的地方是相乘的时候,可以优化
    
"""
class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 边界条件
        if len(nums) <= 1:
            return len(nums)
        ans = 1
        # 这里判断有上下折线的方法是求导,相乘为负即为不同
        diff = nums[0] - nums[1]
        if diff != 0:
            ans += 1
        for i in range(2,len(nums)):
            if nums[i] != nums[i - 1]:  # 这里主要是处理相等值的问题
                if diff * (nums[i - 1] - nums[i]) <= 0: # 这里的=0主要是为了处理前面都是相等项到起伏点的情况
                    ans += 1
                    diff = nums[i - 1] - nums[i]
                    
        return ans
        

  

原文地址:https://www.cnblogs.com/LiCheng-/p/6678262.html