Given an unsorted array nums
, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]...
.html
Example 1:數組
Input: Output: One possible answer is .nums = [1, 5, 1, 1, 6, 4][1, 4, 1, 5, 1, 6]
Example 2:app
Input: Output: One possible answer is .nums = [1, 3, 2, 2, 3, 1][2, 3, 1, 3, 1, 2]
Note:
You may assume all input has valid answer.post
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?url
這道題給了咱們一個無序數組,讓咱們排序成擺動數組,知足nums[0] < nums[1] > nums[2] < nums[3]...,並給了咱們例子。咱們能夠先給數組排序,而後在作調整。調整的方法是找到數組的中間的數,至關於把有序數組從中間分紅兩部分,而後從前半段的末尾取一個,在從後半的末尾去一個,這樣保證了第一個數小於第二個數,而後從前半段取倒數第二個,從後半段取倒數第二個,這保證了第二個數大於第三個數,且第三個數小於第四個數,以此類推直至都取完,參見代碼以下:spa
解法一:code
// O(n) space class Solution { public: void wiggleSort(vector<int>& nums) { vector<int> tmp = nums; int n = nums.size(), k = (n + 1) / 2, j = n; sort(tmp.begin(), tmp.end()); for (int i = 0; i < n; ++i) { nums[i] = i & 1 ? tmp[--j] : tmp[--k]; } } };
這道題的Follow up讓咱們用O(n)的時間複雜度和O(1)的空間複雜度,這個真的比較難,參見網友的解答,(未完待續。。)htm
解法二:blog
// O(1) space class Solution { public: void wiggleSort(vector<int>& nums) { #define A(i) nums[(1 + 2 * i) % (n | 1)] int n = nums.size(), i = 0, j = 0, k = n - 1; auto midptr = nums.begin() + n / 2; nth_element(nums.begin(), midptr, nums.end()); int mid = *midptr; while (j <= k) { if (A(j) > mid) swap(A(i++), A(j++)); else if (A(j) < mid) swap(A(j), A(k--)); else ++j; } } };
相似題目:排序
Kth Largest Element in an Array
參考資料:
https://leetcode.com/problemset/algorithms/
https://leetcode.com/problems/wiggle-sort-ii/discuss/77706/Short-simple-C%2B%2B
https://leetcode.com/problems/wiggle-sort-ii/discuss/77677/O(n)%2BO(1)-after-median-Virtual-Indexing