zoukankan      html  css  js  c++  java
  • [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.

    思路: 假设在下标为 i 的位置已经知道了前面最长wiggle subsequence 的值, 那么对于 i 这个位置wiggle subsequence 的值要么和前面一样,要么比之前多1;

     1 class Solution {
     2 public:
     3     int wiggleMaxLength(vector<int>& nums) {
     4         if (nums.size() <= 1)
     5             return nums.size();
     6         int dp[nums.size()], diff = nums[1] - nums[0]; dp[0] = 1;
     7         int flag = (diff > 0 ? -1 : 1);
     8         for (int i = 1; i != nums.size(); ++i){
     9             diff = nums[i] - nums[i-1];
    10             if ((flag > 0 && diff > 0) || (flag < 0 && diff < 0) || !diff)
    11                 dp[i] = dp[i-1];
    12             else {
    13                 dp[i] = dp[i-1] + 1;
    14                 flag = diff;
    15             }
    16         }
    17         return dp[nums.size() - 1];
    18     }
    19 };
  • 相关阅读:
    java——异常(一)
    java —— 全面解析 Annotation
    多线程(一)——三种实现方式
    java ——static 关键词总结
    java —— equals 与 ==
    java——数组与内存控制
    java—— finall 关键词
    File类实现文件夹和文件复制
    java —— 内部类
    类成员——代码块
  • 原文地址:https://www.cnblogs.com/David-Lin/p/8342030.html
Copyright © 2011-2022 走看看