Leetcode: Sort colors

Source: Internet
Author: User

Description:

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.


Idea: use counting sort. First, traverse the array and calculate the numbers N0, N1, and N2 respectively. Then, the N0 0, N1 1, and N2 2 are respectively written to the original array.


Code:

void Solution::sortColors(int A[], int n){    int zero = 0;    int one = 0;    int two = 0;    int i;    for(i = 0;i < n;i++)    {        if(A[i] == 0)            zero++;        else if(A[i] == 1)            one++;        else if(A[i] == 2)            two++;    }    i = 0;    while(zero > 0)    {        A[i] = 0;        i++;        zero--;    }    while(one > 0)    {        A[i] = 1;        i++;        one--;    }    while(two > 0)    {        A[i] = 2;        i++;        two--;    }}


Leetcode: Sort colors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.