Given an unsorted array nums
, reorder it in-place such nums[0] <= nums[1] >= nums[2] <= nums[3]...
.
For example, given nums = [3, 5, 2, 1, 6, 4]
, one possible answer are [1, 6, 2, 5, 3, 4]
.
Solution:
Loop through, when odd index num should is greater then the previous num;
When even index num should is smaller then the previous num;
So if even index NUM was greater then the previous NUM then it must was greater then the previous of previous Num too Ly swap once.
1 Public classSolution {2 Public voidWigglesort (int[] nums) {3 intL =Nums. Length;4 for(intI=1; i<l;i++)5 {6 if(i%2==1)7 {8 if(nums[i]<nums[i-1])9 {Ten Swap (Nums, i); One } A } - Else - { the if(nums[i]>nums[i-1]) - { - Swap (Nums, i); - } + } - } + } A Public voidSwap (int[] Nums,inti) at { - inttemp = nums[i-1]; -nums[i-1]=Nums[i]; -Nums[i] =temp; - } -}
Leetcode 280. Wiggle Sort C #