Notice
Recent Posts
Recent Comments
Link
«   2026/01   »
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
Archives
Today
Total
관리 메뉴

hwooo

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

Study/Algorithm

LeetCode (C/C++) 75. Sort Colors

hwooo 2024. 11. 5. 11:59


풀이

공간복잡도가 상수이어야 하고, 색은 {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;
        }
    }
};