hwooo
LeetCode (C/C++) 75. Sort Colors 본문

풀이
공간복잡도가 상수이어야 하고, 색은 {0,1,2} 3개로 나타내는 방식이라, 3칸짜리 배열에 색의 정보를 저장했다.
배열에 저장된 수에 따라 nums 순서대로 값을 넣어주었다.
코드
class Solution {
public:
void sortColors(vector<int>& nums) {
// save colors
int colors[3] = {0, };
for (int n : nums)
colors[n]++;
// change sequence
int idx = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < colors[i]; j++)
nums[idx++] = i;
}
}
};
'Study > Algorithm' 카테고리의 다른 글
| LeetCode (C/C++) 581. Shortest Unsorted Continuous Subarray (0) | 2024.11.07 |
|---|---|
| 프로그래머스 (C/C++) 118667 : 두 큐 합 같게 만들기 (0) | 2024.11.06 |
| 프로그래머스 (C/C++) 43163 : 단어 변환 (0) | 2024.11.04 |
| LeetCode (C/C++) 152. Maximum Product Subarray (0) | 2024.11.01 |
| 프로그래머스 (C/C++) 135807 : 숫자 카드 나누기 (2) (0) | 2024.10.31 |