LintCode:1252. Queue Reconstruction by Height

描述

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.

简而言之就是对其再次排序

dalao思路:首先对数组进行排序,因为对于高的人来说,它前面的人少一点,所以排序的标准是当高度相同时,k多的排后面,当高度不相同时,h高的排前面。采取贪心策略就是:遍历时如果k等于数组大小,那说明是最后一位,否则,按照k直接插入相应的位置,即按照前面有多少人,就把你安排在什么位置,又因为高的排在前面,所以不用担心多余的问题

public int[][] reconstructQueue(int[][] people) {
        // write your code here
        Comparator<int[]> comparator=new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
               return o1[0]==o2[0]?o1[1]-o2[1]:o2[0]-o1[0];
                
            }
        };
        Arrays.sort(people,comparator);
        List<int[]> list=new ArrayList<>();
        for (int[] p:people){
            if(p[1]==list.size()){
                list.add(p);
            }
            else{
                list.add(p[1],p);
            }
        }
        int[][] res=new int[people.length][2];
        for (int i=0;i<list.size();i++){
            res[i][0]=list.get(i)[0];
            res[i][1]=list.get(i)[1];
        }
        return res;// write your code here

        
    }

summary:一开始自己越做越复杂,就是没有分析好问题,排序的顺序错误,当发现自己的解决办法越来越复杂,赶紧回头是岸,好好分析!

按要求排序的贪心策略,在什么位置就放在什么位置上

猜你喜欢

转载自blog.csdn.net/qq_38702697/article/details/82762042