根据身高重建队列

根据身高重建队列

题目:
假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(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]]

解题思路:先将数组按照h进行降序排序,当h相等时按照k进行升序排序,之后依次按照元素的k进行插入即可

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, (a, b) -> {
            if(a[0] == b[0]) {
                return a[1] - b[1];
            }
            //降序排序
            return b[0] - a[0];
        });
        
        for(int i = 0; i < people.length; i++) {
            insert(people, i, people[i][1]);
        }
        
        return people;
    }
    
    private void insert(int[][] nums, int cur, int idx) {
        for(int i = cur; i > 0 && i > idx; i--) {
            int t[] = nums[i - 1];
            nums[i - 1] = nums[i];
            nums[i] = t;
        }
    }
}
原文地址:https://www.cnblogs.com/katoMegumi/p/13983878.html