406. Queue Reconstruction by Height

Description

height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]


简要题解:

这道题总的解题方向是采用贪心算法。具体做法是不断循坏people向量的各个元素直到该向量为空。每次从people中取出一个,在result中找到一个刚好可以放的位置放入。如果找不到可以放的位置放就跳过这个元素,等待下一轮循坏再继续找位置。

但是这样做会有点问题,我们必须保证后放入result的元素不会影响到先放入result的元素。因此,需要对people中的每个人按身高大小由高到底排序。(身高较低的不管怎么放都不会影响到身高较高的人)。还要注意到,对于两个身高相同的情况,k值小的应该放在前面。因为,身高相同的两个人,在result中k值小的一定是放在k值较大的那个人的前面。也就是说,在身高相同的情况下,k值较小的可能会影响k值较大的那个人。排完序后,就采用前面说的那种贪心算法来构造result就可得到正确的结果。


代码:

class Solution {
public:
    static vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
        vector<pair<int, int> > result;

        for (int i = 0; i < people.size(); i++)
            for (int j = i + 1; j < people.size(); j++)
                if ((people[i].first < people[j].first) ||
                    (people[i].first == people[j].first && people[i].second > people[j].second)) {
                    pair<int, int> temp = people[i];
                    people[i] = people[j];
                    people[j] = temp;
                }

        while (!people.empty()) {
            vector<pair<int, int> >::iterator iter1, iter2;
            for (iter1 = people.begin(); iter1 != people.end(); iter1++) {
                int count = 0;
                int flag = false;
                for (iter2 = result.begin(); iter2 != result.end(); iter2++) {
                    if (count == iter1->second + 1) {
                        iter2--;
                        result.insert(iter2, *iter1);
                        people.erase(iter1);
                        flag = true;
                        break;
                    }
                    if (iter2->first >= iter1->first)
                        count++;
                }

                if (!flag && count == iter1->second + 1) {
                    pair<int, int> temp = result[result.size()-1];
                    result[result.size()-1] = *iter1;
                    result.push_back(temp);
                    people.erase(iter1);
                    flag = true;
                }

                if (!flag && count == iter1->second) {
                    result.push_back(*iter1);
                    people.erase(iter1);
                    flag = true;
                }

                if (flag)
                    break;
            }
        }

        return result;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章