首页 > 代码库 > [LeetCode]Sort Colors

[LeetCode]Sort Colors

题目描述:

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.

解题方案:

本题不允许使用STL sort,其实也不需要,因为本题数组中只有由0,1,2三个数字组成,因此可以新开辟一个同等大小的数组B,将元素都初始化为1,然后遍历数组A,如果A[i] = 0,放在B的数组前面,如果A[i] = 1,则放在B数组尾部。下面是本题代码:

 1 class Solution { 2 public: 3     void sortColors(int A[], int n) { 4         int *B = new int[n]; 5         for (int i = 0; i < n; ++i) {B[i] = 1;} 6         int start = 0; 7         int lback = n - 1; 8         for (int i = 0; i < n; ++i) { 9             if (A[i] == 0) {10                 B[start++] = 0;11             }12             if (A[i] == 2) {13                 B[lback--] = 2;14             }15         }16         for (int i = 0; i < n; ++i) {17             A[i] = B[i];18         }19         delete [] B;20     }21 };

 

[LeetCode]Sort Colors