好久没更新这个系列的博文了,主要是因为放暑假了,我也懒了。。。
这个Wiggle Subsequence 的意思,也就是说有个数组,这个数组的差异是需要交替的,什么事差异呢,就是第I个数相对于第I-1个数的差异,而这里的交替是指正负交替,也就是说第二个数大于第一个数的话,第三个数就要小于第二个数,第四个数又要大于第三个数。。必须是这样严格的交替。。输出这个数组的最长Wiggle Subsequence序列的长度
题目要求O(n)解决。。
其实直接遍历一遍,保留上一次有效的差异(就是不相等时的情况),如果遇到一次有效的交替就计数+1就可以了
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?
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;
}
}
这里我贴一些我自己用来测试的,大家可以贴上去自己试下
[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]