题目描述:
Given an unsorted array nums
, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]...
.
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?
符合要求的顺序有很多,比较简单的方法是先对数组排序,令一个指针指向数组末尾,一个指针指向数组中间,依次向前遍历,遍历的元素加入新建的数组中,这就是排序的结果。需要注意到是,必须从末尾和中间往前遍历,而不能从开头和中间往后面遍历,因为数组中间可能存在多个重复值,例如[4,5,5,6]按开头和中间往后遍历得到的是[4,5,5,6],也就是说这种方法不能把中间的重复数值分开。
class Solution {
public:
void wiggleSort(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size();
vector<int> result;
int mid=0;
if(n%2==0) mid=n/2-1;
else mid=n/2;
int i=mid;
int j=n-1;
while(i>=0&&j>mid)
{
result.push_back(nums[i]);
result.push_back(nums[j]);
i--;
j--;
}
if(n%2==1) result.push_back(nums[0]);
nums=result;
}
};