前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode406. Queue Reconstruction by Height

leetcode406. Queue Reconstruction by Height

作者头像
眯眯眼的猫头鹰
发布2019-03-20 10:56:37
5030
发布2019-03-20 10:56:37
举报

题目要求

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

假设有一组人站成一堆,每个人都记录下了自己的高度,以及在自己前面有多少个不比自己矮的人。现在请按照这个信息将这组人放在队列中正确的位置上并返回。

思路和代码

刚开始我试图用分治法来解决,因为每一个小队列中,高度最矮且站在自己前面的高个最少的人一定位于k位置上。但是这样解决其实复杂化了问题。

可以从另一个角度来想,首先我们知道,同等高度的人,其相对位置一定是根据k的值从小到大排列的。即k越大,则该同等高度的人一定在另一个同等高度的人后面。如果我们从高到低将人们插入队列中,可以知道,k的值就该人在当前队列中的下标,如:

[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
首先将其按照h和k排序,得出结果:
[[7,0],[7,1],[6,1],[5,1],[5,0],[5,2],[4,4]]

当前结果队列为[]
将[7,0]插入下标为0的位置上 结果队列[[7,0]]
将[7,1]插入下标为1的位置上 结果队列[[7,0],[7,1]]
将[6,1]插入下标为1的位置上 结果队列[[7,0],[6,1],[7,1]]
按照这种规则,依次按照顺序和k的值将数据插入结果队列中

代码如下:

    public int[][] reconstructQueue(int[][] people) {
        int[][] result = new int[people.length][2];
        Arrays.sort(people, new Comparator<int[]>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0];
            }
            
        });
        for(int i = 0 ; i<people.length ; i++) {
            int pos = people[i][1];
            for (int j = i; j > pos; j--) {
                result[j] = result[j - 1];
            }    
            result[pos] = people[i];
        }
        return result;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档