Array - 508. Wiggle Sort
508. Wiggle Sort
Given an unsorted array nums
, reorder it in-place such that
nums[0] <= nums[1] >= nums[2] <= nums[3]....
Example
Example 1:
Input: [3, 5, 2, 1, 6, 4]
Output: [1, 6, 2, 5, 3, 4]
Explanation: This question may have multiple answers, and [2, 6, 1, 5, 3, 4] is also ok.
Example 2:
Input: [1, 2, 3, 4]
Output: [2, 1, 4, 3]
Notice
Please complete the problem in-place.
思路:
仔细分析输出数组,可以发现下标索引为奇数的数是极大值点,下标索引是偶数的是极小值点,只要遍历数组的时候,移动相邻两个数,就可以。
代码:
java:
public class Solution {
/*
* @param nums: A list of integers
* @return: nothing
*/
public void wiggleSort(int[] nums) {
if (nums == null || nums.length <= 1) return;
for (int i = 1; i < nums.length; i++) {
if (i % 2 == 1){
if (nums[i - 1] > nums[i]) swap(nums, i - 1, i);
} else {
if (nums[i - 1] < nums[i]) swap(nums, i - 1, i);
}
}
}
private void swap(int[] nums, int i, int j ){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}