Wednesday, June 17, 2015

Sort Colors | Leetcode

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.


Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

---

Solution: Keep the index of the last red (0) and the first blue (2). Start by iterating from the end of the array and filter out the blues. Then start iterating from the first element to the element before the index of the first blue we found so far. When we see a red, swap it with the first non-red element and increment the red pointer. When we see a blue, swap it with the last non-blue element and decrement the blue pointer. All the whites (1), if any, will remain in the middle of the array.
public class Solution {
    public void sortColors(int[] nums) {
        int blue = nums.length - 1;
        while (blue >= 0 && nums[blue] == 2) blue--;
        for (int i = 0, red = 0; i <= blue; i++) {
            if (nums[i] == 0) {
                if (i != red) {
                    int tmp = nums[red];
                    nums[red] = 0;
                    nums[i] = tmp;
                }
                red++;
            } else if (nums[i] == 2) {
                int tmp = nums[blue];
                nums[blue--] = 2;
                nums[i--] = tmp;
            }
        }
    }
}

No comments: