Sort Colors NO 72

Java Solution

Posted by Captain Nimo 1 month ago

Question

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.

Code

public class Solution {  
    public static void sortColors(int[] nums) {  
        int len = nums.length;  
        int[] tmp = new int[len];  
        for(int i = 0; i < len; i++)       
            tmp[i] = 1;  
        int first = 0, last = len - 1;  
        for(int i=0; i<len; i++)            
            if(nums[i] == 0) tmp[first++] = 0;  
            else if(nums[i] == 2) tmp[last--] = 2;  
        for(int i=0; i<len; i++) nums[i] = tmp[i];  
    }  
}