sort-colors——排序3种数字

题目描述

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.

click to show follow up.

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的序列按顺序排好。
【扫描两遍的计数排序】
 1 public class Solution {  
 2     public void sortColors(int[] A) {  
 3         int i, r, w, b;  
 4         r = w = b = 0;  
 5         for (i = 0; i < A.length; i++) {  
 6             if (A[i] == 0) r++;  
 7             else  if (A[i] == 1) w++;  
 8             else b++;  
 9         }  
10         for (i = 0; i < A.length; i++) {  
11             if (i < r) A[i] = 0;  
12             else if (i < r + w) A[i] = 1;  
13             else A[i] = 2;  
14         }  
15     }  
16 }  

【扫描一遍,单向遍历】

注意,l记录0区,r记录2区的边界。因此循环遍历到i<=r即可。

 1 class Solution {
 2 public:
 3     void swap(int A[], int i, int j){
 4         int tmp=A[i];
 5         A[i]=A[j];
 6         A[j]=tmp;
 7     }
 8     void sortColors(int A[], int n) {
 9         int l=0,r=n-1;
10         for(int i=0;i<=r;i++){
11             if(A[i]==0){
12                 swap(A,i,l);
13                 l++;
14             }
15             else if(A[i]==2){
16                 swap(A,i,r);
17                 r--;
18                 i--;
19             }
20         }
21     }
22 };
原文地址:https://www.cnblogs.com/zl1991/p/7092210.html