【排序29:根据身高重建队列】

本文介绍了一种解决队列重建问题的方法,通过自定义排序规则对人员数组进行排序,并逐一插入形成最终队列。适用于算法面试及日常编程挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 【解题思路】

        先对people进行排序,排序按照第一个数字的大小,从小到大排序,如果第一个数字相同,则按照第二个数字从小到大的顺序排序。

        对于排好序的people[ ][ ]依次取出每一个数组,对于数组people[i],他前面有people[i][1]个比他个子高的人(他的身高为people[i][0]),所以需要从头数出people[i][1] - Num(比他高的人数)个空位,然后将他插入。

        需要注意的是,有一个测试样例中,有身高为0的数据。

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, new Comparator<int[]>(){
            public int compare(int[] a, int[] b){
                if(a[0] == b[0]) return a[1]-b[1];
                else return a[0]-b[0];
            }
        });
        
        int n = people.length;
        int[][] queue = new int[n][2]; 
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < 2; j++)
            {
                queue[i][j] = -1;
            }
        }
        for(int i = 0; i < n; i++)
        {
            int cnt = 0;
            int j = 0;
            while(cnt < people[i][1])
            {
                if(queue[j][0] == -1 && queue[j][1] == -1) cnt++;
                else if(queue[j][0] >= people[i][0]) cnt++;
                j++;
            } 
            if(queue[j][0] == -1 && queue[j][1] == -1)
            {
                queue[j][0] = people[i][0];
                queue[j][1] = people[i][1];
            }
            else{
                int k = j+1;
                while(!(queue[k][0] == -1 && queue[k][1] == -1))
                {
                    k++;
                }
                queue[k][0] = people[i][0];
                queue[k][1] = people[i][1];
            }
        }

        return queue;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值