根据身高重建序列

代码是好想,但思路不好想,如果用C语言的话,那你的指针还得用的熟练

假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:先排序再插入
* 1.排序规则:按照先H高度降序,K个数升序排序
* 2.遍历排序后的数组,根据K插入到K的位置上
*
* 核心思想:高个子先站好位,矮个子插入到K位置上,前面肯定有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 comfunc(const void *p1,const void *p2)//此函数用于比较身高和次数
{
    const int **p11=(const int**)p1;
    const int **p22=(const int**)p2;
    if(p11[0][0]!=p22[0][0])
    {
        return p22[0][0]-p11[0][0];
    }
    else{
        return p11[0][1]-p22[0][1];
    }
}
int** reconstructQueue(int** people, int peopleSize, int* peopleColSize, int* returnSize, int** returnColumnSizes){
    int **ret=(int **)malloc(sizeof(int*)*peopleSize);//返回指针 ,指向指针数组的指针,数组里面是指针,每个指针又指向一个含有两个元素的一维数组
    for(int i=0;i<peopleSize;i++)
    {
        ret[i]=(int *)malloc(sizeof(int)*2);//每个指针指向的数组的长度
    }
    *returnSize=peopleSize;//返回的人数,没个屁用,但题目要求
    *returnColumnSizes=(int*)malloc(sizeof(int)*peopleSize);
    for(int i=0;i<peopleSize;i++)
    {
        (*returnColumnSizes)[i]=2;
    }//赋值,明知道是二,题目非要输入
    qsort(people,peopleSize,sizeof(int*),comfunc);
    //快排
    for(int i=0;i<peopleSize;i++)
    {
        for(int j=i;j>people[i][1];j--)
        {
            ret[j]=ret[j-1];//数据后移
        }
        ret[people[i][1]]=people[i];
    }
    return ret;
}

执行结果: 通过 显示详情 执行用时 : 52 ms , 在所有 c 提交中击败了
99.14% 的用户 内存消耗 :
12.2 MB , 在所有 c 提交中击败了
100.00% 的用户

发布了37 篇原创文章 · 获赞 1 · 访问量 662

猜你喜欢

转载自blog.csdn.net/zzuzhaohp/article/details/103353630