http://www.lintcode.com/en/problem/wiggle-sort/
Given an unsorted array nums
, reorder it in-place such that
nums[0] <= nums[1] >= nums[2] <= nums[3]....
从前往后遍历,将当前与前一位置比较不满足的交换即可。因为前一位置满足条件,所以当前位置交换过去之后肯定满足条件(举个例子写一下就知道了)
public class Solution {
/**
* @param nums a list of integer
* @return void
*/
public void wiggleSort(int[] nums) {
// Write your code here
for (int i = 1; i < nums.length; 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;
}
}
}
}