MENU

LeetCode376. 摆动序列

July 5, 2018 • Read: 3037 • LeetCode阅读设置

class Solution {
    public int wiggleMaxLength(int[] nums) {
        int state = 0;//分别用0,1,-1表示起始,上升,下降状态
        int length = 1;//最短的摆动序列的长度都是1
        for(int i = 1;i < nums.length;i++){//从第2个数开始遍历
            switch(state){
                case 0:if(nums[i] > nums[i - 1]){
                    state = 1;
                    length++;
                }
                    else if(nums[i] < nums[i - 1]){
                        state = -1;
                        length++;
                    }
                    break;
                case 1:if(nums[i] < nums[i - 1]){
                    state = -1;
                    length++;
                }
                    break;
                case -1:if(nums[i] > nums[i - 1]){
                    state = 1;
                    length++;
                }
                    break;
            }
        }
        return nums.length == 0 ? 0 : length;
    }
}
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code