zoukankan      html  css  js  c++  java
  • Sort Colors leetcode java

    题目:

    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?

    题解:

    这道题就是运用指针来解决了,可以说叫3指针吧。

    一个指针notred从左开始找,指向第一个不是0(红色)的位置;一个指针notblue从右开始往左找,指向第一个不是2(蓝色)的位置。

    然后另一个新的指针i指向notred指向的位置,往后遍历,遍历到notred的位置。

    这途中需要判断:

    当i指向的位置等于0的时候,说明是红色,把他交换到notred指向的位置,然后notred++,i++。

    当i指向的位置等于2的时候,说明是蓝色,把他交换到notblue指向的位置,然后notred--。

    当i指向的位置等于1的时候,说明是白色,不需要交换,i++即可。

    代码如下:

     1     public static void swap(int A[], int i, int j){
     2         int tmp = A[i];
     3         A[i]=A[j];
     4         A[j]=tmp;
     5     }
     6     
     7     public static void sortColors(int A[]) {
     8         if(A == null || A.length==0)
     9             return;
    10             
    11         int notred=0;
    12         int notblue=A.length-1;
    13          
    14         while (notred<A.length&&A[notred]==0)
    15             notred++;
    16             
    17         while (notblue>=0&&A[notblue]==2)
    18             notblue--;
    19          
    20         int i=notred;
    21         while (i<=notblue){
    22             if (A[i]==0) {
    23                 swap(A,i,notred);
    24                 notred++;
    25                 i++;
    26             }else if (A[i]==2) {
    27                 swap(A,i,notblue);
    28                 notblue--;
    29             }else
    30                 i++;
    31         }
    32     }

     

  • 相关阅读:
    [bzoj4653] [NOI2016]区间
    [bzoj5285] [HNOI2018]寻宝游戏
    [bzoj4071] [Apio2015]巴邻旁之桥
    [bzoj1146] [CTSC2008]网络管理Network
    [bzoj3004] [SDOi2012]吊灯
    [bzoj5321] [Jxoi2017]加法
    [bzoj5010] [FJOI2017]矩阵填数
    [bzoj3504] [CQOI2014]危桥
    ASP.NET
    ASP.NET
  • 原文地址:https://www.cnblogs.com/springfor/p/3872313.html
Copyright © 2011-2022 走看看