A different O(N) O(1) solution in Java


  • 0
    R

    This solution is a little bit different from others I've seen in that I rely on a flag to determine if the wiggle is still valid. If it is valid I continue incrementing the counter. If it is invalid, I do not increment the counter and continue looking down the array, essentially ignoring the index. The case of the flag == 0 is special in that it can be 0 for as long as the first index is repeatedly equivalent to the nth index.

        public int wiggleMaxLength(int[] nums) {
        	if (nums.length <= 1) {
        		return nums.length;
        	}
            int previous = nums[0];
        	int flag = 0;
            int length = 1;
        	for (int i = 1; i < nums.length; i++) {
        		if (previous < nums[i] && flag == 1) {
        			length++;
        			flag = 2;
        		} else if (previous > nums[i] && flag == 2) {
        			length++;
        			flag = 1;
        		} else if (flag == 0) {
        		    if (previous < nums[i]) {
            		length++;
            		flag = 2;
            	    } else if (previous > nums[i]) {
           			length++;
           			flag = 1;
           		    }
        		}
    		previous = nums[i];
        	}
        	return length;
        }
    

Log in to reply
 

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