본문 바로가기
LeetCode/2020 LeetCoding Challenge

LeetCode. Sort Colors

by 벤진[Benzene] 2020. 6. 12.

Problems:

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]

 

-Summary-

1. - Move all zeros on the left side of the list. 

   - Move all twos on the right side of the list.

 

2. Swap and replace the value in the while loop.

   - When we found 0, move to left side

   - When we found 1, keep continuing search

   - When we found 2, move to right side

이 문제는 dutch national flag algorithm (네덜란드 국기 알고리즘) 으로 아래에 자세한 내용이 있다.

https://en.wikipedia.org/wiki/Dutch_national_flag_problem#:~:text=The%20algorithm%20indexes%20three%20locations,middle%20and%20the%20top%20group.

 

Dutch national flag problem - Wikipedia

The Dutch national flag problem [1] is a computer science programming problem proposed by Edsger Dijkstra.[2] The flag of the Netherlands consists of three colors: red, white and blue. Given balls of these three colors arranged randomly in a line (it does

en.wikipedia.org

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글