zoukankan      html  css  js  c++  java
  • 根据身高重建队列

    根据身高重建队列

    题目:
    假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(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;
            }
        }
    }
    
  • 相关阅读:
    模拟Struts2框架Action的实现
    Servlet中表单的重复提交
    php回调函数设计
    vagrant+xdebug
    css之vw布局
    css之rem布局
    微信jssdk支付坑
    webpack中添加px2rem-loader
    phpstorm+xdebug手机app调试
    mysql产生死锁
  • 原文地址:https://www.cnblogs.com/katoMegumi/p/13983878.html
Copyright © 2011-2022 走看看