1
2
6var sortColors = function(nums) {
7 let red = 0, white = 0, blue = 0;
8 nums.forEach(el => {
9 if(el === 0) {
10 red++
11 } else if(el === 1) {
12 white++
13 } else {
14 blue++
15 }
16 });
17
18 for (let i = 0, l = nums.length; i < l; i++) {
19 if(i < red) {
20 nums[i] = 0;
21 } else if (i < red + white) {
22 nums[i] = 1;
23 } else {
24 nums[i] = 2;
25 }
26 }
27
28 return nums;
29};
30
31
32let sortColors1 = function(nums) {
33 for (let i = 0, j = 0, k = nums.length - 1; i <= k; i++) {
34 if (nums[i] === 0) {
35 [nums[i], nums[j++]] = [nums[j], nums[i]];
36 } else if (nums[i] === 2) {
37 [nums[k--], nums[i--]] = [nums[i], nums[k]];
38 }
39 }
40};
41
42
43var sortColors2 = function(nums) {
44 for(var i=0, l = nums.length; i < l; i++) {
45 if(nums[i] === 0) {
46 nums.splice(i,1);
47 nums.unshift(0);
48 } else if(nums[i] === 2) {
49 nums.splice(i,1);
50 nums.push(2);
51 l--;
52 i--;
53 }
54 }
55
56 return nums;
57};
58
59ensureEqual(sortColors([2,0,2,1,1,0]), [0,0,1,1,2,2], 'test 1');