LeetCode OJ 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.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?


【题目分析】

一个数组中用0,1,2分别代表三种颜色red,white,blue。对这三种颜色排序,使得red在最前面,blue在最后面。最好的办法是一次遍历,使用固定的空间。


【思路】

1. 排序法

这是效率最低的方法,我们要像排序其他数组一样对有三种值(0,1,2)的数组增序排序,时间复杂度在O(n2);

2. 计数法

先遍历一遍数组,统计每种颜色的个数m,n,l,然后进行第二次遍历,写入m个0,n个1,l个2;时间复杂度为O(n);

3. 标记法

我们设置两个标记,分别记录0的结束位置和2的开始位置,遍历当前数组,如果为1则继续向前,如果为0则把它放到0的结束位置之后,如果为2就把它放到2的开始位置之前。这样经过一遍遍历就可以把不同的颜色分开。举个例子如下:


【java代码】

 1 public class Solution {
 2     public void sortColors(int[] nums) {
 3         if(nums == null || nums.length == 0) return;
 4         
 5         int lastred = -1;
 6         int firstblue = nums.length;
 7         int i = 0;
 8         
 9         while(i < firstblue){
10             if(nums[i] == 0){
11                 if(i == lastred + 1)
12                     lastred = i++;
13                 else if(i > lastred + 1){
14                     nums[++lastred] = 0;
15                     nums[i++] = 1;
16                 }
17             }
18             else if(nums[i] == 2){
19                 if(nums[firstblue-1] != 2){
20                     nums[i] = nums[firstblue-1];
21                     nums[--firstblue] = 2;
22                 }
23                 else firstblue--;
24             }
25             else i++;
26         }
27     }
28 }

 

posted @ 2016-05-31 09:25  Black_Knight  阅读(196)  评论(0编辑  收藏  举报