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]]

思路1:每次挑选k为0的,且为最小的数组。即挑选[5,0],随后对所有数值进行更新,如果挑选数组h的值比当前值大,则当前数组的k--。repeat直至队列为空。O(n^2)
public int[][] reconstructQueue(int[][] people) {
        int m = people.length;
        int[][] temp = new int[m][2];
        for(int i = 0;i<m;i++){temp[i][0] = people[i][0];temp[i][1] = people[i][1];}
        int[][] result = new int[m][2];
        for(int i = 0;i<m;i++)
        {
            int min = Integer.MAX_VALUE;
            int k = 0;
            for(int j=0;j<m;j++)
            {
                if(people[j][1] == 0 && people[j][0] < min)
                {
                    min = people[j][0];
                    k = j;
                }
            }
            for(int j=0;j<m;j++)
            {
                if(people[j][0] <= people[k][0])
                {
                    people[j][1]--;
                }
            }
            result[i] = temp[k];
        }

        return result;

    }
 思路2:
 对队列进行排序,排序方式是按h值从大到小排序,如果h相同则按k值从小到大排序。排好序后,依次将队列中数组插入到k位置的队列M中,这样既不会影响其在M后面的数组,自身也会满足条件。
 public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                // TODO Auto-generated method stub
                return o1[0] != o2[0] ? o2[0] - o1[0] : o1[1] - o2[1];
            }
        });
        for(int i = 0;i<people.length;i++)
        {
            System.out.println(people[i][0]+","+people[i][1]);
        }
        List<int[]> re  = new ArrayList<int[]>();
        for(int[] cur : people)
        {
            re.add(cur[1], cur);
        }

        return re.toArray(new int[people.length][2]);

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值