Discussion에서 아래의 방법으로 푼 분이 올린 그림이다.
// Discussion
// 나중에 다시 풀어봐야할 문제
function sortColors(nums) {
let low = 0;
let high = nums.length - 1;
for (let i = 0; i <= high; i++) {
if (nums[i] === 0) {
[nums[i], nums[low]] = [nums[low], nums[i]]; // swap
low++;
} else if (nums[i] == 2) {
[nums[i], nums[high]] = [nums[high], nums[i]];
high--;
i--;
}
}
}
// 비슷한 풀이
var sortColors = function(arr) {
let low=0, mid=0, high=arr.length-1
while ( mid <= high ) {
if( arr[mid] == 0 ){
swap( low, mid );
mid++;
low++ ;
}
else if( arr[mid] == 1 ) {
mid++ ;
}
else if( arr[mid] == 2 ) {
swap( mid,high );
high--
}
}
function swap(a,b) {
[arr[b], arr[a]] = [arr[a], arr[b]]
}
};
https://leetcode.com/problems/sort-colors/
https://github.com/tTab1204/LeetCode/tree/main/%EC%A3%BC%EC%98%81