forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0075-sort-colors.js
51 lines (40 loc) · 947 Bytes
/
0075-sort-colors.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// problem link https://leetcode.com/problems/sort-colors
// brute force approche O(n^2);
var sortColors = function(nums) {
for(let i = 0; i < nums.length; i++) {
for(let j = i +1; j < nums.length; j++) {
if(nums[j] < nums[i]) {
swap(nums, j, i);
}
}
}
return nums;
};
function swap(nums, j, i) {
const temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
// optimized approche O(n);
function sortColors(nums) {
let i = 0;
let l = 0;
let r = nums.length - 1;
while(i <= r) {
const num = nums[i];
if(num === 0) {
swap(nums,i,l);
i++;
l++;
} else if(num === 2) {
swap(nums,i,r);
r--;
} else {
i++;
}
}
return nums;
}
function swap(nums,i,j) {
[nums[i], nums[j]] = [nums[j],nums[i]];
}