Leetcode 376. Wiggle Subsequence 摇摆序列 解题报告

1 解题思想

好久没更新这个系列的博文了,主要是因为放暑假了,我也懒了。。。

这个Wiggle Subsequence 的意思,也就是说有个数组,这个数组的差异是需要交替的,什么事差异呢,就是第I个数相对于第I-1个数的差异,而这里的交替是指正负交替,也就是说第二个数大于第一个数的话,第三个数就要小于第二个数,第四个数又要大于第三个数。。必须是这样严格的交替。。输出这个数组的最长Wiggle Subsequence序列的长度

题目要求O(n)解决。。
其实直接遍历一遍,保留上一次有效的差异(就是不相等时的情况),如果遇到一次有效的交替就计数+1就可以了

2 原题

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.
Examples:
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

Follow up:
Can you do it in O(n) time?

3 AC解

public class Solution {
    public int wiggleMaxLength(int[] nums) {
        int n = nums.length;
        if(n <= 1)
            return n;
        int result = nums[0] != nums[1] ? 2:1;
        int flag = nums[1] - nums[0];
        for(int i=2;i<nums.length;i++){
            if((nums[i] - nums[i-1]) * flag < 0 || (flag==0 && (nums[i] - nums[i-1])!=0)){
                result ++;
                flag = nums[i] - nums[i-1];
            }
        }
        return result;
    }
}

4 TestCases

这里我贴一些我自己用来测试的,大家可以贴上去自己试下

[1,7,4,9,2,5]
[1,17,5,10,13,15,10,5,16,8]
[1,2,3,4,5,6,7,8,9]
[0,0]
[5,4,2,5,5,7,9,7,8]
[0,0,0,0]
[0,0,0,0,1,5,3,4,5,3,4,2]
[0,0,0,0,1,5,3,4,5,3,4,2,2,2,2,2,2,2,5,6,3,4]
[5,5,5,5,4,4,4,4,3,3,3,3,2,2,2,2,1,1,1,1,1]
[5,5,5,5,4,4,4,4,3,3,3,3,2,2,2,2,1,1,1,1,1,6,6,6,6,6]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值