zoukankan      html  css  js  c++  java
  • 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.

    click to show follow up.

    Analyse: First put all 0s in the left parts, then put all 2s in the right parts.

    Runtime: 4ms.

    new version!!

     1 class Solution {
     2 public:
     3     void sortColors(vector<int>& nums) {
     4         if(nums.size() <= 1) return;
     5         
     6         int red = 0, blue = nums.size() - 1;
     7         for(int i = 0; i < blue + 1; ){
     8             if(nums[i] == 0){
     9                 swap(nums[i], nums[red]);
    10                 red++;
    11                 i++;
    12             }
    13             else if(nums[i] == 2){
    14                 swap(nums[i], nums[blue]);  //be careful about this index!!
    15                 blue--;
    16             }
    17             else i++;
    18         }
    19         
    20         return;
    21     }
    22 };
     1 class Solution {
     2 public:
     3     void sortColors(vector<int>& nums) {
     4         if(nums.size() <= 1) return;
     5         
     6         int index = 0;
     7         
     8         //sort all 0s in the left part
     9         for(int i = 0; i < nums.size(); i++){
    10             if(nums[i] == 0){
    11                 swap(nums[index], nums[i]);
    12                 index++;
    13             }
    14         }
    15         
    16         //sort all 2s int the right part
    17         if(index < nums.size()){
    18             int move = nums.size() - 1;
    19             for(int j = move; j >= index; j--){
    20                 if(nums[j] == 2){
    21                     swap(nums[j], nums[move]);
    22                     move--;
    23                 }
    24             }
    25         }
    26         
    27         return;
    28     }
    29 };
  • 相关阅读:
    Oracle 列顺序测试
    Java基于Servlet过虑器
    Java基于Servlet 验证吗
    WCF实例上下文
    WCF的行为与异常-------配置文件说明
    WCF异步
    WCF的通信
    分布式架构剖析
    [loj2542]「PKUWC2018」随机游走——min-max容斥+树上高消
    [bzoj4589]Hard Nim——SG函数+FWT
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4669998.html
Copyright © 2011-2022 走看看