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
  • 相关阅读:
    MySQL经典练习题(四)
    MySQL经典练习题(三)
    MySQL经典练习题(二)
    MySQL经典练习题(一)
    MySQL经典练习题-数据准备
    表连接
    子查询
    MySQL中函数分类
    排序
    数据分组
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105937.html
Copyright © 2011-2022 走看看