[LeetCode] Sort Colors

来源:互联网 发布:上古世纪人物捏脸数据 编辑:程序博客网 时间:2024/06/15 02:16
[Problem]

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 thecolor red, white, and blue respectively.

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

Follow up:
A rather straight forward solution is a two-pass algorithm usingcounting sort.
First, iterate the array counting number of 0's, 1's, and 2's, thenoverwrite array with total number of 0's, then 1's and followed by2's.

Could you come up with an one-pass algorithm using only constantspace?

[Solution]

class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0, red = 0, blue = n-1;

// one pass
while(i <= blue){
// fill 0s
if(A[i] == 0){
swap(A[red++], A[i++]);// 从A[red]交换过来的只可能是0或1,如果是0,则必然red==i
}
// count 1s
else if(A[i] == 1){
i++;
}
// fill 2s
else if(A[i] == 2){
swap(A[i], A[blue--]);
}
}
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击