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?
AC code:
class Solution { public: void wiggleSort(vector<int>& nums) { int len = nums.size(); if (len == 0) return; int mid = len / 2; nth_element(nums.begin(), nums.begin()+mid, nums.end()); helper(nums, nums[mid]); vector<int> res(len); int largeStart = len - 1; int smallStart = (len % 2) ? mid : (mid - 1); for (int i = 0; i < len; i += 2) { res[i] = nums[smallStart--]; } for (int i = 1; i < len; i += 2) { res[i] = nums[largeStart--]; } nums = res; } private: void helper(vector<int>& nums, int val) { int i = 0; int j = 0; int n = nums.size()-1; while (j < n) { if (nums[j] < val) { swap(nums[i++], nums[j++]); } else if (nums[j] > val) { swap(nums[j], nums[n--]); } else { j++; } } } };
Runtime: 116 ms, faster than 16.67% of C++ online submissions for Wiggle Sort II.
tips:
Sort element in range
Rearranges the elements in the range [first,last)
, in such a way that the element at the nth position is the element that would be in that position in a sorted sequence.
The other elements are left without any specific order, except that none of the elements preceding nth are greater than it, and none of the elements following it are less.
The elements are compared using operator<
for the first version, and comp for the second.
Parameters
- first, last
- Random-access iterators to the initial and final positions of the sequence to be used. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
Notice that in this function, these are not consecutive parameters, but the first and the third. - nth
-
Random-access iterator pointing to the location within the range
[first,last)
that will contain the sorted element.
Notice that the value of the element pointed by nth before the call is not relevant. - comp
- Binary function that accepts two elements in the range as arguments, and returns a value convertible to
bool
. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.