Leetcode之Sort Colors 问题

来源:互联网 发布:大数据可视化 网络攻击 编辑:程序博客网 时间:2024/05/19 13:19

问题描述:

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with thecolors 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.

问题来源:Sort Colors (详细地址:https://leetcode.com/problems/sort-colors/description/)

思路分析:翻译一下题目的意思就是整个数组排好序应该是0,1,2这种,0总在1前面,1总在2前面,2必须位于最后。所以,我们就动用两个指针,zero用来标记0的个数,second用来标记2的个数,其中zero从左往右遍历,second从右往左遍历,i遍历的时候遇到0就和zero交换,遇到2的话就和second交换。在这也有个小的细节,就是啥时候i++,把0交换掉的时候肯定是要i++的,往前移动一格继续存放下一个0;遇到1的时候,我们是不做任何处理的,这时候i也是要往后继续遍历的;遇到2的时候呢?这时候是不着急遍历下一个元素的,因为很有可能2和0交换之后,0跑到1后面了,i必须停在这里,继续把0交换到前面去,具体的例子在代码中已经给出了。

代码: