My code:
public class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
else if (nums.length == 1) {
return 1;
}
boolean nextBig = false;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[0]) {
nextBig = true;
break;
}
else if (nums[i] < nums[0]) {
nextBig = false;
break;
}
}
Stack<Integer> st = new Stack<Integer>();
st.push(nums[0]);
for (int i = 1; i < nums.length; i++) {
if (nums[i] > st.peek()) {
if (nextBig) {
st.push(nums[i]);
nextBig = !nextBig;
}
else {
st.pop();
st.push(nums[i]);
}
}
else if (nums[i] < st.peek()) {
if (nextBig) {
st.pop();
st.push(nums[i]);
}
else {
st.push(nums[i]);
nextBig = !nextBig;
}
}
}
return st.size();
}
}
reference:
https://discuss.leetcode.com/topic/51946/very-simple-java-solution-with-detail-explanation/2
這道題目沒能自己做出來。
哎,發現新題,稍微難一些,基本就做不出來了。
這道題目官方給的題解,用了很多方法:
https://leetcode.com/articles/wiggle-subsequence/
DP那些實在有些看不動了。大腦有點累,轉不動了。
Greedy 的思想最容易理解。
就是先確定 index 0,1 的大小關系。
比如 num1[0] > nums[1] , 那么下面我們就需要 nums[1] < nums[2]
如果 nums[2] < nums[1] ,那就把 nums[1] delete, 加入 nums[2]
就這樣,保證頂部的永遠是 max / min peak
這道題目可以不用棧,用一個 pre variable 就能存。
但如果有 follow up 要求還原出這個 array,那就必須得用棧來做記錄了。
Anyway, Good luck, Richardo! -- 09/21/2016