75. 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.

给定一个包含红,白,蓝且长度为n的数组,将数组元素进行分类使同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数0,1和2分别代表红,白,蓝。

 1     private void swap(int[] nums,int left,int right)
 2     {
 3         int temp = nums[left];
 4         nums[left] = nums[right];
 5         nums[right] = temp;
 6     }
 7     
 8     public void sortColors(int[] nums) {
 9         int second=nums.length-1, zero=0;
10         for (int i=0; i<=second; i++) {
11             while (nums[i]==2 && i<second) swap(nums,i,second--);
12             while (nums[i]==0 && i>zero) swap(nums,i,zero++);
13         }  
14     }
原文地址:https://www.cnblogs.com/wzj4858/p/7676028.html