[Leetcode] Sort colors

Source: Internet
Author: User

Description:

Given an arrayNObjects 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.

Solution:

STL sort is not allowed in this question. In fact, it is not required because the array in this question is composed of only numbers 0, 1 and 2. Therefore, an array B of the same size can be created, initialize all elements to 1 and traverse array A. If a [I] = 0, put it in front of array B. If a [I] = 1, put it at the end of array B. Below is the code for this question:

 1 class Solution { 2 public: 3     void sortColors(int A[], int n) { 4         int *B = new int[n]; 5         for (int i = 0; i < n; ++i) {B[i] = 1;} 6         int start = 0; 7         int lback = n - 1; 8         for (int i = 0; i < n; ++i) { 9             if (A[i] == 0) {10                 B[start++] = 0;11             }12             if (A[i] == 2) {13                 B[lback--] = 2;14             }15         }16         for (int i = 0; i < n; ++i) {17             A[i] = B[i];18         }19         delete [] B;20     }21 };

 

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