LeetCode

来源:互联网 发布:淘宝上海景兰差评 编辑:程序博客网 时间:2024/06/05 20:46

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?


给你一个数组,找出最大的子序列使得,nums[j] - nums[i]为一正一负交替。比如1 2 1 2 1 2……

最开始想了个n^2的思路,没看到有O(n)的条件限制,美滋滋敲完交了AC,结果发现了时间限制。唔,猴吧

先贴一下O(n^2)的,做出dp还是很兴奋的,虽然复杂度so high

class Solution {public:    int wiggleMaxLength(vector<int>& nums) {        if (nums.size() <= 1) return nums.size();        vector<int> dp(nums.size() + 1, 1);     //up        vector<int> dp2(nums.size() + 1, 1);    //down        for (int i = 0; i < nums.size(); ++i) {            for (int j = i + 1; j < nums.size(); ++j) {                if (nums[j] > nums[i]) {                    dp[j] = max(dp[j], dp2[i] + 1);                }                else if (nums[j] < nums[i]) {                    dp2[j] = max(dp2[j], dp[i] + 1);                }            }        }        int mmax = 0;        for (int i = 0; i < nums.size(); ++i) {            mmax = max(mmax, dp[i]);            mmax = max(mmax, dp2[i]);        }        return mmax;    }};
因为要求找出最长的序列,所以我们需要尽可能找出每一次更大、更小的数字。

比如 2 1 3 4 5 3

我们会在遍历过程中,先用 2 1 4 取代 2 1 3,又用 2 1 5 取代 2 1 4,以此。

时间复杂度O(n),空间复杂度O(1)

class Solution {public:    int wiggleMaxLength(vector<int>& nums) {        if (nums.size() <= 1) return nums.size();        int i = 0;        while (i < nums.size() - 1 && nums[i] == nums[i + 1])//去掉重复数字            ++i;        if (i == nums.size() - 1) return 1;                int cnt = 2;        bool flag = nums[i] < nums[i + 1];//决定前一步是up还是down        ++i;        while (i < nums.size()) {            if (flag && nums[i] < nums[i-1]) {                cnt++;                flag = !flag;            }            else if (!flag && nums[i] > nums[i-1]) {                cnt++;                flag = !flag;            }            ++i;        }        return cnt;    }};