[LeetCode] Sort Colors

來源:互聯網
上載者:User

標籤: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++;            }       }    };

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.