leetCode(30):Sort Colors

來源:互聯網
上載者:User

標籤:

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.




void sortColors(vector<int>& nums){//排序時間複雜度O(n)int length=nums.size();int zero=0;int two=length-1;while(zero<length && nums[zero]==0){//找到第一個不為0的數的下標zero++;}while(two>=zero && nums[two]==2){//找到倒數第一個不為2的數的下標,zero前的數都是0two--;}    for(int i=zero;i<=two;++i)    {    if(nums[i]==0)    {//如果為0,和zero指向的數交換,zero前移    nums[i]=1;//zero指向的值肯定是1,首先不可能為0,其次,i遍曆過的地方,2都已經換到最後    nums[zero]=0;    zero++;    }    else if(nums[i]==1)    {//如果為1,則跳過    continue;    }    else    {//如果為2,則和two指向的數交換,並更新two的值,    //和zero不同,two前面的數可能還未排序    nums[i]=nums[two];    nums[two]=2;    two--;    while(two>=i && nums[two]==2)    {    two--;    }    i--;//先向後退一步,因為two指向的數還未進行排序    }    }}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

leetCode(30):Sort Colors

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.