Sort Color

来源:互联网 发布:有毒网络剧歌曲 编辑:程序博客网 时间:2024/05/28 15:06

Given an array with n objects colored red, white or blue, sort them 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.

click to show follow up.

Subscribe to see which companies asked this question


2遍扫描:
统计red,white,blue的数量,然后第二次扫描覆盖。
1遍扫描:
两个指针分别指着white, red,再取一个指针遍历数组,如果是white,就和指向white的指针交换,同时向前移动,如果是red,就和指向red的指针交换。
O(n)的时间复杂度。

0 0
原创粉丝点击