leetcode [324]Wiggle Sort II
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?
题目大意:
将数组变成为nums[0] < nums[1] > nums[2] < nums[3]....这种形式。
解法:
将数组排好顺序,从左到右偶数位填充比中位数大的数字,从右到左奇数位填充比中位数小的数字,剩下的全填充中位数。
java:
class Solution { public void wiggleSort(int[] nums) { if (nums.length<=1) return; Arrays.sort(nums); int len=nums.length,mid=nums[len/2],low=1,high=(len%2==1?len-1:len-2); int[] ans=new int[len]; Arrays.fill(ans,mid); for (int i=len-1;i>=0&&nums[i]>mid;i--,low+=2){ ans[low]=nums[i]; } for (int i=0;i<len&&nums[i]<mid;i++,high-=2){ ans[high]=nums[i]; } for(int i=0;i<len;i++) nums[i]=ans[i]; } }