Skip to content

Commit a493af2

Browse files
committed
Wiggle Sort II
1 parent a7b2831 commit a493af2

File tree

3 files changed

+39
-10
lines changed

3 files changed

+39
-10
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
5757
- [Next Permutation](src/array/next-permutation.js)
5858
- [Find Peak Element](src/array/find-peak-element.js)
5959
- [Wiggle Sort](src/array/wiggle-sort.js)
60+
- [Wiggle Sort II](src/array/wiggle-sort-ii.js)
6061
- [Valid Triangle Number](src/array/valid-triangle-number.js)
6162
- [Find Anagram Mappings](src/array/find-anagram-mappings.js)
6263
- [K Empty Slots](src/array/k-empty-slots.js)

src/array/wiggle-sort-ii.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Wiggle Sort II
3+
*
4+
* Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
5+
*
6+
* Example 1:
7+
*
8+
* Input: nums = [1, 5, 1, 1, 6, 4]
9+
* Output: One possible answer is [1, 4, 1, 5, 1, 6].
10+
*
11+
* Example 2:
12+
*
13+
* Input: nums = [1, 3, 2, 2, 3, 1]
14+
* Output: One possible answer is [2, 3, 1, 3, 1, 2].
15+
*
16+
* Note:
17+
* You may assume all input has valid answer.
18+
*
19+
* Follow Up:
20+
* Can you do it in O(n) time and/or in-place with O(1) extra space?
21+
*/
22+
23+
/**
24+
* O(nlogn) Solution
25+
*
26+
* @param {number[]} nums
27+
* @return {void} Do not return anything, modify nums in-place instead.
28+
*/
29+
var wiggleSort = function(nums) {
30+
const n = nums.length;
31+
const sorted = nums.slice().sort((a, b) => a - b);
32+
33+
for (let i = 0, j = n, k = Math.floor((n + 1) / 2); i < n; i++) {
34+
nums[i] = i % 2 === 0 ? sorted[--k] : sorted[--j];
35+
}
36+
};

src/array/wiggle-sort.js

+2-10
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,8 @@
1212
*/
1313
const wiggleSort = nums => {
1414
for (let i = 1; i < nums.length; i++) {
15-
if (i % 2 !== 0 && nums[i] < nums[i - 1]) {
16-
swap(nums, i, i - 1);
17-
} else if (i % 2 === 0 && nums[i] > nums[i - 1]) {
18-
swap(nums, i, i - 1);
15+
if ((i % 2 === 0) === nums[i] > nums[i - 1]) {
16+
[nums[i], nums[i - 1]] = [nums[i - 1], nums[i]];
1917
}
2018
}
2119
};
22-
23-
const swap = (nums, i, j) => {
24-
const tmp = nums[i];
25-
nums[i] = nums[j];
26-
nums[j] = tmp;
27-
};

0 commit comments

Comments
 (0)