280 Wiggle Sort

280. Wiggle Sort

1. Question

Given an unsorted arraynums, reorder itin-placesuch thatnums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, givennums = [3, 5, 2, 1, 6, 4], one possible answer is[1, 6, 2, 5, 3, 4].

2. Implementation

1
class Solution {
2
public void wiggleSort(int[] nums) {
3
for (int i = 0; i < nums.length - 1; i++) {
4
if (i % 2 == 0 && nums[i] > nums[i + 1] ||
5
i % 2 == 1 && nums[i] < nums[i + 1]) {
6
swap(nums, i, i + 1);
7
}
8
}
9
}
10
11
public void swap(int[] nums, int i, int j) {
12
int temp = nums[i];
13
nums[i] = nums[j];
14
nums[j] = temp;
15
}
16
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)