406. Queue Reconstruction by Height

2018/07/01 leetcode 共 965 字,约 3 分钟

title

problem link

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

题目描述:一个学生用两个分量 (h, k) 描述,h 表示身高,k 表示排在前面的有 k 个学生的身高比他高或者和他一样高。

为了在每次插入操作时不影响后续的操作,身高较高的学生应该先做插入操作,否则身高较小的学生原先正确插入第 k 个位置可能会变成第 k+1 个位置。

身高降序、k 值升序,然后按排好序的顺序插入队列的第 k 个位置中。

class Solution {
public:
	bool static cmp(pair<int, int> a, pair<int, int> b) {
		return  a.first > b.first || a.first == b.first&&a.second < b.second;
	}
	vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
		sort(people.begin(), people.end(), cmp);
		vector<pair<int, int>> res;
		for (auto &it : people) {
			res.insert(res.begin()+it.second, it);
		}
		return res;
	}
};

Search

    Table of Contents