Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], 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?Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
解题的基本思想参考:
3 lines Python, with Explanation / Proof
即:首先逆序排列数组,寻找中位数,然后按照大于、等于、小于中位数把所有的数分为三类L,M,S。按照数组长度,将所有数分为两个数组,按照此分类进行填充。有如下两种情况。
Small half: M . M . S . S Small half: M . S . S . S .
Large half: . L . L . M . Large half: . L . M . M . M
-------------------------- --------------------------
Together: M L M L S M S Together: M L S M S M S M
即中位数若在S数组中,则必为最大值,若在L数组中必为最小值,所以按照如上拍法可以保证不会将中位数排到一起从而达不到要求。可以看出,偶数下标位皆为小数(M、S),奇数下标位皆为大数(L、M)。所以先从右到左排列S到偶数位,从左到右排列L到奇数位,剩下的位置插入M。
具体算法有两种,第一种采用赋值的方法,通过建立辅助数组拷贝原数组,并按照上述方式进行对原数组的赋值从而达到要求。时间复杂度为O(n),空间复杂度为O(n);第二种方法采用原地交换的方式进行,时间复杂度为O(n),空间复杂度为O(1)。
第一种方法代码如下:
class Solution {
int N;
public void wiggleSort(int[] nums) {
N = nums.length;
int[] temp = new int[N];
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++)
temp[i] = nums[N-1-i]; //temp的顺序为降序
for(int i = 0; i < N; i++){
nums[indexTo(i)] = temp[i];
}
}
public int indexTo(int x){
return (1+2*x)%(N|1);
}
}
第二种方法思路如下:
建立一个下标映射方法,使得对原始下标(如:0,1,2,3,4,5,6)映射得新下标(如:1,3,5,0,2,4,6),如此便可按照新下标进行操作,这就达到了顺序交换的目的。具体的映射函数为(1 + 2*index) % (n | 1)
(注意在这里的“|”位运算符作用是保证n始终是奇数,即对n的二进制的最低位取位或操作)
然后建立三个“指针”Left,Right,i。Left用于从左到右排列L,Right用于从右到左排列S,i用于按映射顺序进行下标移动。具体算法可以参考:Step by step explanation of index mapping in Java(要注意的是,里面的left和i都是从0到N-1的,right是从N-1到0的。而在使用时候,会进行映射操作以保证按照1,3,5,0,2,4,6···的顺序进行。)