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 if (nums == null || nums.Length < 2) return; 4 5 for (int i = 1; i < nums.Length; i++) 6 { 7 if (i % 2 == 1 && nums[i - 1] > nums[i]) 8 { 9 var tmp = nums[i - 1]; 10 nums[i - 1] = nums[i]; 11 nums[i] = tmp; 12 } 13 14 if (i % 2 == 0 && nums[i] > nums[i - 1]) 15 { 16 var tmp = nums[i - 1]; 17 nums[i - 1] = nums[i]; 18 nums[i] = tmp; 19 } 20 } 21 } 22 }