leetcode刷题记录 406.根据身高重建队列
思路
先对队列按身高降序,按k升序排列,然后便利队列把k当作下标插入即可。
代码
/**
* 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 *x=*(int**)a,*y=*(int**)b;
return x[0]==y[0]?x[1]-y[1]:y[0]-x[0];
}
int** reconstructQueue(int** people, int peopleSize, int* peopleColSize, int* returnSize, int** returnColumnSizes){
//将队列按照身高从高到低,k从低到高的顺序排列
qsort(people,peopleSize,sizeof(int*),cmp);
int**ans =(int **)malloc(sizeof(int*)*peopleSize);
*returnSize=0;
*returnColumnSizes=(int*)malloc(sizeof(int)*peopleSize);
for(int i=0;i<peopleSize;i++) (*returnColumnSizes)[i]=2;
for(int i=0;i<peopleSize;i++)
{
int* person=people[i];
(*returnSize)++;
for(int j=(*returnSize)-1;j>person[1];j--) ans[j]=ans[j-1];
int *tmp=(int*)malloc(sizeof(int)*2);
tmp[0]=person[0],tmp[1]=person[1];
ans[person[1]]=tmp;
}
return ans;
}