## 荷兰国旗排序的几种解法

2019年10月02日 ⁄ 综合 ⁄ 共 1323字 ⁄ 字号 评论关闭

# 荷兰国旗排序的几种解法

`leetcode` `排序` `算法`
`分治`

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.

leetcode Sort Colors

Method 1

``//时间复杂度 O(n),空间复杂度O(1)``class Sloution {``public:``    void sortColorts(int A[], int n) {``        int colors[3]={0};``        for( int i = 0; i < n; ++i)``            colors[A[i]]++;``        for(int i = 0, index =0; i < 3; ++i)``        {``            for(int j=0; j< colors[i]; ++j)``                A[index++] = i;``        }``    }``}``

Method 2

``//时间复杂度 O(n),空间复杂度O(1)``class Solution {``public:``    void sortColors(int A[], int n) {``        int begin = 0, cur = 0, end = n-1;``        while(cur != end)``        {``            if(A[cur] == 0)``            {``                swap(A[begin],A[cur]);``                begin++;``                cur++;``            } else if(A[cur] == 1)``            {``                cur++;``            } else``            {``                swap(A[cur], A[end]);``                end--;``            }``        }``    }``};``

Method 3

``//时间复杂度 O(n),空间复杂度O(1)``class Solution {``public:``    void sortColors(int A[], int n) {``        int i=-1,j=-1,k=-1;``        for(int p = 0; p < n; ++p)``        {``            if(A[p] == 0)``            {``                A[++k] = 2;``                A[++j] = 1;``                A[++i] = 0;``            }``            else if (A[p] == 1)``            {``                A[++k] = 2;``                A[++j] = 1;``            }``            else if (A[p] == 2)``            {``                A[++k] = 2;``            }``        }``    }``};``

Method 4

``//时间复杂度O(n)，空间复杂度O(1)``class Solution {``public:``    void sortColors(int A[], int n) {``        int red = 0, blue = n-1;``        for （int i = 0; i < n; ++i)``        {``            if(A[i] == 0)``                swap(A[i++], A[red++]);``            else if (A[i] == 2)``            {``                swap(A[i++],A[blue--]);``            }``            else``            {``                i++;``            }``        }``    }``};``