280. Wiggle Sort

Problem:
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]
Analysis:

3/15/2018 update:
If the index is odd, the number is peak. Otherwise, is valley. Loop through the array, if nums[i]  and nums[i - 1] violates the trend, swap them.

How do we know that the above approach works. For instance



If we reach index 3, we found that nums[3] < nums[2], we need to swap them. Before swapping, we know that nums[1] > nums[2] >nums[3]. We will swap a smaller number to left, still follow the wiggle trend.

Solution:


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

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array