26.leetCode406:Queue Reconstruction by Height

来源:互联网 发布:java 同步互斥 编辑:程序博客网 时间:2024/05/16 11:34

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

题意:给定一个随机排列的队列,里面的人有两个属性h、k:身高和比他高的人数。要求将队列重新排序,使得所有人的k都是满足要求的。

思路:先排序后插入的一个过程。首先按身高从大到小对所有人进行排序,对于身高一样的人,按k从小到大进行排序。然后,从数组people第一个元素开始,放入到数组result中,放入的位置就是离result开始位置偏移了元素第二个数字后的位置。
借用一下别人写的过程:
*一、排序*
排序前:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
排序后:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]

*二、插入*
1.
people: [7,0]
插入到离开始位置偏移了0个距离的位置。
result: [[7,0]]
2.
people: [7,1]
插入到离开始位置偏移了1个距离的位置,即插入到[7,0]的后面。
result: [[7,0], [7,1]]
3.
people: [6,1]
插入到离开始位置偏移了1个距离的位置,即插入到[7,0]的后面。
result: [[7,0], [6,1], [7,1]]
4.
people: [5,0]
插入到离开始位置偏移了0个距离的位置,即插入到[7,0]的前面。
result: [[5,0], [7,0], [6,1], [7,1]]
5.
people: [5,2]
插入到离开始位置偏移了2个距离的位置,即插入到[7,0]的后面。
result: [[5,0], [7,0], [5,2], [6,1], [7,1]]
6.
people: [4,4]
插入到离开始位置偏移了4个距离的位置,即插入到[6,1]的后面。
result: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

代码

class Solution {    public int[][] reconstructQueue(int[][] people) {        Arrays.sort(people,new Comparator<int[]>(){            public int compare(int[] a, int[] b){                if(a[0] != b[0]) return b[0]-a[0];                return a[1] - b[1];            }        });        List<int[]> result = new ArrayList<>();        for(int[] p: people){            result.add(p[1],p);        }        return result.toArray(new int[people.length][]);    }}


1.使用Comparator接口:编写多个排序方式类实现Comparator接口,并重写新Comparator接口中的compare()方法。升序是前者减去后者,降序是后者减去前者。
2.list又一个add方法:add(index,element)就是把element插入到list中第index的位置

原创粉丝点击