论坛首页 编程语言技术论坛

[LeetCode] Sort Colors

浏览 1104 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-03  

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.

 

class Solution {
public:
    void sortColors(int A[], int n) {
        int r = 0, w = 0, b = n - 1;
        int* a = A;
        while (a[r] == 0) r++;
        while (a[b] == 2) b--;
        
        w = r;
        
        while (w <= b) {
            int t = 0;
            while (r <= w && w <= b && a[w] != 1) {
                if (a[w] == 0) swap(a[r++], a[w]);
                else if (a[w] == 2) swap(a[w], a[b--]);
            }
            w++;
        }
        
    }
};

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics