题目描述:
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 1:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
Follow up:
Can you do it in O(n) time and/or in-place with O(1) extra space?
思路:
注意怎么排放能让两端的中位数不可能相遇。
代码:
class Solution {
public:
void wiggleSort(vector<int>& nums) {
int len = nums.size();
sort(nums.begin(), nums.end());
vector<int> ans;
int cnt = len / 2;
int tt = 0;
for (int i=len-cnt-1; i>=0; --i) {
ans.push_back(nums[i]);
if (tt < cnt) {
ans.push_back(nums[len-1-tt]);
tt++;
}
}
nums = ans;
}
};