假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:
总人数少于1100人。
示例
输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int cmp(const void* _a, const void* _b) {
int *a = *(int**)_a, *b = *(int**)_b;
return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0];
}
int** reconstructQueue(int** people, int peopleSize, int* peopleColSize, int* returnSize, int** returnColumnSizes) {
qsort(people, peopleSize, sizeof(int*), cmp);
int** res = malloc(sizeof(int*) * peopleSize);
*returnSize = peopleSize;
*returnColumnSizes = malloc(sizeof(int) * peopleSize);
memset(*returnColumnSizes, 0, sizeof(int) * peopleSize);
for (int i = 0; i < peopleSize; ++i) {
int spaces = people[i][1] + 1;
//printf("i:%d spaces:%d people[i][0]:%d\n", i, spaces, people[i][0]);
for (int j = 0; j < peopleSize; ++j) {
//printf(" #==#j:%d (*returnColumnSizes)[j]:%d spaces:%d\n", j, (*returnColumnSizes)[j], spaces);
if ((*returnColumnSizes)[j] == 0) {
spaces--;
if (!spaces) {
(*returnColumnSizes)[j] = 2;
res[j] = malloc(sizeof(int) * 2);
res[j][0] = people[i][0];
res[j][1] = people[i][1];
break;
}
}
}
}
return res;
}
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (x[0], -x[1]))
n = len(people)
res = [[] for _ in range(n)]
for person in people:
spaces = person[1] + 1
for i in range(n):
if not res[i]:
spaces -= 1
if spaces == 0:
res[i] = person;
break
return res