leetcode 406. Queue Reconstruction by Height(按身高重建队列)

You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.

Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).

Example 1:

Input: people = [[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]]
Explanation:
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.
Example 2:

Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]

people数组里面的每一组是[身高,前面比我高或者和我一样高的有几个人]
按“前面比我高的有几个人”给数组排个序

思路

首先明确一点,假设现在已经排好了序,前面比我高的有3个人,那么往前面加一个比我矮的是不会影响现在的顺序的。
但是前面加一个比我高的就会有影响,那前面比我高的就是4个人了。

所以,先把people按身高(people[i][0])降序排序,确保高的先排好,然后再把矮的加进去,就不会影响顺序。

people[i] = [hi, ki], ki表示前面有ki个人比当前第i个people高,
因为是按身高从高到低排的,那现有的前面的都是比当前people高的,所以直接把他insert到第ki个位置,
然后后面来的矮的insert到他前面也无所谓,不影响ki。
理解这点是关键。

那身高相同的两个人怎么排的,是先排前面的(ki较小的)还是后面的(ki较大的)?
试想,如果先排后面的,比如(5,4):身高为5的人,前面有4个比他高或者和他一样高的,
再来一个(5,2),要insert到第2个,在(5,4)的前面,那么好了,前面和他一样高的多了一个,(5,4)该变成(5,5)了,受到了影响。

所以,如果身高一样,先排ki较小的。

public int[][] reconstructQueue(int[][] people) {
    int n = people.length;
    Arrays.sort(people, (a, b)->(a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));
    List<int[]> res = new LinkedList<>();
    
    for(int[] tmp : people) {
        res.add(tmp[1], tmp);
    }
    return res.toArray(people);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值