LeetCode Sort Colors

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

原文地址:https://www.cnblogs.com/llguanli/p/7018376.html