Leetcode_sort-colors(c++ and python updated)

来源:互联网 发布:犇犇网络 编辑:程序博客网 时间:2024/05/06 06:22
地址:http://oj.leetcode.com/problems/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.

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

思路:遇0则从头开始换,遇2从尾开始换,用两个游标left和right记录0和2的范围。
参考代码:
class Solution {public:    void sortColors(int A[], int n) {        int left = 0, right = n-1;        for(int i = 0; i < n && left<right;)        {            if(A[i]==0)            {                if(i>left)                {                    A[i]=A[left];                    A[left++] = 0;                }                else                    ++i;            }            else if(A[i]==2)            {                if(i<right)                {                    A[i]=A[right];                    A[right--]=2;                }                else                    ++i;            }            else                ++i;        }    }};


SECOND TRIAL

c++:
class Solution {public:    void sortColors(int A[], int n) {        int i = 0, j = n-1, k=0;        while(k<=j)        {            if(A[k]==0)                swap(A[i++], A[k]);            else if(A[k]==2)                swap(A[j--], A[k]);            else                ++k;            if(i>k)                k = i;        }    }};

python:
class Solution:    # @param A a list of integers    # @return nothing, sort in place    def sortColors(self, A):        k = i = 0        j = len(A)-1        while k<=j:            if not A[k]:                A[i], A[k] = A[k], A[i]                i+=1            elif A[k]==2:                A[j], A[k] = A[k], A[j]                j-=1            else:                k+=1            if i>k:                k = i

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

0 0