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.

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

Notes:

  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) {
        if(A.length==0)return;
        int red = 0;
        int blue = A.length-1;
        int i = 0;
        while(i <= blue){
            if(A[i]==0){
                //swap with red
                A[i] = A[red];
                A[red] = 0;
                red++;
            }
            if(A[i]==2){
                //swap with blue
                A[i] = A[blue];
                A[blue] = 2;
                blue--;
                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
            }
            i++;
        }
       
    }
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s