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]
.
Title Tags: Array, Sort
The topic gave us a nums array, let's wiggle sort.
Wiggle Sort attribute: All index is odd number greater than or equal to both sides of the number.
We can understand from another angle: All even index numbers are smaller than the next number, and all odd index numbers are greater than or equal to the next number.
This allows you to traverse the nums, checking each pair of numbers according to the odd even number, and swap them if they do not meet the requirements.
Java Solution:
Runtime beats 60.02%
Completion Date: 09/10/2017
Keywords: Array
Key points: Traverse check each pair of numbers, do not meet the requirements of the swap
1 classSolution2 {3 Public voidWigglesort (int[] nums)4 {5 for(inti=0; i<nums.length; i++)6 {7 //For even index8 if(i% 2 = = 0)9 { Ten //if even index number > next one, swap them One if(I+1 < nums.length && Nums[i] > nums[i+1]) A { - inttemp =Nums[i]; -Nums[i] = nums[i+1]; theNUMS[I+1] =temp; - } - } - Else //For Odd index + { - //if odd index number < next one, swap them + if(I+1 < nums.length && Nums[i] < nums[i+1]) A { at inttemp =Nums[i]; -Nums[i] = nums[i+1]; -NUMS[I+1] =temp; - } - } - } in } -}
Reference: N/A
Leetcode algorithm topic List- leetcode algorithms Questions list
Leetcode 280. Wiggle sort (oscillating sort) $