• 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
  • 相关阅读:
    设计师用的几个网站
    微信小程序开发框架
    数据模型
    数据库系统
    大话设计模式读书笔记(一)
    关于数据统计时的效率
    orcale同一条语句运行速度差异问题
    使用plspl创建orcale作业
    正则表达式(一)
    oracle游标小试
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105937.html
Copyright © 2020-2023  润新知