当前位置: 首页 > java >正文

406. Queue Reconstruction by Height

目录

题目描述

贪心+直接插入排序

代码一:

代码二:

代码三:


题目描述

406. Queue Reconstruction by Height

贪心+直接插入排序

先按照身高从大到小排序,身高相等的人谁的k小谁站前面。

然后按照直接插入排序的想法,将每个人插入到他应该到达的位置。

代码一:

复用输入数据people,手写直接插入排序

class Solution {
public:vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {int len = people.size();sort(people.begin(),people.end(),[](vector<int> &p1,vector<int> &p2){if(p1[0] > p2[0])return true;else if(p1[0] == p2[0])return p1[1] < p2[1];return false;});for(int i = 0;i <len;i++){if(people[i][1] < i){vector<int> temp = people[i];int pos = people[i][1];for(int j = i-1;j >= pos;j--){people[j+1] = people[j];}people[pos] = temp;}}return people;}
};

插入会很耗时,时间复杂度是O(logn+n^2)

代码二:

用vector自己的insert函数,位置指定用迭代器。随机迭代器支持+n操作

class Solution {
public:vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {int len = people.size();sort(people.begin(),people.end(),[](vector<int> &p1,vector<int> &p2){if(p1[0] > p2[0])return true;else if(p1[0] == p2[0])return p1[1] < p2[1];return false;});vector<vector<int>> res;res.reserve(len);for(int i = 0;i <len;i++){int pos = people[i][1];if(pos < i){res.insert(res.begin()+pos,people[i]);}else{res.push_back(people[i]);}}return res;}
};

代码三:

用链表来插入。不过寻找插入位置仍然是O(n)的时间复杂度,因为在 C++ 中,std::list 的迭代器是双向迭代器,不支持随机访问(即不能直接使用 + 运算符进行偏移)

class Solution {
public:vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {int len = people.size();sort(people.begin(),people.end(),[](vector<int> &p1,vector<int> &p2){if(p1[0] > p2[0])return true;else if(p1[0] == p2[0])return p1[1] < p2[1];return false;});std::list<vector<int>> listres;for(int i = 0;i <len;i++){if(people[i][1] < i){int pos = people[i][1];listres.insert(std::next(listres.begin(),pos),people[i]);}elselistres.push_back(people[i]);}vector<vector<int>> res(listres.begin(),listres.end());return res;}
};

http://www.xdnf.cn/news/13737.html

相关文章:

  • 安装 Poppler(Windows)
  • Actix-web 中的权限中间件实现
  • 论文略读:Large Language Models Assume People are More Rational than We Really are
  • SQL进阶之旅 Day 27:存储过程与函数高级应用
  • 自检该如何写
  • 哈医大团队利用网络药理学+PPI分析+分子对接三联策略,解码灵芝孢子调控AKI凋亡的精准机制
  • 按关键字批量合并 Excel 多工作簿工作表攻略-Excel易用宝
  • FramePack 与其他视频生成工具的横向对比:优势、短板与差异化竞争
  • 有没有实现“直链”的网盘?不是外链
  • Spring生命周期及关联面试题
  • 25.6.12学习总结
  • 强化微调技术与GRPO算法(1):简介
  • 如何选择适合自己需求的PCB厚板厂家?
  • Windows桌面图标修复
  • 基于NSGA2的柔性作业车间调度
  • 【React】使用 useContext + useReducer 实现一个轻量的状态管理库
  • 大模型Prompt|提示工程的10个常见设计模式
  • Kubernetes安全机制深度解析(二):从身份认证到资源鉴权
  • 埃隆·马斯克宣布特斯拉Robotaxi自动驾驶出租车服务将于6月22日在奥斯汀“试运行”启动
  • Rust入门之并发编程基础(二)
  • Redis 安装实践:基于鲲鹏 ARM 架构 Ubuntu 环境
  • 【Linux网络篇】:TCP协议全解析(一)——从数据段格式到可靠传输的三大基石
  • GitHub Desktop Failure when receiving data from the peer
  • Facebook的速推帖子有用吗?
  • 补充讲解perfetto/systrace的CPU Trace信息详解和抓取方法
  • 深度学习:张量标量概念、PyTorch张量创建、类型转换等
  • C 语言之 循环
  • mvc与mvp
  • Oracle DG库手动注册归档日志的两种方法
  • 单链表经典算法题之分割链表