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