Sort Colors

用双index从头尾两方向同时遍历

 1 public class Solution {
 2     public void sortColors(int[] A) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         int frontRunner = 0;
 6         int backRunner = A.length - 1;
 7         int i = 0;
 8         while(i < backRunner+1)
 9         {
10             if(A[i] == 0)
11             {
12                 swap(A, frontRunner, i);
13                 frontRunner++;
14                 i++;
15             }
16             else if(A[i] == 1)
17                 i++;
18             else{
19                 swap(A, backRunner, i);
20                 backRunner--;
21             }
22         }
23         
24     }
25     
26     private void swap(int[] matrix, int x, int y)
27     {
28         int tmp = matrix[x];
29         matrix[x] = matrix[y];
30         matrix[y] = tmp;
31     }
32 }
原文地址:https://www.cnblogs.com/jasonC/p/3414355.html