LC 406. Queue Reconstruction by Height

本文介绍了一种基于高度和相对位置的队列重构算法。通过将人员按身高降序、相同身高下按人数升序排序,再根据第二个人数指标进行插入操作,实现了高效的队列重建。此算法在处理大规模数据时表现良好。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

 

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

Runtime: 32 ms, faster than 52.69% of C++ online submissions for Queue Reconstruction by Height.

按身高降序排列,身高相同的按第二个数升序排列。

然后我们一个一个按照第二个数的index插入一个新的序列。这样做的好处是,插入后面的数不会对之前的数产生

影响。

但这种做法需要新开一个数组,如果你不想新开一个数组,可以在当前数组种修改,但如果是vector其实提升效果一般吧,最好开一个链表。

 

#include <assert.h>
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#define ALL(x) (x).begin(), (x).end()
using namespace std;
class Solution {
public:
  static bool sortcmp(const pair<int,int> a, const pair<int,int> b){
    if(a.first == b.first) return a.second < b.second;
    return a.first > b.first;
  }
  vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
    vector<pair<int,int>> ret;
    if(people.empty()) return ret;
    sort(ALL(people), sortcmp);
    for(int i=0; i<people.size(); i++){
      ret.insert(ret.begin() + people[i].second, people[i]);
    }
    return ret;
  }
};

 

转载于:https://www.cnblogs.com/ethanhong/p/10190940.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值