324 Wiggle Sort II
324. Wiggle Sort II
1. Question
Given an unsorted arraynums, reorder it such thatnums[0] < nums[1] > nums[2] < nums[3]....
Example:
(1) Givennums = [1, 5, 1, 1, 6, 4], one possible answer is[1, 4, 1, 5, 1, 6].
(2) Givennums = [1, 3, 2, 2, 3, 1], one possible answer is[2, 3, 1, 3, 1, 2].
Note: You may assume all input has valid answer.
Follow Up:
2. Implementation
(1) Sort
class Solution {
public void wiggleSort(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
Arrays.sort(nums);
int n = nums.length;
int[] temp = new int[n];
int low = (n + 1) / 2, high = n;
for (int i = 0; i < n; i++) {
temp[i] = i % 2 == 0 ? nums[--low] : nums[--high];
}
for (int i = 0; i < n; i++) {
nums[i] = temp[i];
}
}
}(2) Quick Select
3. Time & Space Complexity
Sort : 时间复杂度O(nlogn), 空间复杂度O(n)
Quick Select: 时间复杂度O(n), 空间复杂度O(n)
Last updated
Was this helpful?