https://leetcode.com/problems/wiggle-subsequence/?tab=Description
本题两解,均为Time:O(N);Space:O(1)。关键在于当nums[i] > nums[i - 1]时,上摆数组长度为下摆数组长度加一,反之亦然。
解法一:
public class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int cnt1 = 1;
int cnt2 = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
cnt1 = cnt2 + 1;
} else if (nums[i] < nums[i - 1]) {
cnt2 = cnt1 + 1;
}
}
return Math.max(cnt1, cnt2);
}
}
解法二:
用needSmall来标记当前摆动方向。需要比较的是nums[i]和nums[i - 1]而不是当前获得的摆动数组的结尾数字。
public class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int k = 0;
while (k < nums.length - 1 && nums[k] == nums[k + 1]) {
k++;
}
if (k == nums.length - 1) {
return 1;
}
boolean needSmall = nums[k] < nums[k + 1];
int res = 2;
for (int i = k + 1; i < nums.length; i++) {
if (needSmall && nums[i] < nums[i - 1]) {
res++;
needSmall = false;
} else if (!needSmall && nums[i] > nums[i - 1]) {
res++;
needSmall = true;
}
}
return res;
}
}