Topic:
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]
.
Links: http://leetcode.com/problems/wiggle-sort/
Exercises
Wiggle a sorted array. Follow the test instructions to write it. You can also simplify and learn more about Stefan's code.
Time Complexity-o (n), Space complexity-o (1)
Public classSolution { Public voidWigglesort (int[] nums) { for(inti = 1; i < nums.length; i++) { if(i% 2 = = 1) { if(Nums[i] < nums[i-1]) {swap (nums, i); } } Else { if(I! = 0 && nums[i] > Nums[i-1]) {swap (nums, i); } } } } Private voidSwapint[] Nums,inti) {intTMP = Nums[i-1]; Nums[i-1] =Nums[i]; Nums[i]=tmp; }}
Reference:
Https://leetcode.com/discuss/57113/java-o-n-solution
Https://leetcode.com/discuss/57206/java-o-n-10-lines-consice-solution
Https://leetcode.com/discuss/60824/java-python-o-n-time-o-1-space-solution-3-lines
Https://leetcode.com/discuss/57118/easy-code-of-python
280.Wiggle Sort