280. Wiggle Sort/324. Wiggle Sort II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了280. Wiggle Sort/324. Wiggle Sort II相关的知识,希望对你有一定的参考价值。
?????????color condition ?????? == ?????? private sort one ssi
280 Given an unsorted array nums
, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
.
Example:
Input:nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]
280????????????????????????????????????????????????
????????????
1. ???????????????????????? a0<=a1<=a2<=a3<=a4....<ai<=ai+1
2. ?????????a1 ??????????????????????????? ???????????????a0<=a2>=a1<=a4>=a3<=an
class Solution { public void wiggleSort(int[] nums) { Arrays.sort(nums); for(int i=1; i<nums.length-1; i+=2){ swap(nums, i,i+1); } } private void swap(int[] nums, int i, int j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
???????????? ?????????????????? nlogn????????? ??????????????????On ????????????
??????O(n) ??????????????????????????????????????????????????????
1. ???even index ????????????index = 0, ?????? nums[i] > nums[i+1], ?????????
2. ???odd index ?????? ??????index=1, ?????? nums[i] <nums[i+1] ????????????
????????????????????????????????????????????????????????? Mathematical Induction??? ???????????????
??????????????? ?????????????????????????????????????????????????????????
a0<=a1>=a2<=a3>=a4<=....ak...
??????n = k+1 ????????????
if n = k+1 is even( ??????????????????????????????)??? ?????? ak>=a(k+1) ???
?????? a(k+1) > a???k+2?????? ??????????????? ?????? ak >= a(k+2) <=a(k+1), ????????????????????????
??????a(k+a) <a(k+2) ?????????????????? ??????????????????ak<=a(k+1)<=a(k+2) , the order is also correct.
????????? if n =k+1 is odd ????????????????????????????????????
class Solution { public void wiggleSort(int[] nums) { for(int i=0; i<nums.length-1; i++){ if(i%2 ==0 && nums[i] > nums[i+1] || i%2==1 && nums[i] <nums[i+1]) { //the condition need to swap swap(nums,i,i+1); } } } private void swap(int[] nums, int i, int j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
??????324 ???????????????????????????????????????????????????????????????
Given an unsorted array nums
, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]...
.
??????????????????????????????????????????????????????????????????????????????????????????????????????
以上是关于280. Wiggle Sort/324. Wiggle Sort II的主要内容,如果未能解决你的问题,请参考以下文章