LeetCode Queue Reconstruction by Height

LeetCode Queue Reconstruction by Height

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

本题给了一个存储pair的数组,每个pair是一个(h,k)对,表示身高为h的人,其前面有k个身高大于等于h的人。现在要对这个数组重新排序,使得所有pair都满足其自己的(h,k)约束。

网上有一种很巧妙的方法,先对数组排序,排序规则是h大的在前,如果h相等,则k小的在前。然后新建一个数组,把每个pair插入到下标k的位置。

我们来举个例子,比如样例数据,先按上述规则排序之后变成了:

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

上述排序规则基于这样一个事实:h越小的,其前面比h大的数越多,越有可能满足其k约束;h相同时,肯定是k小的排前面,因为相同的h对k是有贡献的。

然后新建一个空的数组,不断把上述排好序的元素插入空数组中。

  1. [7,0]插入第0个位置,数组为[7,0]
  2. [7,1]插入第1个位置,数组为[7,0], [7,1]
  3. [6,1]插入第1个位置,数组为[7,0], [6,1], [7,1]
  4. [5,0]插入第0个位置,数组为[5,0], [7,0], [6,1], [7,1]
  5. [5,2]插入第2个位置,数组为[5,0], [7,0], [5,2], [6,1], [7,1]
  6. [4,4]插入第4个位置,数组为[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]

完整代码如下:

bool comp(const pair<int, int>& p1, const pair<int, int>& p2) {
	return p1.first > p2.first || (p1.first == p2.first&&p1.second < p2.second);
}

class Solution {
public:
	vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
		sort(people.begin(), people.end(), comp);
		vector<pair<int, int>> ans;
		for (int i = 0; i < people.size(); ++i) {
			ans.insert(ans.begin() + people[i].second, people[i]);
		}
		return ans;
	}
};

本代码提交AC,用时49MS。

Leave a Reply

Your email address will not be published. Required fields are marked *