標籤:style class blog code http color
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就指向110 //11 // 0 0 1 2 1 2 1 2 2 012 // 初始時red和i一同增長13 // 當i=2時,i++變成3,但red還是214 //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指向的一定是132 i++;33 red++;34 } 35 else if (A[i] == 2)36 swap(A[i], A[blue--]);37 else38 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++; } } };