刷题-Leetcode-406. 根据身高重建队列(贪心-两个维度权衡问题)

406. 根据身高重建队列

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

在这里插入图片描述在这里插入图片描述

题目分析

1.排序。
按照hi从大到小排列,hi相同则按照ki从小到大排列。
2.插入res中。
排好序的people依次插入到res中,因为是先插入hi大的,所以后序插入对前面已经插入的没有影响。
在这里插入图片描述

class Solution {
    
    
public:
    static bool cmp(vector<int> a, vector<int> b)
    {
    
    
        if(a[0] > b[0]){
    
    
            return true;
        }else if(a[0] == b[0]){
    
    
            return a[1] < b[1];
        }else{
    
    
            return false;
        }
    }
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) 
    {
    
    
        vector<vector<int>> res;
        sort(people.begin(), people.end(), cmp);
        for(int i = 0; i < people.size(); i++)
        {
    
    
            int pos = people[i][1];
            res.insert(res.begin() + pos, people[i]);//插入res中
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42771487/article/details/118326724