leetcode [324]Wiggle Sort II

Posted xiaobaituyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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];
    }
}

以上是关于leetcode [324]Wiggle Sort II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 324 Wiggle Sort 2

280. Wiggle Sort/324. Wiggle Sort II

java 324. Wiggle Sort II(#)。java

java 324. Wiggle Sort II(#)。java

java 324. Wiggle Sort II(#)。java

java 324. Wiggle Sort II(#)。java