-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path075.js
More file actions
34 lines (30 loc) · 891 Bytes
/
075.js
File metadata and controls
34 lines (30 loc) · 891 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var sortColors = function(nums) {
const RED = 0;
const WHITE = 1;
const BLUE = 2;
let redIndex = 0;
while(nums[redIndex] === RED) { ++redIndex; }
let currentIndex = redIndex;
let blueIndex = nums.length - 1;
while(nums[blueIndex] === BLUE) { --blueIndex; }
while(currentIndex <= blueIndex && redIndex < blueIndex) {
if (currentIndex < redIndex) {
++currentIndex;
}
if (nums[currentIndex] === WHITE) {
++currentIndex;
} else if (nums[currentIndex] === RED) {
nums[currentIndex] = nums[redIndex];
nums[redIndex++] = RED;
} else {
nums[currentIndex] = nums[blueIndex];
nums[blueIndex--] = BLUE;
}
while(nums[redIndex] === RED) { ++redIndex; }
while(nums[blueIndex] === BLUE) { --blueIndex; }
}
};