[Leetcode] Sort Colors

Source: Internet
Author: User

Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue.

Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You is not a suppose to use the library's sort function for this problem.

In short, the problem is given a sequence of three numbers containing 0,1,2, requiring that the sequence be re-integrated, the same elements placed in the adjacent position, the overall order is still 0,1,2. Requires that the sorting algorithm in the library function cannot be used.

The idea is very simple, do not rigidly adhere to the idea of sorting, first go through the array, statistics 0,1,2 three number of each occurrence of the frequency, and then rewrite the array.

void sortcolors (int A[], int n){int count[3] = { 0, 0, 0 }; IntI=0; for(I=0;I< n;I++){count[a[i]]++; }IntJ=0; for(I=0;I< count[0];I++){a[j++] = 0; }         for(I=0;I< count[1];I++){a[j++] = 1; }         for(I=0;I< count[2];I++){a[j++] = 2; }}

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