Discuss with even and odd position


  • 0
    R

    public void wiggleSort(int[] nums) {
    // first sort then switch
    // direct switch divide as even and odd situation
    if(nums==null || nums.length == 0) return;
    for(int i = 0; i < nums.length; i++) {
    if(i%2==1) {
    if(nums[i] < nums[i-1]) { swap(nums, i); }
    //swap
    } else if(i!=0 && nums[i] > nums[i-1]) { swap(nums, i); }
    }

    }
    public void swap(int[] nums, int pos) {
        int temp = nums[pos];
        nums[pos] = nums[pos-1];
        nums[pos-1] = temp;
    }

Log in to reply
 

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