Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
class Solution {
public:
void wiggleSort(vector<int>& nums) {
int n = nums.size();
if (n < 1)
{
return;
}
sort(nums.begin(), nums.end());
vector<int> temp(n, 0);
int j = n-1;
for (int i = 1; i < n; i += 2, j--)
{
temp[i] = nums[j];
}
for (int i = 0; i < n; i += 2, j--)
{
temp[i] = nums[j];
}
nums = temp;
}
};