码迷,mamicode.com
首页 > 其他好文 > 详细

280. Wiggle Sort

时间:2017-02-02 10:50:02      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:length   public   偶数   one   else   int   区别   sorted   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].

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

public class Solution {

    public void wiggleSort(int[] nums) {

        for(int i=0;i<nums.length-1;i++){

            if(i%2==0){

                if(nums[i]>nums[i+1]) swap(nums,i,i+1);

            }else{

                if(nums[i]<nums[i+1]) swap(nums,i,i+1);

            }

        }

    }

    public void swap(int[] nums,int i,int j){

        int temp = nums[i];

        nums[i] = nums[j];

        nums[j] = temp;

    }

}

280. Wiggle Sort

标签:length   public   偶数   one   else   int   区别   sorted   sort   

原文地址:http://www.cnblogs.com/codeskiller/p/6360840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!