Description
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]…
Example 1:
Input:
Output:
Example 2:
Input:
Output:
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[0] < nums[1] > nums[2] < nums[3]…。
- STL中的nth_element()方法的使用 通过调用nth_element(start, start+n, end) 方法可以使第n大元素处于第n位置(从0开始,其位置是下标为 n的元素),并且比这个元素小的元素都排在这个元素之前,比这个元素大的元素都排在这个元素之后,但不能保证他们是有序的。
- 是一个数组的题目,需要读者手工模拟一下计算过程。先把mid位置的值求出来,然后把小于该值的元素放在前面,大于该元素的值放在后面,然后遍历,然后前后位置通过交换得到摆动数组。这道题有些地方我也不是很懂,有兴趣的可以交流一下。
代码
参考文献
324. Wiggle Sort IISTL中的nth_element()方法的使用[LeetCode] Wiggle Sort II 摆动排序之二