Three-color sorting

Source: Internet
Author: User

Main topic:

Give you a red, white, blue array of three colors, ordered according to the Order of red, white, and blue, Leetcode link: https://leetcode.com/problems/sort-colors/

Idea 1:

Sort the entire array directly, time complexity O (NLOGN)

Idea 2:

Count sorting method, use a hash-like array to record the number of each color, and then sort, but need to traverse the original array two times

Idea 3:

Using three pointers, P1 represents the dividing line between red and white, p2 represents the dividing line between white and blue, and I represents the current element

That is, 0~p1-1 is red, p1~i-1 is white, p2+1~n-1 means blue.

1) If the current element is red, it is exchanged with the element pointed to by P1, because the color I refer to after the interchange is white, I traverse the next element directly

2) If the current element is blue, it is exchanged with the element pointed to by the P2, because the color I refer to after the interchange may be white, it may be red, so I need to rewind I

The implementation code is as follows: note I should be between [P1,P2]

classsolution{ Public:    voidSortcolors (vector<int>&nums) {    intn =nums.size (); if(N <=1)    {    return; }     intP1 =0; intP2 = n-1; //Notice the cyclic condition of I     for(intI=0; i<=p2; ++i) {if(Nums[i] = =0) {swap (NUMS[P1], nums[i]); ++P1; }    Else if(Nums[i] = =2) {swap (NUMS[P2], nums[i]); --P2; --i; }    }    }Private:    voidSwapint&a,int&b) {intTMP =A; A=b; b=tmp; }};

Three-color sorting

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.