Leetcode - 75. Sort Colors

숲사람·2022년 8월 17일
0

멘타트 훈련

목록 보기
124/237

문제

주어진 배열은 색정보(red:0, white:1, blue:2)를 가지고 있다. 배열을 red/white/blue순으로 정렬하라.

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

해결

3개의 hashtable을 만들고 빈도수를 저장한뒤, nums배열을 순차적으로 변경

void sortColors(int* nums, int numsSize){
    int freq[3] = {0};
    int curidx = 0;
    int i = 0;
    for (int i = 0; i < numsSize; i++)
        freq[nums[i]]++;
    while (i < numsSize) {
        if (freq[curidx]--)
            nums[i++] = curidx;
        else
            curidx++;
    }
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글