题目描述:
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
Wiggle排序II,给定数组,进行排序后,要求生成的序列An满足:A1<A2>A3<A4...>An-1<An,可假设有解。
思路:对数组排序,使用两个索引,一个从中间开始:i,一个从最后:j,向前依次遍历即可。
实现代码:
public class Solution {
public void WiggleSort(int[] nums) {
if(nums == null){
return;
}
var len = nums.Length;
if(len == 1){
return ;
}
var arr = new int[len];
for(var i = 0;i < len; i++){
arr[i] = nums[i];
}
Array.Sort(arr);
var index = 0;
var mid = len % 2 == 0 ? len/2 - 1 : len/2;
var m = mid;
var end = len-1;
while(mid >= 0 || end > m){
if(mid >= 0){
nums[index] = arr[mid];
index++;
mid--;
}
if(end > m){
nums[index] = arr[end];
end--;
index++;
}
}
}
}