[LeetCode][JavaScript]Wiggle Sort II

Wiggle Sort II

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].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

https://leetcode.com/problems/wiggle-sort-ii/


先是O(logn)的解法。

排序,双指针,p从头开始,q从中间开始,按照次序更新值。

 1 /**
 2  * @param {number[]} nums
 3  * @return {void} Do not return anything, modify nums in-place instead.
 4  */
 5 var wiggleSort = function(nums) {
 6     var sorted = nums.slice(0).sort(sorting);
 7     var i = 0, p = 0, q = parseInt((sorted.length - 1) / 2 + 1);
 8     for(; i < sorted.length; i++){
 9         if(i % 2 === 0) nums[i] = sorted[p++];
10         else nums[i] = sorted[q++];
11     }
12     return;
13 
14     function sorting(a, b){
15         return a - b;
16     }
17 };
原文地址:https://www.cnblogs.com/Liok3187/p/5091648.html