leetcode 406. Queue Reconstruction by Height (greedy)

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

数组中的两个数一组用pair表示
题目中的pair[0]表示身高,pair[1]表示这个人前面还有几个人比他高,要求输出的排序是
看pair[1], 比如[4,4],pair[1]=4表示前面有4个人比他高,那么它前面必须得有4个元素的pair[0]>=4

思路:
greedy

就说题中的input,[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
遇到[4,4]的时候知道前面还有4个元素要>=pair[0]=4,但是从左到右遍历的时候只看到一个7比4大,这时候就需要在后面再找出3个比4大的元素,同时还要照顾到pair[1]
这时候需要同时考虑两个因素,一个身高,一个是位置

这时候应该降维,固定一个因素,只考虑剩下的一个因素
固定位置显然不行,因为位置不是绝对位置,它是由前面人的身高决定的,所以要固定身高这个因素

题中说了前面有几个人比自己“高”,所以高的排在前面,按从高到低排序,这样有一个好处,
因为是从高到低
7, 7, 6, 5, 5, 4
如果要求6前面有1个人比它高,4前面有两个人比它高
从左到右遍历的时候把6直接移到第二位
7, 6, 7, 5, 5, 4
4前面有两个人比它高:
因为排好序的结果是4前面所有元素都比4大,所以前面的移动不影响比4大的元素个数,同时4不管移动到前面哪个位置,都能保证那个位置之前的元素是比4大的
所以要求4前面有2个人比它高,那么可以直接把4移到第3个位置上,而不需要考虑前面2个是不是会比4小

pair[1]相同的情形:
比如[5, 0], [7, 0]
还是按身高大的排前面,因为更便于后面的元素不需要考虑身高而直接按位置移动

pair[0]相同的情形:
[7,0], [7, 1]
pair[0]小的排在前面,因为不需要再额外移动了

**注意java的Comparator的compare方法,参数一定要是Object的,用的时候需要down cast
还有就是asList()和toArray()

    public int[][] reconstructQueue(int[][] people) {
        if (people == null || people.length <= 1) {
            return people;
        }
        
        Arrays.sort(people, new Comparator(){
           public int compare(Object p1, Object p2) {
               if (((int[])p1)[0] == ((int[])p2)[0]) {
                   return (((int[])p1)[1] - ((int[])p2)[1]);
               } else {
                   return (((int[])p2)[0] - ((int[])p1)[0]);
               }
           } 
        });
        
        ArrayList<int[]> list = new ArrayList<>();
        
        for (int[] p : people) {
            list.add(p[1], p);
        }
        
        return list.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、付费专栏及课程。

余额充值