qingcheng奕  

https://oj.leetcode.com/problems/sort-colors/

0,1,2对这三个数组成的序列,扫描一遍的排序。

class Solution {
public:
    void sortColors(int A[], int n) {
        int x = -1, y = -1, z = -1; // x means the last 0's position
        
        for(int i = 0; i < n; i++)
        {
            if(A[i] == 2)
            {
               z = i;
            }
            else if(A[i] == 1)
            {
                if(i == 0) // the first element
                {
                    y = 0;
                    continue;
                }
                if(A[i-1] == 2)
                {
                    if(y < x) //if y is -1
                    y = x;
                    y++;
                    A[y] = 1;
                    A[i] = 2;
                    z = i;
                }
                else 
                    y = i;
            }
            else
            {
                if(i ==0)
                {
                    x = 0;
                    continue;
                }
                if(A[i -1] == 1)
                {
                    x++;
                    A[x] = 0;
                    A[i] = 1;
                    y = i;
                }
                else if(A[i -1] == 2)
                {
                    A[i] = 2;
                    z = i;
                    x++;
                    if(A[x] == 2)
                    A[x] = 0;
                    else if(A[x] ==1)
                    {
                        y++;
                        A[y] = 1;
                        A[x] = 0;
                    }
                }
                else
                   x = i;
                
            }
        }
        return;
    }
};

 

posted on 2014-06-15 18:29  qingcheng奕  阅读(107)  评论(0编辑  收藏  举报