Java Simple Solution


  • 1

    The solution is basicly based on comparison. In this case, we don't need to care about the global but focus on the local is fairly enough.

    Traverse from left to right.
    1, if i & 1 == 0, check if nums[i] > nums[i+1]
    2, If i & 1 != 0, check if nums[i] < nums[i+1]
    

    Here is the solution

    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        for (int i = 0; i < nums.length-1; i++) {
            if ((i&1) == 0 && nums[i] > nums[i+1] || (i&1) != 0 && nums[i] < nums[i+1]) {
                int t = nums[i];
                nums[i] = nums[i+1];
                nums[i+1] = t;
            }
        }
    }

Log in to reply
 

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