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.
You are not suppose to use the library's sort function for this problem.
Analysis:
This is a relative easy problem.
The goal is to rearrange the array, where 0s are in the 1st part of the array, 1s in the middle, and 2s are in the last. So, we can just scan the whole array, when meet 0, put it in the front, when meet 2, put it in the last, and leave 1 alone thus in the middle. 0 and 2's positions are stored and modified each time a swap is performed.
Details see the code.
Code:
class Solution { public: void swap(int A[], int i, int j){ int tmp = A[i]; A[i]=A[j]; A[j]=tmp; } void sortColors(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int red=0; int blue=n-1; while (A[red]==0){red++;} while (A[blue]==2){blue--;} int i=red; while (i<=blue){ if (A[i]==0 && i>red) {swap(A,i,red);red++;continue;} if (A[i]==2) {swap(A,i,blue);blue--;continue;} i++; } } };
This comment has been removed by the author.
ReplyDeleteHey, I think the line 15 in your code above should be modified something like this,
ReplyDeleteline 15: while(red<A.length && A[red]==0) red++;
Because, if A=[0], the index will be out of the array's boundary. And the same logic also apply for line 16.