Sunday, March 22, 2015

Sort Colors II

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

-------------------- thinking --------------------------
http://codeanytime.blogspot.com/2014/12/sort-colors-ii.html
Use inplace to record the count of each number. It's a way of doing count sorting
---------------------- codes ----------------------------------
class Solution{
public:
    /**
     * @param colors: A list of integer
     * @param k: An integer
     * @return: nothing
     */    
    void sortColors2(vector<int> &colors, int k) {
        // write your code here
        int start = 0;
        while (start < colors.size()) {
            if (colors[start] <= 0) {
                start++;
                continue;
            }
            int pos = colors[start] - 1;
            if (colors[pos] <= 0) {
                colors[start] = 0;
                colors[pos]--;
                start++;
            } else {
                colors[start] = colors[pos];
                colors[pos] = -1;
            }
        }
        int index = colors.size() - 1;
        int fill_id = colors.size() - 1;
        while (index >= 0) {
            if (colors[index] >= 0) {
                index--;
                continue;
            }
            for (int i = 0; i < (-colors[index]); i++) {
                //bug here: since fill_id is updated, don't need to use fill_id - i anymore
                colors[fill_id] = index + 1;
                fill_id--;
            }
            index--;
        }
        
    }

};

No comments:

Post a Comment