[LeetCode] 406、根据身高重建队列

406、根据身高重建队列(贪心)M

题目描述

假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。

输入:
[[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高度降序,K个数升序排序

      static bool cmp(const vector<int> &a, const vector<int> &b){
          return a[0] == b[0]? (a[1] < b[1]): (a[0] > b[0]); 
      }
      
    • 遍历排序后的数组,根据K插入到K的位置上

    • 核心思想:高个子先站好位,矮个子插入到K位置上,前面肯定有K个高个子,矮个子再插到前面也满足K的要求

      假设候选队列为 A,已经站好队的队列为 B.

      从 A 里挑身高最高的人 x 出来,插入到 B。 因为 B 中每个人的身高都比 x 要高,因此 x 插入的位置,就是看 x 前面应该有多少人就行了。比如 x 前面有 5 个人,那 x 就插入到队列 B 的第 5 个位置就可以啦。

      // [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]
      

    注:vector支持插入操作:res.insert(res.begin() + e[1], e);

参考代码

class Solution {
public:
    vector<vector<int> > reconstructQueue(vector<vector<int> >& people) {
        int length = people.size();
        if(length == 0)
            return vector<vector<int> >();
        vector<vector<int> > res;
        
        sort(people.begin(), people.end(), cmp);
        
        for(auto e: people){
            res.insert(res.begin() + e[1], e);  // 迭代器也能 +int
        }
        
        return res;
    }
    
    static bool cmp(const vector<int> &a, const vector<int> &b){
        return a[0] == b[0]? (a[1] < b[1]): (a[0] > b[0]); 
    }
    
};
发布了390 篇原创文章 · 获赞 576 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/ft_sunshine/article/details/103916508