O(n) Solution


  • 0
    W

    就是一遍扫过去,之前上升的话下降就加一,所以设一个状态描述之前是上升还是下降。。规律发现完整扫一遍就是最大值
    public class Solution {
    public int wiggleMaxLength(int[] nums) {
    if(nums.length==2&&(nums[0]==nums[1])){
    return 1;
    }
    if(nums.length==2&&(nums[0]!=nums[1])){
    return 2;
    }

    	if(nums.length<=1){
    	    return nums.length;
    	}
    	int state=3;//不确定状态 1上升 -1 下降 0 平稳
    	
    	int max=0;
    	for(int i=1;i<nums.length;i++){
    		if(state==3){
    		    
    			if(nums[i]-nums[i-1]>0){
    				 state=1;
    				 max=2;
    				 continue;
    			}
    			if(nums[i]-nums[i-1]<0){
    				 state = -1;
    				 max=2;
    				 continue;
    			}
    			else {
    				state=0;
    				max=1;
    				continue;
    			}
    		}
    		if(state==1){
    			if(nums[i]<nums[i-1]){
    				max++;
    				state=-1;
    				continue;
    			}
    			else{
    				continue;
    			}
    		}
    		if(state == 0){//遇到前后两个相同的数
    			continue;
    		}
    		if(state == -1){
    			if(nums[i]>nums[i-1]){
    				max++;
    				state = 1;
    				continue;
    			}
    			else continue;
    		}
    	}
    	return max;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.