[leetcode/Matrix](sort)Sort Colors-计数排序的运用

约定不等于承诺〃 2021-09-28 07:46 382阅读 0赞

Sort Colors 计数排序

    • 题干:
    • 第一种解法:计数排序
    • 第二种解法:头尾指针解法

题干:

Given an array with n objects colored red, white or blue, sort them in-place(the input is overwritten by the output as the algorithm executes) 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.

Example:

  1. Input: [2,0,2,1,1,0]
  2. Output: [0,0,1,1,2,2]

Please submit a cpp file with the implementation of functionvoid sortColors(vector<int>& nums), you can start like this:

  1. void Solution::sortColors(vector<int>& nums){}

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 a one-pass algorithm using only constant space?

第一种解法:计数排序

① 扫描第一遍,找出最大最小数
② 开辟一个数组a,长度为max-size+1
③ 扫描第二遍数组,记录每个数字出现的频率即a[nums[i]]++
④ 扫描数组a,输出

适用于已经知道最大最小的情况,这是一种牺牲空间的做法

  1. #include"Solution.h"
  2. #include<algorithm>
  3. #include<string.h>
  4. void Solution::sortColors(vector<int>& nums){
  5. int size=nums.size();
  6. int min=1e10;
  7. int max=0;
  8. for(int i=0;i<size;i++){
  9. if(nums[i]<min){
  10. min=nums[i];
  11. }
  12. if(nums[i]>max){
  13. max=nums[i];
  14. }
  15. }
  16. //遍历一遍找出最大最小值
  17. int *a=new int[max-min+1];
  18. memset(a,0,(max-min+1)*sizeof(int));
  19. for(int i=0;i<size;i++){
  20. a[nums[i]-min]++;
  21. }
  22. int count=0;
  23. for(int i=0;i<max-min+1;i++){
  24. while(a[i]){
  25. a[i]--;
  26. nums[count++]=i+min;
  27. }
  28. }
  29. delete []a;
  30. }

第二种解法:头尾指针解法

left左边全是0,right右边全是2
中间是1

  1. #include"Solution.h"
  2. void Solution::sortColors(vector<int>& nums){
  3. int left=0;
  4. int right=nums.size()-1;
  5. int i=0;
  6. while(i<=right){
  7. if(nums[i]==0){
  8. swap(nums[left],nums[i]);
  9. left++;
  10. i++;
  11. }
  12. else if(nums[i]==2){
  13. swap(nums[right],nums[i]);
  14. right--;
  15. }
  16. else
  17. i++;
  18. }
  19. }
  20. void swap(int &a,int& b){
  21. int temp=a;
  22. a=b;
  23. b=temp;
  24. }

发表评论

表情:
评论列表 (有 0 条评论,382人围观)

还没有评论,来说两句吧...

相关阅读

    相关 计数排序

    计数排序 冒泡、选择、插入、归并、快速、希尔、堆排序,都是基于比较的排序,平均时间复杂度最低是O(nlogn)。 计数排序、桶排序、基数排序,都不是基于比较的排序,它们

    相关 计数排序

    计数排序,他的主要目的是对整数排序并且会比普通的排序算法性能更好。 1. 初始化一个计数数组,大小是输入数组中的最大的数。 2. 遍历输入数组,遇到一个数

    相关 计数排序

    对于一个int数组,请编写一个计数排序算法,对数组元素排序。 给定一个int数组A及数组的大小n,请返回排序后的数组。 测试样例: [1,2,3,5,2,

    相关 计数排序

    / 计数排序:统计小于等于该元素值的元素的个数i,于是该元素就放在目标数组的索引i位(i≥0)。 计数排序基于一个假设,待排序数列的

    相关 计数排序

    计数排序: 假设n个输入元素中的每一个都是在0~区间内的一个整数,其中k为某个整数。当k=O(n)是,排序时间为O(n). 基本思想:对每个输入元素x,确定小于x元素的