LintCode:1252. Queue Reconstruction by Height
阿新 • • 發佈:2018-12-10
描述
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:一開始自己越做越複雜,就是沒有分析好問題,排序的順序錯誤,當發現自己的解決辦法越來越複雜,趕緊回頭是岸,好好分析!
按要求排序的貪心策略,在什麼位置就放在什麼位置上