Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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 };

 

posted on 2014-09-04 21:56  Boostable  阅读(173)  评论(0编辑  收藏  举报