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

[LeetCode]Sort Colors

时间:2014-10-21 00:43:54      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   使用   for   strong   

题目描述:

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

标签:style   blog   color   io   os   ar   使用   for   strong   

原文地址:http://www.cnblogs.com/skycore/p/4039147.html

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