首页 > 其他 > 详细

LeetCode Sort Colors

时间:2015-03-14 23:17:32      阅读:324      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!