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

    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?

     1 class Solution {
     2 public:
     3     void sortColors(vector<int>& nums) {
     4 
     5         int size=nums.size();
     6         vector<int> c_list(3,0);
     7         for(int i=0;i<size;i++)
     8         {
     9             c_list[nums[i]]++;
    10         }
    11         int i=0;
    12         while(c_list[0]>0)
    13         {
    14             nums[i]=0;
    15             c_list[0]--;
    16             i++;
    17         }
    18         while(c_list[1]>0)
    19         {
    20             nums[i]=1;
    21             c_list[1]--;
    22             i++;
    23         }
    24         while(c_list[2]>0)
    25         {
    26             nums[i]=2;
    27             c_list[2]--;
    28             i++;
    29         }
    30         
    31     }
    32 };
    View Code
  • 相关阅读:
    is as运算符
    继承,多态
    封装等
    面向对象
    在JDBC中使用带参数的SQL语句
    我的程序库:HiCSDB
    我的程序库:HiCSUtil
    Java中,将ResultSet映射为对象和队列及其他辅助函数
    Java版的对象关系映射实现
    Java中的基本数据类型转换
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105937.html
Copyright © 2011-2022 走看看