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从中间开始,按照次序更新值。
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var wiggleSort = function(nums) { var sorted = nums.slice(0).sort(sorting); var i = 0, p = 0, q = parseInt((sorted.length - 1) / 2 + 1); for(; i < sorted.length; i++){ if(i % 2 === 0) nums[i] = sorted[p++]; else nums[i] = sorted[q++]; } return; function sorting(a, b){ return a - b; } };
以上就是[LeetCode][JavaScript]Wiggle Sort II的详细内容,更多关于[LeetCode][JavaScript]Wiggle Sort II的资料请关注九品源码其它相关文章!