[Xi. Algorithm series] the Dutch flag issue

Source: Internet
Author: User

"Problem"

Existing red and white blue three different colors of the ball, disorderly order together, please rearrange these small balls, so that the red and white blue Three colors of the same color ball together. The problem with the Dutch flag is that we can think of the red, white, and blue three-colored balls as strips, arranged in order to form the Dutch flag.

"Analysis"

We can consider this problem as an array sorting problem. red and white blue correspond to numbers 0, 1, 2 respectively. The number of red, white, and blue balls is not necessarily the same.

"Idea One"

First, iterate the array counting number of 0 ' s, 1 ' s, and 2 ' s, then overwrite array with total number of 0 ' s, then 1 ' s and Followed by 2 ' s.

(1) Iterate the array, statistics the number of red white blue tri-color ball (0,1,2)

(2) rearrange arrays According to the number of red, white and blue tri-color balls (0,1,2)

Time complexity: O (N)

"Code One"

    /**------------------------------------* Date: 2015-02-02 * SJF0115 * Title: 75.Sort Colors * URL: https: oj.leetcode.com/problems/sort-colors/* Results: AC * Source: Leetcode * Blog:------------------------------------ ---**/class Solution {public:void sortcolors (int a[], int n) {if (n <= 1) {RET            Urn            }//if//Count int red = 0,white = 0,blue = 0;                for (int i = 0;i < N;++i) {if (a[i] = = 0) {++red;                }//if else if (a[i] = = 1) {++white;                }//else else{++blue;                    }//else}//for//re-layout for (int i = 0;i < N;++i) {if (Red > 0) {                    A[i] = 0;                --red;                    }//if else if (White > 0) {a[i] = 1; --whitE                }//else else{A[i] = 2; }}//for}};

"Thinking Two"

We can divide the array into three parts, the front (all 0), the middle (all 1) and the rear (all 2) three parts, and each element (red and white blue corresponds to 0, 1, 2) must belong to one of them.

The front and rear rows are lined up in front and back of the array, and the middle is naturally lined up.

Set two pointers begin to point to the next element at the end of the front (no 0 at the beginning of the default, so point to the first position), end points to the previous position at the beginning of the rear (No 2 at the beginning of the default, so point to the last position), and then set a traverse pointer current to traverse from the beginning.

(1) if the traverse to the position of 1, then it must belong to the middle, according to the general idea, we are not moving in the middle, then the current move forward a position.

(2) if the traverse to a position of 0, then it must belong to the front, so it is exchanged with the begin position, and then the current moves forward a position , begin also moves forward a position (indicating that the front is already lined up).

(3) if the traverse to the position of 2, then it must belong to the rear, so it is exchanged with the end position, since the exchange is completed after the current point may belong to the front, if at this time current forward will cause the position can not be exchanged to the front, so at this time current does not advance. with 1), end moves one position forward.

"code two"

    /**------------------------------------    *   Date: 2015-02-04    *   SJF0115    *   title: Sort Colors    *   Website: https://oj.leetcode.com/problems/sort-colors/    *   blog:    ----------------------------------- ----**/   class Solution {public    :        void sortcolors (int a[], int n) {            int begin = 0,end = N-1,cur = 0;
   while (cur <= end) {                if (a[cur] = = 0) {                    swap (a[begin],a[cur]);                    Point to the next position at the end of sort 0                    ++begin;                    Traverse                    ++cur forward;                } If                else if (a[cur] = = 1) {                    ++cur;                } else                else{                    swap (a[end],a[cur]);                    Point to the previous position of the beginning of the sort 2                    --end;                } else            }//for        }    };


"Thinking three"

Record the subscript position of the red,white,blue with three variables. The starting subscript is-1

If a[i] = = 0, insert red on white blue has an effect, blue first move one bit backwards, white and then the overall backward move one bit, if not moved, the data before the inserted will overwrite the existing.

If a[i] = = 1, insert White has an effect on blue and the blue whole moves backwards one bit.

A[i] = = 2, insert directly into blue

"code three"

    /**------------------------------------* Date: 2015-02-03 * SJF0115 * Title: 75.Sort Colors * URL: https: oj.leetcode.com/problems/sort-colors/* Results: AC * Source: Leetcode * Blog:------------------------------------ ---**/class Solution {public:void sortcolors (int a[], int n) {if (n <= 1) {RE            Turn            }//if int red = -1,white = -1,blue =-1; for (int i = 0;i < N;++i) {//insert red on white blue has an effect if (a[i] = = 0) {//Blu                    E-Move the whole backwards one a[++blue] = 2;                    White whole moves backwards one a[++white] = 1;                Insert Red a[++red] = 0;                    }//if//Insert white blue affected else if (a[i] = = 1) {//Blue overall move backward one                    A[++blue] = 2;                Insert White a[++white] = 1;         }//else       Inserting blue has no effect on the other else{//inserting blue a[++blue] = 2; }//else}//for}};



Reference: http://www.cnblogs.com/gnuhpc/archive/2012/12/21/2828166.html


[Xi. Algorithm series] the Dutch flag issue

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.