LeetCode 406. Queue Reconstruction by Height
原題鏈接在這里:https://leetcode.com/problems/queue-reconstruction-by-height/description/
題目:
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]]題解:
先把最高的人挑出來,然后按照k把他們插入到ArrayList<int []> resList中. 然后再插第二高的,以此類推.
Time Complexity: O(nlogn). n = people.length. sort用時O(nlogn), 插入時因?yàn)槭褂肁rrayList, 可以忽略resize的用時, 所以插入共用時O(n).
Space: O(n).
AC Java:
1 class Solution { 2 public int[][] reconstructQueue(int[][] people) { 3 if(people == null || people.length == 0|| people[0].length != 2){ 4 return people; 5 } 6 7 Arrays.sort(people, new Comparator<int []>(){ 8 public int compare(int [] a, int [] b){ 9 if(a[0] == b[0]){ 10 return a[1]-b[1]; 11 } 12 return b[0]-a[0]; 13 } 14 }); 15 16 ArrayList<int []> resList = new ArrayList<int []>(); 17 for(int [] item : people){ 18 resList.add(item[1], item); 19 } 20 21 return resList.toArray(new int[people.length][2]); 22 } 23 }跟上315. Count of Smaller Numbers After Self.?
轉(zhuǎn)載于:https://www.cnblogs.com/Dylan-Java-NYC/p/7568309.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode 406. Queue Reconstruction by Height的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Lucene第一讲——概述与入门
- 下一篇: 扫描线三巨头 hdu1928hdu 12