Sort Colors(lintcode 148)

Description

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.

Notice:
You are not suppose to use the library's sort function for this problem. 
You should do it in-place (sort numbers in the original array).

Example

Given [1, 0, 1, 2], sort it in-place to [0, 1, 1, 2].

Interface

class Solution {
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */
    public void sortColors(int[] nums) {
        // write your code here
    }
}

Solution

class Solution {
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */
    public void sortColors(int[] nums) {
        // write your code here
        int pl = 0;
        int pr = nums.length - 1;
        int curr = 0;

        while (curr <= pr) {
            if (nums[curr] == 0) {
                swap(nums, pl, curr);
                ++pl;
                ++curr;
            } else if (nums[curr] == 1) {
                ++curr;
            } else {
                swap(nums, pr, curr);
                --pr;
            }
        }
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

results matching ""

    No results matching ""