leetcode 324. Wiggle Sort II 摇摆排序

来源:互联网 发布:绘制图片的软件 编辑:程序博客网 时间:2024/04/30 04:36

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?

这道题我直接的做法是先排序,然后依次安排。

代码如下:

import java.util.Arrays;public class Solution {    public void wiggleSort(int[] nums)     {        if(nums==null || nums.length<=1)            return;        int[] tmp=new int[nums.length];        for(int i=0;i<nums.length;i++)            tmp[i]=nums[i];        Arrays.sort(tmp);        int i=(nums.length+1)/2,j=nums.length;        for(int k=0;k<nums.length;k++)        {            nums[k]=(k&1)>0? tmp[--j]:tmp[--i];        }    }}
原创粉丝点击