[Leetcode] Sort Colors

Source: Internet
Author: User

Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue.

Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

0 1 2

Count-sort like, but in one pass

Pointers start from beginning

          1. Zero stands for the end of 0s

          2. One stands for the end of 1s

          3. A third pointer iterate through the array, when found a 1, change the current number to 2 and change one to 1 and move one To Next

          4. When found a 0, the change of the current number to 2, change one to 1, move one to next and then change from zero to 0, move Zero to next (order matters, when one was at the same position as zero, we want this position to being 0 at T to 1 First,then 0)

     Public voidSortcolors (int[] nums) {        if(Nums = =NULL|| Nums.length = = 0)return; intZero = 0; intone = 0;  for(inti = 0; i < nums.length; i++){            if(Nums[i] = = 0) {Nums[i]= 2; Nums[one+ +] = 1; Nums[zero+ +] = 0; }            Else if(Nums[i] = = 1) {Nums[i]= 2; Nums[one+ +] = 1; }        }            }

Now we add one restriction: What's in the array are not integers, is a object, so we could only use swap

if (Nums[cur] = = 1) {    cur+ +;} Else if (Nums[cur] = = 0) {    swap (cur, zero);    Zero+ +;    Cur+ +;} Else {    swap (cur, both);    double--;}

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