现在的位置: 首页 > 综合 > 正文

荷兰国旗排序的几种解法

2019年10月02日 ⁄ 综合 ⁄ 共 1323字 ⁄ 字号 评论关闭

荷兰国旗排序的几种解法

leetcode 排序 算法
分治


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.

leetcode Sort Colors

Method 1
统计各颜色出现的次数,然后重新给颜色数组赋值

  1. //时间复杂度 O(n),空间复杂度O(1)
  2. class Sloution {
  3. public:
  4. void sortColorts(int A[], int n) {
  5. int colors[3]={0};
  6. for( int i = 0; i < n; ++i)
  7. colors[A[i]]++;
  8. for(int i = 0, index =0; i < 3; ++i)
  9. {
  10. for(int j=0; j< colors[i]; ++j)
  11. A[index++] = i;
  12. }
  13. }
  14. }

Method 2
利用快速排序的思想,遍历,交换元素

  1. //时间复杂度 O(n),空间复杂度O(1)
  2. class Solution {
  3. public:
  4. void sortColors(int A[], int n) {
  5. int begin = 0, cur = 0, end = n-1;
  6. while(cur != end)
  7. {
  8. if(A[cur] == 0)
  9. {
  10. swap(A[begin],A[cur]);
  11. begin++;
  12. cur++;
  13. } else if(A[cur] == 1)
  14. {
  15. cur++;
  16. } else
  17. {
  18. swap(A[cur], A[end]);
  19. end--;
  20. }
  21. }
  22. }
  23. };

Method 3
同样维护三个指针,指向0,1,2的三个数组的起始位置。如果下一个数字是0,向右移动1,2两个指针的位置,将0放到合适的位置。移动指针时,并没有移动整个数组,只需要3个位置需要改变。 1和2同上

  1. //时间复杂度 O(n),空间复杂度O(1)
  2. class Solution {
  3. public:
  4. void sortColors(int A[], int n) {
  5. int i=-1,j=-1,k=-1;
  6. for(int p = 0; p < n; ++p)
  7. {
  8. if(A[p] == 0)
  9. {
  10. A[++k] = 2;
  11. A[++j] = 1;
  12. A[++i] = 0;
  13. }
  14. else if (A[p] == 1)
  15. {
  16. A[++k] = 2;
  17. A[++j] = 1;
  18. }
  19. else if (A[p] == 2)
  20. {
  21. A[++k] = 2;
  22. }
  23. }
  24. }
  25. };

Method 4
两个指针,和快排的解法一样

  1. //时间复杂度O(n),空间复杂度O(1)
  2. class Solution {
  3. public:
  4. void sortColors(int A[], int n) {
  5. int red = 0, blue = n-1;
  6. for int i = 0; i < n; ++i)
  7. {
  8. if(A[i] == 0)
  9. swap(A[i++], A[red++]);
  10. else if (A[i] == 2)
  11. {
  12. swap(A[i++],A[blue--]);
  13. }
  14. else
  15. {
  16. i++;
  17. }
  18. }
  19. }
  20. };

抱歉!评论已关闭.