leetcode题目:406. 根据身高重建队列(贪心算法)

本文探讨了一种二维数组的排序问题,其中每个元素包含两个维度h和k。关键在于按照k从高到低排序,然后根据h重新构建队列,确保每个人都在比自己身高矮的人前面。通过Python和Java代码示例展示了具体的解决方案,强调了解题思路对于解决类似问题的重要性。
摘要由CSDN通过智能技术生成

1. 题目分析

在这里插入图片描述
本题有两个维度,h和k,看到这种题目一定要想如何确定一个维度,然后在按照另一个维度重新排列。
我们不能h和k一起考虑,这样会顾此失彼,我们必须先确定一个维度,h或者k。
如果按照k来从小到大排序,排完之后,会发现k的排列并不符合条件,身高也不符合条件,两个维度哪一个都没确定下来。

  • 思路:
    按照k从高到底排序,这样前面的k一定高于后面的,在重新创建一个队列,遍历排序后的数组,再重新插入就行了。

  • 我们拿第一个样例来说
    排序完的people:
    [[7,0], [7,1], [6,1], [5,0], [5,2],[4,4]]
    插入的过程:
    插入[7,0]:[[7,0]]
    插入[7,1]:[[7,0],[7,1]]
    插入[6,1]:[[7,0],[6,1],[7,1]]
    插入[5,0]:[[5,0],[7,0],[6,1],[7,1]]
    插入[5,2]:[[5,0],[7,0],[5,2],[6,1],[7,1]]
    插入[4,4]:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]

那么在以后遇见类似的题型,是不是就能考虑到先确定其中一个维度的思想呢?

2. 代码实现

2.1. Python代码

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        people = sorted(people,reverse=True,key=lambda x: (x[0], -x[1]))
        res = []
        for i in range(len(people)):
            if people[i][1] < i:
                res.insert(people[i][1],people[i])
            else:
                res.append(people[i])
        return res

2.2. Java代码

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        int[][] res = new int[people.length][2];
        people = sort(people);
        res[0] = people[0];
        for(int i = 1;i < people.length;i++){
            if(i > people[i][1]){
                for(int j = i;j > people[i][1];j--){
                    res[j] = res[j - 1];
                }
                res[people[i][1]] = people[i];
            }else{
                res[i] = people[i];
            }
        }
        return res;
    }

    public int[][] sort(int[][] people){
        for(int i = 0;i < people.length;i++){
            int max = i;
            for(int j = i + 1;j < people.length;j++){
                if(people[j][0] > people[max][0]){
                    max = j;
                }
                if(people[j][0] == people[max][0] && people[j][1] < people[max][1]){
                    max = j;
                }
            }
            if(max != i){
                int[] t = people[max];
                people[max] = people[i];
                people[i] = t;
            }
        }
        return people;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若能绽放光丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值