Question
Given an integer array nums
, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
.
You may assume the input array always has a valid answer.
Example 1:
Input: nums = [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
Explanation: [1,6,2,5,3,4] is also accepted.
Example 2:
Input: nums = [6,6,5,6,3,8]
Output: [6,6,5,6,3,8]
Constraints:
1 <= nums.length <= 5 * 104
0 <= nums[i] <= 104
- It is guaranteed that there will be an answer for the given input
nums
.
Follow up: Could you solve the problem in O(n)
time complexity?
Algorithm
- TBH, I was inspired by the explanation of first example
- The description of the question illustrated that there must be a valid answer.
- So I order the numbers and pick smallest and largest one by one to assemble a valid answer -> Code1
- Actually I don't have to create a temp array to store the numbers. Swapping the nums[i+1] and nums[i] can be a valid answer -> code2
- Or like what I did first and last, same idea;
- A O(n) solution is that, we use greedy algorithm. A detailed expiation is here. ->code3
Code1
class Solution { public void wiggleSort(int[] nums) { Arrays.sort(nums); int[] res = new int[nums.length]; int i = 0, j = nums.length - 1; int x = 0; while (i <= j) { if (i != j) { res[x++] = nums[i++]; res[x++] = nums[j--]; } else { res[x++] = nums[i++]; } } for (i = 0; i < nums.length; i++) { nums[i] = res[i]; } } }
Code2
class Solution { public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public void wiggleSort(int[] nums) { Arrays.sort(nums); for (int i = 1; i < nums.length - 1; i += 2) { swap(nums, i, i + 1); } } }
Code3
class Solution { public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public void wiggleSort(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { if (((i % 2 == 0) && nums[i] > nums[i + 1]) || ((i % 2 == 1) && nums[i] < nums[i + 1])) { swap(nums, i, i + 1); } } } }