Java Solution


  • 0
    R

    Dry run it with [1,2,3,4,5] and [1,2,3,1,5] to better understand.

    public void wiggleSort(int[] nums) {
            if(nums == null)
                return;
            for(int i = 1; i < nums.length; i += 2) {
                if(nums[i] < nums[i - 1])
                    swap(nums, i, i - 1);
                if(i + 1 < nums.length && nums[i] < nums[i + 1])
                    swap(nums, i, i + 1);
            }
        }
        
        public void swap(int a[], int i, int j) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    

Log in to reply
 

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