首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。