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.
题意:将一堆乱序的0,1,2组成的数组将其他排成0,1,2有序的
题解:采用2个指针,start记录0前面的数为止,end为2的为止,遍历数组遇到0,与前面的数交换,遇到2与后面的数交换。
code:
package com.leetcode.mair;
public class Solution75{
public void sortColors(int[] nums) {
int start=0,end = nums.length-1;
if(nums.length<2)
return;
for(int i=0; i<nums.length; i++){
if(nums[i] == 0){
swap(nums, start++, i);
}else if(nums[i] == 2){ // i--,交换后继续比较,避免未比较的数
swap(nums, end--, i--);
}
}
}
public void swap(int nums[],int x,int y){
int temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
public static void main(String[] args) {
int nums[] = {2,2};
new Solution75().sortColors(nums);
for(int i=0; i<nums.length; i++){
System.out.print(nums[i]+" ");
}
}
}