[leetcode] Sort Colors

来源:互联网 发布:网络英语哪家好 编辑:程序博客网 时间:2024/05/21 10:21

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.

题目给出的要求是one-pass algorithm. 

public class Solution {      public void sortColors(int[] A) {       int i = -1, j = -1;        for (int p = 0; p < A.length ; p++) {        int v = A[p];         A[p] = 2;         if(v == 0){          A[++i] = 1;           A[++j] = 0;         }        else if(v == 1){          A[++i] = 1;         }                }    }    }

i, j, p are used as counter in the code. 

i: the number of 0, and write zero to them. 

j: the number of 0 & 1, and write one to them. 

p: the number of 0 & 1 & 2, and write two to them. Besides, it's also the iterator pointer. 

every time, the number will be over ride to 2 at first, if it's a zero, will be over ride to 1 then, but the final result is still 0 at last. 

0 0