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]
.
Solution:
The rule is each element at odd index is smaller than the next element while element at even index is greater than the next. So we can sort the array according to the definition.
Time complexity: O(n)
Space complexity: O(1)
public class Solution {
public void wiggleSort(int[] nums) {
int length = nums.length;
boolean odd = true;
for (int i = 0; i < length - 1; i++) {
if (odd) {
if (nums[i] > nums[i + 1]) {
swap(nums, i, i + 1);
}
odd = !odd;
} else {
if (nums[i] < nums[i + 1]) {
swap(nums, i, i + 1);
}
odd = !odd;
}
}
}
private void swap (int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}