leetcode:(406)Queue Reconstruction by Height(java)
阿新 • • 發佈:2018-12-02
題目:
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
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)的形式,h代表陣列值的大小,k代表前面有幾個大於或者等於該陣列值的個數。
解題思路:
首先將陣列按照h降序 ,k升序進行排序。即:先比較h值的大小(按照h降序排序),如果h值相同,比較k值(按照k值升序進行排序),然後從頭向尾遍歷陣列串,將每個陣列放在佇列k的位置。具體程式碼及思路如下:
package Leetcode_Github; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GreedyThought_ReconstructQueue_406_1108 { public int[][] reconstructQueue(int[][] people){ if (people == null || people.length == 0 || people[0].length == 0) { return new int[0][0]; } //按照身高降序,K值升序進行排序 Arrays.sort(people, (m, n) -> (m[0] == n[0] ? m[1] - n[1] : n[0] - m[0])); //將people中的每個陣列放到佇列peo[1]處 List<int[]> queue = new ArrayList<>(); for (int[] peo : people) { queue.add(peo[1], peo); } //將佇列轉換成陣列,返回 return queue.toArray(new int[queue.size()][]); } }