406. Queue Reconstruction by Height

题目大意:有一队人,每个人由一个(h,k)表示,h表示高度,k表示前面高于或等于自己的人个人。给一个打乱了的队列,求出正确的序列。

思路:

1.每次从队列中找出k=0,再在其中选出h最小的,加入到res队列中;然后对剩余队列做相应的处理;再循环,即可求出全部队列,类似于递归。176ms

2.先把队列按h从大到小,h相同则k从小到大的顺序排列,然后依次将每个人插入到res队列。83ms

CODE:

1.

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** reconstructQueue(int** people, int peopleRowSize, int peopleColSize, int** columnSizes, int* returnSize) {
    if(peopleRowSize<1||peopleColSize<1) {columnSizes=NULL;*returnSize=0;return NULL;}
    *returnSize=peopleRowSize;
    int i,j,k,h,**res;
    *columnSizes=(int*)malloc(sizeof(int)*peopleRowSize);
    res=malloc(sizeof(int*)*peopleRowSize);
    for(i=0;i=res[i][0])res[i][1]++;
        }
        people[k][1]=-1;
        for(j=0;j
2.
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** reconstructQueue(int** people, int peopleRowSize, int peopleColSize, int** columnSizes, int* returnSize) {
    if(peopleRowSize<1||peopleColSize<1) {columnSizes=NULL;*returnSize=0;return NULL;}
    *returnSize=peopleRowSize;
    int i,j,k,**res;
    *columnSizes=(int*)malloc(sizeof(int)*peopleRowSize);
    res=malloc(sizeof(int*)*peopleRowSize);
    for(i=0;ipeople[j][1]){
                k=people[i][1],people[i][1]=people[j][1],people[j][1]=k;
            }
        }
    }
    //以上为排序
    res[0][0]=people[0][0];res[0][1]=people[0][1];
    for(i=1;ij){
            if(res[k][0]>=people[i][0]) j++;
            k++;
        }
        for(j=i;j>k;j--){
            res[j][0]=res[j-1][0];
            res[j][1]=res[j-1][1];
        }
        res[k][0]=people[i][0];
        res[k][1]=people[i][1];
    }
    return res;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值