324. Wiggle Sort II

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?

含义:给定一个没有排序的数组,重排以后达到 nums[0] < nums[1] > nums[2] < nums[3]....这种效果

 1     public void wiggleSort(int[] nums) {
 2         //        先给数组排序,然后找到数组的中间的数,相当于把有序数组从中间分成两部分,然后从前半段的末尾取一个,在从后半的末尾去一个,以此类推直至都取完
 3         int[] temp = (int[])nums.clone();
 4         Arrays.sort(temp);
 5         int n = nums.length,k=(1+n)/2,j=n;
 6         boolean flag = true;
 7         for (int i=0;i<n;i++)
 8         {
 9             nums[i] = flag?temp[--k]:temp[--j];
10             flag = !flag;
11         }        
12     }

 

posted @ 2017-10-25 19:43  daniel456  阅读(119)  评论(0编辑  收藏  举报