매일프로그래밍 - 코딩테스트 30/06/2019

MP·2019년 12월 15일
0

문제

0, 1, 2로 이루어진 배열을 가장 효율적으로 정렬 하시오. 시간복잡도 O(n).
Given an array consisting of 0, 1 and 2s, sort this array.

Input

[0, 1, 2, 2, 0, 0, 0, 1]

Output

[0, 0, 0, 0, 1, 1, 2, 2]

void sort012(int in[], int out[], int n) {
  int i, j, n[3] = {0, };
  for (i = 0; i < n; i++) {
    n[in[i]]++;
  }
  for (i = 0 ; i < 3; i++) {
    for (j = 0; j < n[i]; j++) {
      out[j] = i;
    }
  }
}

0개의 댓글