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

LeetCode-Wiggle Sort

时间:2016-08-07 15:16:24      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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].

Analysis:

We just need to substitute each two consecutive numbers to make the arrya wiggle.

Solution:

 1 public class Solution {
 2     public void wiggleSort(int[] nums) {
 3         boolean isDec = false;
 4         for (int i=0;i<nums.length-1;i++){
 5             if ((isDec && nums[i]<nums[i+1]) || (!isDec && nums[i]>nums[i+1])){
 6                 int temp = nums[i+1];
 7                 nums[i+1] = nums[i];
 8                 nums[i] = temp;
 9             }
10             isDec = !isDec;
11         }
12         
13     }
14 }

 

LeetCode-Wiggle Sort

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5746019.html

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