码迷,mamicode.com
首页 > 其他好文 > 详细

Sort Colors

时间:2015-10-01 22:58:42      阅读:255      评论:0      收藏: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.

 

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?

void sortColors(int* nums, int numsSize) {
  if(numsSize<2||nums==NULL)
    return;
  int *ptr=malloc(3*sizeof(int));
  int i,j;
  for(i=0;i<3;i++)//初始化
  {
    ptr[i]=0;
  }
  for(i=0;i<numsSize;i++)//对三种颜色计数
  {
    ptr[nums[i]]++; 
  }
  
for(i=0;i<ptr[0];i++)  {     nums[i]=0;   }   j=ptr[0]+ptr[1];   for(;i<j;i++)   {     nums[i]=1;   }    j+=ptr[2];   for(;i<j;i++)   {     nums[i]=2;   } }

下面是别人的代码:

 1 // LeetCode, Sort Colors
 2 // Counting Sort
 3 // 时间复杂度O(n),空间复杂度O(1)
 4 class Solution {
 5 public:
 6   void sortColors(int A[], int n) {
 7   int counts[3] = { 0 }; // 记录每个颜色出现的次数
 8   for (int i = 0; i < n; i++)
 9     counts[A[i]]++;
10   for (int i = 0, index = 0; i < 3; i++)
11     for (int j = 0; j < counts[i]; j++)
12       A[index++] = i;
13   }
14 };
 1 // LeetCode, Sort Colors
 2 // 双指针,时间复杂度O(n),空间复杂度O(1)
 3 class Solution {
 4 public:
 5     void sortColors(int A[], int n) {
 6     // 一个是red 的index,一个是blue 的index,两边往中间走
 7         int red = 0, blue = n - 1;
 8         for (int i = 0; i < blue + 1;) {
 9       if (A[i] == 0)
10         swap(A[i++], A[red++]);
11       else if (A[i] == 2)
12         swap(A[i], A[blue--]);
13       else
14         i++;
15     }
16   }
17 };            
// LeetCode, Sort Colors
// 重新实现partition()
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
  public:
    void sortColors(int A[], int n) {
      partition(partition(A, A + n, bind1st(equal_to<int>(), 0)), A + n,bind1st(equal_to<int>(), 1));
    }
  private:
    template<typename ForwardIterator, typename UnaryPredicate>
    ForwardIterator partition(ForwardIterator first, ForwardIterator last,UnaryPredicate pred) {
      auto pos = first;
      for (; first != last; ++first)
        if (pred(*first))
          swap(*first, *pos++);
      return pos;
    }
};

 

Sort Colors

标签:

原文地址:http://www.cnblogs.com/chym1009/p/4851611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!