leetcode 406. Queue Reconstruction by Height

来源:互联网 发布:数据库课程视频 编辑:程序博客网 时间:2024/05/17 00:09

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]]
我的思路是先将所有人按身高从高到矮排序,身高一样的话,后面的数小的排前面。然后遍历,当遍历到一个元素i时,再从0开始找i之前有哪些元素比i的身高大,当已找出了i[1]个元素时,将i插进那个元素后面。

public class Queue_Reconstruction_by_Height_406 {public int[][] daoxu(int[][] people){for(int i=0;i<people.length;i++){for(int j=0;j<people.length-1-i;j++){if(people[j][0]<people[j+1][0]||(people[j][0]==people[j+1][0]&&people[j][1]>people[j+1][1])){int[] temp=people[j];people[j]=people[j+1];people[j+1]=temp;}}}return people;}public int[][] reconstructQueue(int[][] people) {people=daoxu(people);for(int i=1;i<people.length;i++){int count=0;for (int j = 0; j < i; j++) {if(count==people[i][1]){int[] temp=people[i];for(int k=i;k>j;k--){people[k]=people[k-1];}people[j]=temp;break;}if (people[j][0] >= people[i][0]) {count++;}}}return people;}public static void main(String[] args) {// TODO Auto-generated method stubQueue_Reconstruction_by_Height_406 q=new Queue_Reconstruction_by_Height_406();int[][] a=new int[][]{{9,0},{7,0},{1,9},{3,0},{2,7},{5,3},{6,0},{3,4},{6,2},{5,2}};int[][] b=q.reconstructQueue(a);for(int i=0;i<b.length;i++){System.out.print("("+b[i][0]+","+b[i][1]+") ");}}}

发现大神的思路跟我差不多,但是后面是采用的链表插入的方式,比我这个更快。而且i[1]等于多少,就把它填入第i[1]个元素,这个很机智,因为在i前面的元素都是身高比i高的,就算i插在它们前面,对它们的[1]值不会有影响。

public class Solution {    public int[][] reconstructQueue(int[][] people) {        //pick up the tallest guy first        //when insert the next tall guy, just need to insert him into kth position        //repeat until all people are inserted into list        Arrays.sort(people,new Comparator<int[]>(){           @Override           public int compare(int[] o1, int[] o2){               return o1[0]!=o2[0]?o2[0]-o1[0]:o1[1]-o2[1];           }        });        List<int[]> res = new LinkedList<>();        for(int[] cur : people){            res.add(cur[1],cur);               }        return res.toArray(new int[people.length][]);    }}

We first sort the people to make them stand from the highest to shortest. For people with same height, sort them according to the count of people before them from small to big.
Then, we use the way similar to insert sorting to reorder the people. For a given person to insert, all the people already sorted are higher, so we just insert him in the "right" place to make the people before him as his "count" indicates. Since he is shorter than all the people in the sorted list, the "count" of the "existing" people does not be broken by the insertion.


0 0
原创粉丝点击