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

LeetCode: Sort Colors

时间:2014-09-04 22:10:20      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   strong   for   

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.

地址:https://oj.leetcode.com/problems/sort-colors/

算法:题目要求用一次遍历完成。由于总共就三种元素,那么我们可以设置两个变量pos_red和pos_blue,分别用于表示0到pos_red-1之间存放的都是red元素,pos_blue+1到n-1之间存放的都是blue元素。代码:

 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) {
 4         if(n <= 1 || !A) return;
 5         int pos_red = 0;
 6         int pos_blue = n-1;
 7         for(int i = 0; i <= pos_blue; ){
 8             if(A[i] == 0){
 9                 swap(A[i],A[pos_red]);
10                 ++pos_red;
11                 ++i;
12             }else if(A[i] == 2){
13                 swap(A[i],A[pos_blue]);
14                 --pos_blue;
15             }else{
16                 ++i;
17             }
18         }
19     }
20     void swap(int &a, int &b){
21         int temp = a;
22         a = b;
23         b = temp;
24     }
25 };

 

LeetCode: Sort Colors

标签:style   blog   http   color   os   io   ar   strong   for   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_sort_colors.html

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