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[] nums) {
        int notred = 0;
        int notblue = nums.length-1;
        while (notred<nums.length && nums[notred]==0) {
        	notred++;
        }
        while (notblue>=0 && nums[notblue]==2) {
        	notblue--;
        }
        int i = notred;
        while (i <= notblue) {
        	if (nums[i] == 0) {
        		int tmp = nums[i];
        		nums[i] = nums[notred];
        		nums[notred] = tmp;
        		i++;
        		notred++;
        	} else if (nums[i] == 2) {
        		int tmp = nums[i];
        		nums[i] = nums[notblue];
        		nums[notblue] = tmp;
        		notblue--;
        	} else {
        		i++;
        	}
        }
    }
}

 

你可能感兴趣的:(color)