Queue Reconstruction by Height-面试题

题目内容

  • 按高度重构队列
  • 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.
  • 将一个被打乱的有顺序的序列重新排序,这个序列中的每个元素由一队整数h,k构成,h表示身高高度,k表示排在该元素前面的h不小于该h的元素个数。
  • 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大的元素会对后面的h小的元素有影响,所以应该按照h从大到小进行排序,其中h相同的,则按照k的大小,从小到大排序。
  • 然后使用从第二个元素开始进行插入排序,根据k的大小插入到适当的位置。

Java代码

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        if(people == null || people.length == 0 || people[0].length == 0) return new int[0][0];
        Arrays.sort(people, new Comparator<int[]>() {//使用Comparator构造体排序
            public int compare(int[] a, int[] b) {//自定义compare
                if(a[0] == b[0]) return a[1] - b[1];//h相同时,k从小到大排序
                return b[0] - a[0];//h从大到小排序
            }
        });
        List<int[]> res = new ArrayList<>();//新建一个空列表
        for(int[] p:people){//遍历已经排好序的people序列
            res.add(p[1],p);//因为h是从大到小的,所以k的大小即为所在位置的下标
        }
        return res.toArray(new int[people.length][]);//toArray将列表内容转化为数组
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值