Leetcode: Sort colors

Source: Internet
Author: User

Leetcode: Sort colors

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.

Address: https://oj.leetcode.com/problems/sort-colors/

Algorithm: the question must be traversed once. Since there are three elements in total, we can set two variables pos_red and pos_blue to indicate that the red elements are stored between 0 and the pos_red-1, respectively, pos_blue + 1 to n-1 stores blue elements. Code:

 1 class Solution { 2 public: 3     void sortColors(int A[], int n) { 4         if(n <= 1 || !A) return; 5         int pos_red = 0; 6         int pos_blue = n-1; 7         for(int i = 0; i <= pos_blue; ){ 8             if(A[i] == 0){ 9                 swap(A[i],A[pos_red]);10                 ++pos_red;11                 ++i;12             }else if(A[i] == 2){13                 swap(A[i],A[pos_blue]);14                 --pos_blue;15             }else{16                 ++i;17             }18         }19     }20     void swap(int &a, int &b){21         int temp = a;22         a = b;23         b = temp;24     }25 };

 

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.