zoukankan      html  css  js  c++  java
  • Sort Colors

    1. Title

    Sort Colors

    2.   Http address

    https://leetcode.com/problems/sort-colors/

    3. The question

    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.

    4. My code (AC)

     1 // Accepted
     2     public static void sortColors(int []nums){
     3         if( nums == null || nums.length <= 1)
     4                 return;
     5         int len = nums.length;
     6         int i,j,tmp;
     7         i = 0; j = len -1;
     8         while(i < len && j >= i )
     9         {
    10 
    11             if( nums[i] == 0)
    12             {
    13                 i++;
    14                 continue;
    15             }
    16 
    17             if ( nums[j] != 0 )
    18             {
    19                 j--;    
    20                 continue;
    21             }
    22 
    23             tmp = nums[i];
    24             nums[i] = nums[j];
    25             nums[j] = tmp;
    26             i++;
    27             j--;
    28         }
    29 
    30         i = 0;
    31         while( i < len && nums[i] == 0)
    32         {
    33                 i++;
    34         }
    35         j = len-1;
    36         while( i < len && j >= i)
    37         {
    38 
    39             if( nums[i] == 1 )
    40             {
    41                 i++;
    42                 continue;
    43             }
    44 
    45             if(nums[j] == 2 )
    46             {
    47                 j--;
    48                 continue;
    49             }
    50     
    51             tmp = nums[i];
    52             nums[i] = nums[j];
    53             nums[j] = tmp;
    54             i++;
    55             j--;
    56         }
    57     }
  • 相关阅读:
    Java图片裁剪
    jvm参数
    Druid数据源监控配置
    执行jar包或执行其中的某个类
    十进制和二进制之间的相互转化
    Java位运算
    获取网络资源保存本地
    前端PHP入门-010-内部函数
    前端PHP入门-011-可变函数
    前端PHP入门-009-匿名函数
  • 原文地址:https://www.cnblogs.com/ordili/p/4928336.html
Copyright © 2011-2022 走看看