Sort Colors--LeetCode

向右看齐 2022-08-07 11:44 156阅读 0赞

题目:

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.

思路:类似于快速排序的partition过程,下面的代码是非常纯粹的使用这个思想,事件复杂度为O(n),其实这里可以将两个循环合并成一个,0是从头开始,2是从尾部开始,但是没有这么做,如果是四个颜色,最好的方式就是首先通过一个循环将其中一个和其余三个分开,然后再一次循环将剩余的三个分开。

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5. /*
  6. 类似于排序 只不过很多重复的
  7. */
  8. void SortColors(vector<int>& vec)
  9. {
  10. int i,j;
  11. i = -1;
  12. // 先把0排好
  13. for(j=i+1;j<vec.size();j++)
  14. {
  15. if(vec[j] == 0)
  16. {
  17. i++;
  18. swap(vec[i],vec[j]);
  19. }
  20. }
  21. // 再把1 排序好
  22. for(j = i+1;j<vec.size();j++)
  23. {
  24. if(vec[j] == 1)
  25. {
  26. i++;
  27. swap(vec[i],vec[j]);
  28. }
  29. }
  30. }
  31. int main()
  32. {
  33. vector<int> vec(10);
  34. int i;
  35. for(i=0;i<vec.size();i++)
  36. vec[i] = i%3;
  37. SortColors(vec);
  38. for(i=0;i<vec.size();i++)
  39. cout<<vec[i]<<" ";
  40. cout<<endl;
  41. return 0;
  42. }

发表评论

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

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

相关阅读

    相关 python的sortsorted

    一、sort 方法 sort 方法是列表的方法,用于在原地对列表进行排序,即直接修改原始列表,不返回新的列表。 它可以接受两个可选参数:key 和 reverse。