[leetcode刷题系列]Sort Colors

来源:互联网 发布:网络直播的起源与发展 编辑:程序博客网 时间:2024/06/13 23:14

题目虽然简单, 但是确实找了好一会的bug,对着数据- -

这题值得再写一遍。


class Solution {public:    void sortColors(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(n <= 0)            return ;        int p0 = -1;        while(p0 + 1 < n)            if(A[p0 + 1] == 0)                ++ p0;            else                break;        if(p0 == n - 1)            return ;        int p2 = n;        while(p2 - 1 >= 0)            if(A[p2 - 1] == 2)                -- p2;            else                break;        if(p0 + 1 == p2)            return ;        int p1 = p0 + 1;        while(p1 < p2){            if(A[p1] == 2){                swap(A[p1], A[p2 - 1]);                -- p2;                while(p2 - 1 >= 0)                    if(A[p2 - 1] == 2)                        -- p2;                    else                        break;            }            if(A[p1] == 0){                swap(A[p1], A[p0 + 1]);                ++ p0;                ++ p1;            }else ++ p1;        }    }};


原创粉丝点击