Queue Reconstruction by Height

本文介绍了一种用于根据人员的高度及前面特定条件人数来重构队列的算法。通过按高度降序排序并根据条件调整位置,最终得到符合要求的队列布局。

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

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.
Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

思路:
先按照高度从大到小排序,高度h相同的,将k比较小的放在前面。
排完序之后的结果为[7,0],[7,1][6,1][5,0][5,2][4,4]

接下来要调整整个队列,从第二个开始,
1)如[7,1] 允许比其大的一个数在其前面,那么[7,1]的位置可以不变
调整完后
[7,0],[7,1][6,1][5,0][5,2][4,4]

2)调整[6,1], 允许一个大于或者等于6的数在前面,那么就将[6,1]
插入到索引为1的地方
[7,0],[6,1][7,1][5,0][5,2][4,4]

3)调整[5,0],允许0个大于或者等于5的数在前面,将[5,0]插入在索引为0的地方
[5,0][7,0],[6,1][7,1][5,2][4,4]

4)调整[5,2],允许2个大于或者等于5的数在前面,将[5,2]插入在索引为2的地方
[5,0][7,0],[5,2][6,1][7,1][4,4]

5)调整[4,4],可允许4个大于或者等于4的数在前面,将[4,4]插入在索引为4的地方
[5,0][7,0],[5,2][6,1][4,4][7,1]

最后即为最后的结果。

总结:先按照高度从大到小的排序,就是保证在调整某个people的时候,前面的高度都是比自己高的,将自己插入到高度比自己高的人前面的时候,对前面的人也不会产生太大的影响,前面的人不会被自己挡住。

代码:

public class Solution {
    public int[][] reconstructQueue(int[][] people) {
         int m = people.length;
            if(m==0)
                return people;
            int n = people[0].length;
            if(n!=2) 
                return null;
            Arrays.sort(people,new Comparator<int[]>(){
              public  int compare(int[] obj1,int[] obj2)
                {
                    if(obj1[0]==obj2[0])
                    {
                        return obj1[1]-obj2[1];
                    }else
                    {
                        return obj2[0]-obj1[0];
                    }
                }

            });  
            for(int i=1;i<m;i++)
            {
                int temp0 = people[i][0];
                int temp1 = people[i][1];
                if(temp1==i) continue;
                int j=i;
                for(;j>temp1;j--)
                {
                    people[j][0]=people[j-1][0];
                    people[j][1]=people[j-1][1];
                }
                people[temp1][0]=temp0;
                people[temp1][1]=temp1;
            }
            return people;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值