Leetcode: Sort Colors

来源:互联网 发布:jdk 7u80 linux x64 编辑:程序博客网 时间:2024/06/11 03:28

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.

比较直观的是快排,先移0,再移1.

class Solution {public:    void sortColors(int A[], int n) {        int i, j;        for (i = 0, j = n - 1; i < j;) {            while (i < j && A[i] == 0) {                ++i;            }            while (i < j && A[j] != 0) {                --j;            }            swap(A, i, j);        }                for (j = n - 1; i < j;) {            while (i < j && A[i] == 1) {                ++i;            }            while (i < j && A[j] != 1) {                --j;            }            swap(A, i, j);        }    }        void swap(int A[], int i, int j) {        int tmp = A[i];        A[i] = A[j];        A[j] = tmp;    }};
要求只扫描一遍呢?可以设置两个变量,一个i表明1开始的位置,一个k表明2开始的位置。

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

======================第二次======================

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


0 0
原创粉丝点击