280. Wiggle Sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

此题需要把数组序号分成偶数和奇数来区别对待,代码如下:

 1 public class Solution {
 2     public void wiggleSort(int[] nums) {
 3         for(int i=0;i<nums.length;i++){
 4             // the index is even
 5             if(i%2==0){
 6                 if(i+1<nums.length&&nums[i]>nums[i+1]){
 7                     swap(nums,i,i+1);
 8                 }
 9             }else{
10             // the index is odd
11                 if(i+1<nums.length&&nums[i]<nums[i+1]){
12                     swap(nums,i,i+1);
13                 }
14             }
15         }
16     }
17     public void swap(int[] nums,int i,int j){
18         int temp = nums[i];
19         nums[i] = nums[j];
20         nums[j] = temp;
21     }
22 }
23 // run time complexity is O(n),the space complexity is O(1);

 

posted @ 2017-02-02 03:07  CodesKiller  阅读(140)  评论(0编辑  收藏  举报