leetcode problem 406. Queue Reconstruction by Height

Problem

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the 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]]

Solution

一开始我是想用快排来做,后来发现时间超了。
原因很简单,快排其实更适用于两两可比的情况,而这种情况显然不满足。

题目中k is the number of people in front of this person who have a height greater than or equal to h 其实已经告诉我们用什么排序最合适了: 插入排序 。 同样是需要数当前元素需要排在哪个位置。

所以最后的代码应该为:

typedef pair<int, int> P; 

struct cmp
{
    bool operator()(const P p1, const P p2)
    {
        if (p1.first == p2.first) return p1.second > p2.second;
        else return p1.first < p2.first;
    }
};

class Solution {
public:
    cmp tem_cmp; // without this, it will compile error, as the following usage of priority_queue
    vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
        if (people.size() == 0 ) return people;
        priority_queue<P, vector<P>, cmp> que;
        for (int i = 0 ; i < people.size() ; ++i) que.push(people[i]);
    	std::vector<pair<int,int> > res;
    	pair<int,int> cur;
        while(!que.empty()){
            cur = que.top();
            que.pop();
            res.insert(res.begin() + cur.second, cur);
        }
        return res;
    }
};

20190329

tbc.

猜你喜欢

转载自blog.csdn.net/Aries_M/article/details/88888724