Queue Reconstruction by Height解题

2017-09-07  本文已影响19人  黑山老水

Description:

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]]

Link:

https://leetcode.com/problems/queue-reconstruction-by-height/description/

解题方法:

矮个子对于高个子在这道题中并没有什么意义,所以我们先处理最高的,然后矮个子可以根据第二个值往其中插入,从而不会影响高个子。对于相同高的人,我们优先处理第二个值小的,因为相同高度的人可以互相影响。

Time Complexity:

O(nlogn)

完整代码:

vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) 
    {
        sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b) {
            if(a.first > b.first)
                return true;
            if(a.first == b.first)
                return a.second < b.second;
            return false;
        });
        vector<pair<int, int>> result;
        for(auto a: people)
            result.insert(result.begin() + a.second, a);
        return result;
    }
上一篇 下一篇

猜你喜欢

热点阅读