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

[Lc_week] 447 | 155 | Q1 | hash | pair {}调用

447_Q1

题解

class Solution {typedef pair<int,int> PII;// 自定义哈希函数struct HashPII {size_t operator()(const PII& p) const {return hash<int>()(p.first) ^ (hash<int>()(p.second) << 1);}};public:int countCoveredBuildings(int n, vector<vector<int>>& buildings) {//不管有多远 至少存在一个建筑//bfs变形//哦不对,hash 快速查找同行同列,不就可以判断了吗//添加自定义哈希函数HashPII,使用unordered_map<PII, bool, HashPII>解决pair作为键的问题unordered_map<PII,bool,HashPII> hash;int ans=0;for(auto& b:buildings){PII p={b[0],b[1]};  //pair构造和调用 要用{}hash[p]=true;}for(auto& b:buildings){int cnt=0;//四个 方向的查找//上for(int i=b[1]+1;i<=n;i++){if(hash.count({b[0],i})){cnt++;break;}}for(int i=b[1]-1;i>=1;i--){if(hash.count({b[0],i})){cnt++;break;}}for(int i=b[0]-1;i>=1;i--){if(hash.count({i,b[1]})){cnt++;break;}}for(int i=b[0]+1;i<=n;i++){if(hash.count({i,b[1]})){cnt++;break;}}if(cnt==4) ans++;}return ans;}
};©leetcode
  • pair 构造和调用 要用 {}
  • !!!!!!!!!!!!!!花括号

超时了

优化

  • 采取 行列极值法
class Solution {
public:int countCoveredBuildings(int n, vector<vector<int>>& buildings) {// 存 行位置极值和列位置极值unordered_map<int, int> row_min, row_max;unordered_map<int, int> col_min, col_max;for (auto& b : buildings) {int x = b[0], y = b[1];// 预处理行极值if (!row_min.count(x) || y < row_min[x])row_min[x] = y;if (!row_max.count(x) || y > row_max[x])row_max[x] = y;// 预处理列极值if (!col_min.count(y) || x < col_min[y])col_min[y] = x;if (!col_max.count(y) || x > col_max[y])col_max[y] = x;}int ans = 0;for (auto& b : buildings) {int x = b[0], y = b[1];bool up = (y < row_max[x]);bool down = (y > row_min[x]);bool left = (x > col_min[y]);bool right = (x < col_max[y]);if (up && down && left && right)ans++;}return ans;}
};©leetcode

155_Q1

class Solution {
public:string findCommonResponse(vector<vector<string>>& responses) {unordered_map<string,int> hash;for(auto& re:responses){unordered_map<string,bool> check;for(auto& str:re){if(!check[str]){check[str]=true;hash[str]++; //确保 每一个 只加一次}}}pair<string,int> ret(responses[0][0],0);for(auto& [a,b]:hash){string& f=ret.first;int& g=ret.second;if(b==g){if(a<f)f=a;}if(b>g){f=a;g=b;}}return ret.first;}
};

相关文章:

  • 前端性能优化面试回答技巧
  • 解析 OpenHarmony、HarmonyOS 与 HarmonyOS Next:优雅草卓伊凡的观点
  • 三、UI自动化测试03--操作方法API
  • 快速上手 MetaGPT
  • 云计算赋能质检LIMS的价值 质检LIMS系统在云计算企业的创新应用
  • 【计算机网络】网络基础概念
  • 网络安全厂商F5荣登2025 CRN AI 100榜单,释放AI潜力
  • 云计算市场的重新分类研究
  • 衡量矩阵数值稳定性的关键指标:矩阵的条件数
  • 鸿蒙系统应用开发全栈指南
  • openstack迁移虚机rbd报错,删除异常rbd
  • 机器人快速启动
  • Greenbone(绿骨)开源GVM容器docker部署和汉化介绍
  • 【2025 最新前沿 MCP 教程 06】构建你的第一个 MCP 服务器:分步指南(源码讲解)
  • 今日头条安卓版新闻推荐精准度与广告影响测评
  • vue中将html2canvas转成的图片传递给后台 Python Flask 服务
  • qt.qpa.plugin: Could not find the Qt platform plugin “cocoa“ in “ “
  • adb push 报错:CreateProcess failure, error 123
  • LeetCode[150]逆波兰表达式求值
  • Spring MVC深度解析:从原理到实战
  • 美情报机构攻击中国大型商用密码产品提供商,调查报告公布
  • 中国黄金协会:一季度我国黄金产量同比增1.49%,黄金消费量同比降5.96%
  • 经济日报:多平台告别“仅退款”,规则调整有何影响
  • 四川苍溪县教育局通报“工作人员辱骂举报学生”:停职检查
  • 学大教育:去年净利润1.797亿元,学习中心增加约60所
  • 四川一国企“80后”掌门人为报领导“知遇之恩”,盲目决策致数亿损失