LeeCode-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.

void sortColors(int* nums, int numsSize)
{
        if(numsSize==0||nums==NULL)
        return;

    if(numsSize==1)
        return;

    int red=0,white=0,blue=0;

    for(int i=0;i<numsSize;i++)
    {
        if(nums[i]==0)
            red++;

        if(nums[i]==1)
            white++;

        if(nums[i]==2)
            blue++;
    }
    for(int i=0;i<numsSize;i++)
    {
        if(i<red)
        {
            nums[i]=0;
        }
        if(i>=red&&i<(red+white))
        {
            nums[i]=1;
        }
        if(i>=(red+white)&&i<numsSize)
        {
            nums[i]=2;
        }

    }
}


發佈了307 篇原創文章 · 獲贊 65 · 訪問量 61萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章