Leetcode– Sort Colors

The Problem:

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.

You are not suppose to use the library’s sort function for this problem.


  1. Fix two number first, look for the two sum up to a target. The n-sum questions all follow the same idea, break down to two sum. See 3 Sum.

Java Solution:

public class Solution {
    public void sortColors(int[] A) {
        int red = 0;
        int blue = A.length-1;
        int i = 0;
        while(i <= blue){
                //swap with red
                A[i] = A[red];
                A[red] = 0;
                //swap with blue
                A[i] = A[blue];
                A[blue] = 2;
                i--; //---!!!--important--for case A[i]=0 then swaped to 2, it go through both branches
                //--but for case A[i] = 2 then switch to 0, need to decrease i so can enter first branch

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s