【LeetCode】376. Wiggle Subsequence 摆动序列(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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.
Example 1:
Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
Example 2:
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Example 3:
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
题目大意
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
你能否用 O(n) 时间复杂度完成此题?
解题方法
- 找出第一个是升序还是降序,然后找下一个反方向的
- 如果第一为升序,如果当前 nums[i] == pre,直接不用管;如果 nums[i] > pre, pre 替换为 nums[i], 因为为了下次降序可以用更大的数字;如果 nums[i] < pre, 说明下一个是降序,count++, pre = nums[i],开始新的找升序
- 降序也是同理
class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length <= 0) return 0;
int pre = nums[0];
int count = 1;
boolean flag = true;
int start = 1;
while (start < nums.length && nums[start] == nums[0]) {
start++;
}
if (start >= nums.length) return count;
if (nums[start] > pre) {
flag = true;
} else {
flag = false;
}
count++;
pre = nums[start];
for (int i = start + 1; i < nums.length; i++) {
if (nums[i] == pre) continue;
if (flag && nums[i] < pre) {
count++;
flag = false;
} else if (!flag && nums[i] > pre) {
count++;
flag = true;
}
pre = nums[i];
}
return count;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36 MB,击败了62.58% 的Java用户