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.
思路:就是找到中位数,然后将大的放在数组前半部分,小的放在数组后半部分(这个做是为防止1 2 5 5 6 这样放的话 最后是 1 5 2 5 5 6这种情况的发生)
代码如下(已通过leetcode)
public class Solution {
public void wiggleSort(int[] nums) {
if(nums==null||nums.length==0||nums.length==1) return;
Arrays.sort(nums);
int i=(nums.length-1)/2,j=nums.length-1;
int[] res=new int[nums.length];
int k=0;
while(i>=0&&j>=(nums.length-1)/2+1) {
res[k]=nums[i];
i--;
k++;
res[k]=nums[j];
j--;
k++;
}
if(k==nums.length-1) res[k]=nums[0];
for(int p=0;p<nums.length;p++)
nums[p]=res[p];
}
}