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?
解题思路:
我们可以将首先把nums排序,然后从中间和尾部分别往前向新数组添加数字
注意的是:
当nums有奇数个数字时,选取的中点为 n/2
当nums有偶数个数字时,选取的终点为n/2 - 1
此时时间复杂度为O(nlogn) 因为用了排序方法
空间复杂度为O(n)
代码:
class Solution { public: void wiggleSort(vector<int>& nums) { vector<int> temp(nums.begin(), nums.end()); sort(temp.begin(), temp.end()); int n = nums.size(); int m = n&1 ? n/2 : n/ 2 - 1 ; int j = n - 1; for(int i = 0; i < n; i++){ nums[i] = (i & 1) ? temp[j--] : temp[m--]; } } };
Time O(n) & Space O(1)解法: