码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Sort Colors"

时间:2014-07-22 22:42:54      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   

For the one pass solution... first I tried to build white\blue from red, but not working anyway. Then I referred someone‘ code, to build red\blue from white. Working now. The pointers‘ behavior deserves more thinking:

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) {
        if (n == 0 || n == 1) return;
        if (n == 2)
        {
            if (A[0] > A[1]) swap(A, 0, 1);
            return;
        }
        int i0 = 0;
        int i1 = 0;
        int i2 = n - 1;
        while (i1<=i2)
        {
            if (A[i1] == 0)
            {
                swap(A, i0++, i1++); 
         // Reason i1 also inc here: all 2s have been swapped back,
         // so all left are 0\1s - in any case, we don‘t need consider twice. so move on
continue; } else if (A[i1] == 2) { swap(A, i1, i2--); continue; } i1 ++; } } };

LeetCode "Sort Colors",布布扣,bubuko.com

LeetCode "Sort Colors"

标签:des   style   blog   color   io   for   

原文地址:http://www.cnblogs.com/tonix/p/3860160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!