Thursday, May 26, 2016

Wiggle Sort


Given an unsorted array nums, reorder it in-place such that
nums[0] <= nums[1] >= nums[2] <= nums[3]....
Notice
Please complete the problem in-place.

Wow, first one finish in 5 minutes :)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Solution {
    /**
     * @param nums a list of integer
     * @return void
     */
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
        for(int i=1;i<nums.length-1;i+=2){
            int tmp=nums[i];
            nums[i]=nums[i+1];
            nums[i+1]=tmp;
        }
    }
}

No comments: