Thursday, January 8, 2015

LeetCode 75: Sort Colors

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.
public class Solution {
    public void sortColors(int[] A) {
        // Similar to Quick3way sort but without recursion
        int lt = 0, gt = A.length-1;   
        int i = 0;   
        
        while (i <= gt)   
        {   
            if (A[i] == 0)
                swap(A, i++, lt++);
            else if (A[i] == 2)
                swap(A, i, gt--);   
            else 
                i++;   
        }
    }
    
    private void swap(int[] A, int i, int j)
    {
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}

No comments:

Post a Comment