leetcode_middle_2_406. Queue Reconstruction by Height
来源:互联网 发布:iphone7数据恢复失败 编辑:程序博客网 时间:2024/06/18 14:42
题意:
一个二维数组,表示一列人,每个人用一个[h, k]数组描述,h表示这个人的身高,k表示队列前面身高大于等于这个人的数目。
分析:
比如:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
无论是h还是k,都不能作为排序的依据,没什么规律可言。那么,这个排序事件最最核心的就是:前面比我还高的人数。要满足这个条件。
比如[6,1] 前面比它高的人数是1 ,就是7 (两个5相当于没有)
所以抽离出来:[7,0] [6,1] 是这样的。
我们发现[7,0]的0就表示前面有0个比他高的,所以在角标0,[6,1]的前面有1个比他高的所以在角标1.但是为什么最后变成了[5,0],[7,0],[5,2],[6,1]呢?因为[5,?]不影响[6,1]相对位置的正确性,所以使其角标不等于k.意思就是说,更矮的人,可能使更高的人的k从等于角标变成大于角标。变化之后是没什么规律的。但是变化之前k==角标。
所以我们抓住这个重点:当队列里的人的身高都大于等于自己的身高的时候,自己的k值就是角标。
所以我们要解题的关键就是:使一组身高[h,?]排入队列的时候,队列里只有比它高的或者一样高的。也就是说从高到低放入(插入)一个新队列。
public class Solution { public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, new Comparator<int[]>() { //排序的目的是为了先处理高的 public int compare(int[] a, int[] b) { if (b[0] == a[0]) //高度相等的时候,k小的在前面 return a[1] - b[1]; //否则ArrayList.add()可能越界 return b[0] - a[0]; } }); ArrayList<int[]> al = new ArrayList<>(); //因为要插入,所以使用动态数组 for (int i = 0; i < people.length; i++) al.add(people[i][1], new int[]{people[i][0], people[i][1]}); //根据k直接站到相应角标位 int i = 0; for (int[] a : al) { people[i][0] = a[0]; people[i][1] = a[1]; i++; } return people; }}
0 0
- leetcode_middle_2_406. Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- leetcode406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- angular源码解读:forEach方法遍历
- Linux下长时间ping网络加时间戳并记录到文本
- BZOJ3533: [Sdoi2014]向量集
- MAC上安装rocketmq磁盘空间不足的问题
- wikioi1004 四子连棋
- leetcode_middle_2_406. Queue Reconstruction by Height
- 欢迎使用CSDN-markdown编辑器
- 聚类算法
- webpack压缩react
- Leetcode-138. Copy List with Random Pointer
- 今年暑假不AC HDU - 2037
- Qt学习笔记-----Graphics_View_Framework
- 欢迎使用CSDN-markdown编辑器
- 抽象工厂模式