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
  • 相关阅读:
    angular2 如何使用animate实现动画效果
    angular2+ 组件中用@import进来的css不起作用
    ReentrantLock & AQS
    常用JDK命令
    分布式缓存
    持续交付
    持续部署
    持续集成
    领域驱动设计简介
    spring boot 整合JPA bean注入失败
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105937.html
Copyright © 2011-2022 走看看