Leetcode: Sort Colors

红太狼 2022-08-07 12:47 189阅读 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.

思路分析:
题目出了这样的提示:
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?

按照提示two-pass算法代码如下,这个比较简单。
C++参考代码:

  1. class Solution {
  2. public:
  3. void sortColors(int A[], int n)
  4. {
  5. int count[3] = {
  6. 0};
  7. for (int i = 0; i < n; i++)
  8. {
  9. if (0 == A[i]) count[0] += 1;
  10. else if (1 == A[i]) count[1] += 1;
  11. else if (2 == A[i]) count[2] += 1;
  12. }
  13. int x = count[0] + count[1];
  14. int y = x + count[2];
  15. for (int i = 0; i < n; i++)
  16. {
  17. if (i < count[0]) A[i] = 0;
  18. else if (i < x) A[i] = 1;
  19. else if (i < y) A[i] = 2;
  20. }
  21. }
  22. };

那什么是所谓的one-pass算法呢?

我们可以定义两个指针:一个指针left指向当前应该插入0的位置,一个指针right指向当前应该插入2的位置,再利用一个指针current进行循环遍历。遇到0的时候就插入left的位置,left前进一位,遇到2的时候就插入right的位置,right后退一位,遇到1的时候,current前进一位。

C++参考代码:

  1. class Solution
  2. {
  3. public:
  4. void sortColors(int A[], int n)
  5. {
  6. int left = 0;
  7. int right = n - 1;
  8. int current = 0;
  9. //注意这里是<=不是<
  10. while (current <= right)
  11. {
  12. if (0 == A[current])
  13. {
  14. swap(A[current], A[left]);
  15. ++left;
  16. //处理left可能大于current的情况
  17. current = left > current ? left : current;
  18. }
  19. else if (2 == A[current])
  20. {
  21. swap(A[current], A[right]);
  22. --right;
  23. }
  24. else
  25. {
  26. ++current;
  27. }
  28. }
  29. }
  30. };

发表评论

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

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

相关阅读

    相关 LeetCode75——Sort Colors

    LeetCode75——Sort Colors 简要的分析一下题意就是对只包含 0,1,2 这三个数的数组进行排序。 这里提供三种方案,前两种是自己Y出来的,后一种是大