Java 0ms solution


  • 1
    Z

    Replace the array element nums[i] as
    1, if nums[i]>nums[i+1];
    0, if nums[i]=nums[i+1];
    -1, if nums[i]<nums[i+1].
    Below is the accepted code:

    public int wiggleMaxLength(int[] nums) {
        if(nums.length<=1) return nums.length;
        for(int i=0;i<nums.length-1;i++){
           nums[i]=nums[i+1]-nums[i];
           if(nums[i]>0) nums[i]=1;
           else if(nums[i]<0) nums[i]=-1;
           else nums[i]=0;
        }
        int k=-1;
        int res=2;
        while(++k<nums.length-1&&nums[k]==0);
        if(k==nums.length-1) return 1;
        int temp=nums[k];
        for(int i=k;i<nums.length-2;i++){
            if(nums[i+1]+temp==0){
                temp=nums[i+1];
                res++;
            }
        }
        return res;
    }
    

    Thanks @StefanPochmann for pointing out error in case [0,0] and [0,0,0].


  • 0

    Wrong answer for [0,0] and crashes for [0,0,0].


  • 0
    Z
    This post is deleted!

  • 0
    Z

    @StefanPochmann You are right, I didn't check this case...Thanks a lot. I will revise the code.


Log in to reply
 

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