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

LeetCode Sort Colors

时间:2015-03-14 23:19:13      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

1.题目


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.


2.解决方案


class Solution {
public:
    void sortColors(int A[], int n) {
        int left = 0;
        int right = n - 1;
        int current = 0;
        while(current <= right){
            if(A[current] == 0){
                swap(A[left], A[current]);
                ++left;
                ++current;
            }else if(A[current] == 2){
                swap(A[current], A[right]);
                --right;
            }else{
                ++current;
            }
        }
    }
};

思路:首先题目的意思把一个只有0,1,2的乱序数组排序成000111222的次序。因为只有3个数,所以可以用3个变量来交换,把0都换到前面,把2都换到后面。用一个指向开头,用一个指向结尾,把2都换到尾部去。

http://www.waitingfy.com/archives/1634

LeetCode Sort Colors

标签:

原文地址:http://blog.csdn.net/fox64194167/article/details/44263769

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