LeetCode 376. Wiggle Subsequence

来源:互联网 发布:整理相册的软件 编辑:程序博客网 时间:2024/04/29 08:16

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.

二、输入输出

Examples:

Input: [1,7,4,9,2,5]Output: 6The entire sequence is a wiggle sequence.Input: [1,17,5,10,13,15,10,5,16,8]Output: 7There 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?

三、解题思路

贪心算法

  • 养成一个好习惯,首先处理特殊情况:数组长度为0或为1
  • 将数组的diff存储到一个单独的数组中,然后遍历diff数组
  • 使用贪心算法,尽可能的多的把符合条件的加进来。其实位置需要单独处理,因为diff==0的是不能要的,一直找直到找到第一个不为零的。如果数组结束了,说明所有数都相等,返回1.否则如果相邻两个数是异号的那么count++,并跟新last last中记录的是最终选出来子序列最后一个diff的符号。如果是同号,那么直接跳过该点即可。
  • count中是记录的diff中子序列的长度,原序列的长度是count+1
  • 判断是不是同号,只需要把两者相乘,如果为正则同号,如果为负,则异号。注意同样不能为零。
class Solution {public:    int wiggleMaxLength(vector<int>& nums) {        if(nums.size() == 0)return 0;        if(nums.size() == 1)return 1;        vector<int> diff;        for (int i = 1, n = nums.size(); i < n; ++i) {            diff.push_back(nums[i] - nums[i-1]);        }        int last, count = 0, first = 0;        while(first < diff.size() && diff[first] == 0) first++;        if(first == diff.size())return 1;        else{            count = 1;            last = diff[first];        }        for (int j = first + 1, n = diff.size(); j < n; ++j) {            if(diff[j] * last < 0){                count++;                last = diff[j];            }        }        return count+1;    }}; 
原创粉丝点击