[LeetCode] Sort Colors

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.

click to show follow up.

 由于只有三种颜色,可以设置两个 index,一个是 red 的 index,一个是 blue 的 index,两边往中
间走。时间复杂度 O(n),空间复杂度 O(1)。

 1 // 为什么 (A[i] == 0)时是i++,red++,
 2 // 而在(A[i]==2)时仅仅是blue--???
 3 //
 4 //
 5 //
 6 //
 7 //
 8 //red指针在开始的时候可能指向0,当切仅当在i未遇到1之前
 9 //在i遇到1之后,red就指向1
10 //
11 //  0 0 1 2 1 2 1 2 2 0
12 //  初始时red和i一同增长
13 //  当i=2时,i++变成3,但red还是2
14 //
15 //
16 //
17 //
18 //  总之,由于i从前向后扫描,所以i之前只有0 和1,但i之后却可能有0 1 2,遇到0时,交换过来的肯定是1,所以可以i++
19 
20 class Solution {
21     public:
22         void sortColors(int A[], int n) {
23             int red = 0, blue = n - 1;
24             for (int i = 0; i < blue + 1;) {
25                 if (A[i] == 0)
26                 {   
27                     swap(A[i], A[red]);
28                     //此处i和指针同时++,这点是由交换过来的数据肯定是1保证的,
29                     //为什么交换过来的肯定是1呢?
30                     //如果i前面存在2,那么肯定已经被(A[i] == 2)处理过了
31                     //如果i前面存在0,那么也是在red指针之前,red指向的一定是1
32                     i++;
33                     red++;
34                 }   
35                 else if (A[i] == 2)
36                     swap(A[i], A[blue--]);
37                 else
38                     i++;
39                 cout <<endl <<endl;
40             }   
41         }
42 };

 其实上面不是很好理解

下面更好理解

class Solution {
    public:
        void sortColors(int A[], int n) {
            int red = 0, blue = n - 1;
            for (int i = 0; i < blue + 1;) {
                if (A[i] == 0)
                {   
                    if(red == i)
                    {
                        i++;
                        red++;
                    }
                    else
                    {
                        swap(A[i], A[red]);
                        red++;
                    }
                }   
                else if (A[i] == 2)
                    swap(A[i], A[blue--]);
                else
                    i++;
            }   
    }
    
};
原文地址:https://www.cnblogs.com/diegodu/p/3810595.html