假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:
总人数少于1100人。
示例
输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height
思路:
先对输入的数据进行简单的整理,对所有的整数对进行比较
最终的排序肯定是先给身高高的人排,再给身高低的(k是该h前面的比他高的人的个数嘛,插入小矮个对他不影响)
所以先简单处理一下,对比整数对的左边和右边,左边不同的就降序排,相同的就看右边,按右边升序排
能得到结果 70 71 61 50 52 44
再从前往后,一个一个元素插入到它该去的位置上去(逐个插入到第k个位置)
// [7,0], [7,1], [6,1], [5,0], [5,2], [4,4]
// [7,0]
// [7,0], [7,1]
// [7,0], [6,1], [7,1]
// [5,0], [7,0], [6,1], [7,1]
// [5,0], [7,0], [5,2], [6,1], [7,1]
// [5,0], [7,0], [5,2], [6,1], [4,4], [7,1]
用冒泡排序
class Solution {public int[][] reconstructQueue(int[][] people) {sort(people);List<int[]> queue = new ArrayList<>();for (int[] p : people) {queue.add(p[1], p); //参数1表示第k个位置,参数2表示要插入的人(h,k)}return queue.toArray(new int[queue.size()][]);}public void sort(int[][] arr) {//如果左边的不同就降序排列,如果左边的相同就根据右边升序for (int i = 1; i < arr.length; i++) {for (int j = i; j > 0; j--) {if ((arr[j][0] == arr[j - 1][0] && arr[j][1] < arr[j - 1][1])|| arr[j][0] > arr[j - 1][0]) {int temp = arr[j - 1][0];arr[j - 1][0] = arr[j][0];arr[j][0] = temp;int temp1 = arr[j - 1][1];arr[j - 1][1] = arr[j][1];arr[j][1] = temp1;}}}}}
用比较器
public int[][] reconstructQueue(int[][] people) {if (people == null || people.length == 0 || people[0].length == 0) {return new int[0][0];}Arrays.sort(people, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));List<int[]> queue = new ArrayList<>();for (int[] p : people) {queue.add(p[1], p);}return queue.toArray(new int[queue.size()][]);}
