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.

此题是move zero的变形,多出了一个指针,代码如下:

 1 public class Solution {
 2     public void sortColors(int[] nums) {
 3         if(nums==null||nums.length==0) return;//corner case:if the nums is null or the length of nums is zero;
 4         int i=0,j=0,k=nums.length-1;
 5         while(j<=k){
 6             if(nums[j]==0){
 7                 swap(nums,i,j);
 8                 i++;
 9                 j++;
10             }else if(nums[j]==1){
11                 j++;
12             }else if(nums[j]==2){
13                 swap(nums,j,k);
14                 k--;
15             }
16         }
17     }
18     public void swap(int[] nums,int i,int j){
19         int temp = nums[i];
20         nums[i] = nums[j];
21         nums[j] = temp;
22     }
23 }

 

posted @ 2017-02-02 02:59  CodesKiller  阅读(116)  评论(0编辑  收藏  举报