Sort Colors
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:
1 | Input: [2,0,2,1,1,0] |
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?
思路:拿到题目以后第一感受:这不就是个排序吗?话不多说,正好练练前一段时间写过的插入排序,因为都是0,1,2的序列,基本有序,所以用插入排序效率应该比较高,果不其然,leetcode上击败了70%多的人。
代码如下:
1 | class Solution { |