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.


Two pointers

public void sortColors(int[] nums) {

    if(nums.length == 0) return ;

    int i = 0, start = 0, end = nums.length - 1;

    while(i <= end){
        if(nums[i] == 0){
            swap(nums, start, i);
            start ++;
            if(start > i) 
                i = start;
        }else if(nums[i] == 2){
            swap(nums, end, i);
            end --;
        }else i ++;
    }
}

private void swap(int []nums, int i, int j){
    int tmp = nums[i];
    nums[i] = nums[j];
    nums[j] = tmp; 
}

K loops

public void sortColors(int[] nums) {
    int index = 0;

    for(int k = 0 ; k < 2; k++){
        for(int j = index; j < nums.length; j++){
            if(nums[j] == k){
                nums[j] = nums[index];
                nums[index] = k;
                index ++;
            }
        }
    }
}

results matching ""

    No results matching ""