알고리즘

[LeetCode] Set Colors

룰스 2019. 11. 5. 17:23

문제

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

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

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
  • Could you come up with a one-pass algorithm using only constant space?

Approach

문제를 보고 bucket sort가 생각났지만 one-pass에 constant space를 만족하며 풀어보라는 권장 사항이 있었다.

우선은 bucket sort로 풀었다. 시간복잡도 O(n) (two-pass), 공간복잡도 O(1)

 

Optimize

one-pass로 풀려면 포인터가 두개 있어야 한다 - 1이 시작되는 index (lo), 1이 끝나는 index (hi)

배열을 쭉 탐색하며 0이 나오면 lo에 있는 수와 바꿔 발견된 모든 1의 앞으로 보내고 lo를 1 증가시킨다.

2가 나오면 hi에 있는 수와 바꿔 발견된 모든 2의 앞으로 보내고 hi를 1 감소시킨다음,

배열을 탐색하는 index를 1 감소시켜 바꿔진 자리를 한번 더 탐색한다.

그러다 탐색 index가 hi보다 커지면 끝낸다.

이러면 시간복잡도 O(n)(one-pass), 공간복잡도 O(1)로 해결할 수 있다.

하지만 bucket sort와 큰 시간차이는 없었다.

 

Code

Bucket Sort https://github.com/chi3236/algorithm/blob/master/LeetCode_SortColors_bucket.cpp

 

chi3236/algorithm

Contribute to chi3236/algorithm development by creating an account on GitHub.

github.com

One-pass https://github.com/chi3236/algorithm/blob/master/LeetCode_SortColors_onepass.cpp