[LeetCode] Sort Colors, leetcodecolors

Source: Internet
Author: User

[LeetCode] Sort Colors, leetcodecolors
Given an array with n objects 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.

Idea 1: directly traverse the array to count the number of three colors and then fill them in sequence. complexity O (N)

Code 1:

Public void sortColors1 (int [] A) {// count the numbers of 1, 2, and 3 int [] colorCount = new int [3]; for (int I = 0; I <. length; ++ I) {switch (A [I]) {case 0: colorCount [0] ++; break; case 1: colorCount [1] ++; break; case 2: colorCount [2] ++; break;} int from, I = 0, to = 0; while (I <colorCount. length) {from = to; to = to + colorCount [I]; Arrays. fill (A, from, to, I); I ++ ;}}

Train of Thought 2: Simulate the fast-forward, and move 2 and 0 to both sides respectively. This only needs to traverse the array once, and the algorithm complexity O (N)
Code 2:
Public void sortColors (int [] A) {// using the fast sorting idea, final int RED = 0, WHITE = 1, BLUE = 2; int l = 0, r =. length-1, mid = l; while (mid <= r) {if (A [mid] = RED) {int temp = A [mid]; A [mid] = A [l]; A [l] = temp; l ++; mid ++;} else if (A [mid] = BLUE) {int temp = A [mid]; A [mid] = A [r]; A [r] = temp; r -- ;} else {mid ++ ;}}}


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.