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

2023-02-20 leetcode-AccountsMerge

摘要:

记录对leetcode-AccountsMerge的反思

要求:

Given a list accounts, each element accounts[i] is a list of strings, where the first element 
accounts[i][0] is a name, and the rest of the elements are emails representing emails of the 
account.
 * 
Now, we would like to merge these accounts.  Two accounts definitely belong to the same person if 
there is some email that is common to both accounts.  Note that even if two accounts have the same 
name, they may belong to different people as people could have the same name.  A person can have 
any number of accounts initially, but all of their accounts definitely have the same name.
 * 
After merging the accounts, return the accounts in the following format: the first element of each 
account is the name, and the rest of the elements are emails in sorted order.  The accounts 
themselves can be returned in any order.
 * 
Example 1:
 * 
Input: 
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], 
["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  ["John", 
"johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
 * 
Explanation: 
The first and third John's are the same person as they have the common email "johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses are used by other 
accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], 
['John', 'johnnybravo@mail.com'], 
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
 * 
Note:
The length of accounts will be in the range [1, 1000].
The length of accounts[i] will be in the range [1, 10].
The length of accounts[i][j] will be in the range [1, 30].

数据结构相关:

  1. std::vector
  2. std::map
  3. std::unordered_map

题解:

题解一:

// Declare variables for accounts, mapping and result
vector<vector<string>> accounts;
unordered_map<string, string> mapping;
vector<vector<string>> result;// Add accounts to 'accounts'
// ...// Traverse accounts
for (auto &a : accounts) {// Take the first email address and consider it as the root string root = a[1];for (int i = 2; i < a.size(); i++) {// If current email is already present in map if (mapping.find(a[i]) != mapping.end())root = mapping[a[i]]; // Choose its parent else keep root // Make an entry for all those email address mapping[a[i]] = root;}
}// Create the necessary structure for result 
unordered_map<string, set<string>> mp;
for (auto &p : mapping) mp[p.second].insert(p.first);// Form the resultant vector
for (auto &pp : mp) {vector<string> emails(pp.second.begin(), pp.second.end());emails.insert(emails.begin(), pp.first);result.push_back(emails);
}return result;

题解二:

Bad Performance Solution


//Bad Performance Solution
class Solution_Time_Limit_Exceeded {
public:// We can orginze all relevant emails to a chain,// then we can use Union Find algorithm// Besides, we also need to map the relationship between name and email.vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {unordered_map<string, string> emails_chains; // email chainsunordered_map<string, string> names; // names to email chains' head//initializationfor(int i = 0 ; i<accounts.size();i++) {auto& account = accounts[i];auto& name = account[0];for (int j=1; j<account.size(); j++) {auto& email = account[j];if ( names.find(email) == names.end() ) {emails_chains[email] = email;names[email] = name;}join(emails_chains, account[1], email);}}//reform the emailsunordered_map<string, set<string>> res;for( auto& acc : accounts ) {string e = find(emails_chains, acc[1]);res[e].insert(acc.begin()+1, acc.end());}//output the resultvector<vector<string>> result;for (auto pair : res) {vector<string> emails(pair.second.begin(), pair.second.end());emails.insert(emails.begin(), names[pair.first]);result.push_back(emails);}return result;}string find(unordered_map<string, string>& emails_chains,string email) {while( email != emails_chains[email] ){email = emails_chains[email];}return email;}bool join(unordered_map<string, string>& emails_chains,string& email1, string& email2) {string e1 = find(emails_chains, email1);string e2 = find(emails_chains, email2);if ( e1 != e2 )  emails_chains[e1] = email2;return e1 == e2;}
};

题解三:

Performance Tunning

//
// Performance Tunning
// -----------------
//
// The above algorithm need to do string comparison, it causes lots of efforts
// So, we allocated the ID for each email, and compare the ID would save the time.
//
// Furthermore, we can use the Group-Email-ID instead of email ID,
// this would save more time.
//
class Solution {
public:// We can orginze all relevant emails to a chain,// then we can use Union Find algorithm// Besides, we also need to map the relationship between name and email.vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {unordered_map<string, int> emails_id; //using email ID for union findunordered_map<int, int> emails_chains; // email chainsunordered_map<int, string> names; // email id & name//initialization & joinfor(int i = 0 ; i<accounts.size();i++) {// using the account index as the emails group ID,// this could simplify the emails chain.emails_chains[i] = i;auto& account = accounts[i];auto& name = account[0];for (int j=1; j<account.size(); j++) {auto& email = account[j];if ( emails_id.find(email) == emails_id.end() ) {emails_id[email] = i;names[i] = name;}else {join( emails_chains, i, emails_id[email] );}}}//reform the emailsunordered_map<int, set<string>> res;for(int i=0; i<accounts.size(); i++) {int idx = find(emails_chains, i);res[idx].insert(accounts[i].begin()+1, accounts[i].end());}//output the resultvector<vector<string>> result;for (auto pair : res) {vector<string> emails( pair.second.begin(), pair.second.end() );emails.insert(emails.begin(), names[pair.first]);result.push_back(emails);}return result;}int find(unordered_map<int, int>& emails_chains, int id) {while( id != emails_chains[id] ){id = emails_chains[id];}return id;}bool join(unordered_map<int, int>& emails_chains, int id1, int id2) {int e1 = find(emails_chains, id1);int e2 = find(emails_chains, id2);if ( e1 != e2 )  emails_chains[e1] = e2;return e1 == e2;}
};

相关文章:

2023-02-20 leetcode-AccountsMerge

摘要: 记录对leetcode-AccountsMerge的反思 要求: Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. * Now, w…...

中国高速公路行业市场规模及未来发展趋势

中国高速公路行业市场规模及未来发展趋势编辑中国高速公路行业市场规模正在迅速增长。随着中国经济的快速发展和城市化的加速&#xff0c;对交通基础设施的需求也在不断增加。高速公路是最有效的交通工具&#xff0c;可以大大缩短交通时间&#xff0c;提高出行效率。因此&#…...

佳能iC MF645CX彩色激光多功能打印机报E302-0001故障码检修

故障现象: 一台佳能iC MF645CX彩色激光多功能一体机开机报E302-0001故障代码,如果设备未恢复,请联系经销商或客户支持中心。 维修分析: 佳能iC MF645CX彩色激光多功能一体机开机报E302-0001故障代码的...

加密越来越简单——用JavaScript实现数据加密和解密

加密越来越简单——用JavaScript实现数据加密和解密概念常用算法1. MD5加密算法2. SHA-1加密算法3. AES加密算法代码示例结论总结在当今互联网的世界中&#xff0c;安全性越来越受到关注&#xff0c;数据加密成为了必不可少的一环。Javascript作为前端开发的主要语言之一&#…...

线程池的使用场景

学习整理线程池的使用场景。...

图像分割算法

图像分割算法阈值分割固定阈值自适应阈值大津阈值(OTSU)最大熵阈值连通域分析区域生长分水岭阈值分割、连通域分析、区域生长、分水岭 阈值分割 固定阈值、自适应阈值(adaptiveThreshold)、大津阈值(OTSU)、最大熵阈值(KSW) 固定阈值 固定阈值的调用函数&#xff1a; //Input…...

《mysql技术内幕:innodb存储引擎》笔记

任何时候Why都比What重要&#xff1b;不要相信任何的“神话”,学会自己思考&#xff1b;不要墨守成规,大部分人都知道的事情可能是错误的&#xff1b;不要相信网上的传言,去测试,根据自己的实践做出决定&#xff1b;花时间充分地思考,敢于提出质疑。1.MYSQL被设计为一个单进程多…...

windows与linux系统ntp服务器配置

一. windows 打开windows终端&#xff08;管理员&#xff09;&#xff0c;顺序输入以下指令 net stop w32time w32tm /unregister w32tm /register net start w32time w32tm /resync net stop w32time net start w32timewin r 输入regedit&#xff0c;打开注册表。 ①将HKEY_…...

html常用font-family设置字体样式

<table border"1" cellpadding"0" cellspacing"0" ><tr><td><h3 style"font-family: 黑体;">黑体&#xff1a;SimHei</h3></td><td><h3 style"font-family: 华文黑体;">华…...

数据库事务AICD以及隔离级别

目录一.事务的ACID二.隔离级别三.并发事务中的问题1.脏写2.脏读3.不可重复读4.幻读四.MVCC机制五.读锁与写锁六.大事务的影响七.事务优化一.事务的ACID 原子性(Atomicity)&#xff1a;一个事务中的所有操作&#xff0c;要么全部成功&#xff0c;要么失败全部回滚&#xff0c;不…...

(4)VScode之ssh基础配置

VScode和SSH基础配置问题集合 Author&#xff1a;onceday date&#xff1a;2022年8月31日 本文记录linux的ssh和vscode开发环境搭建之路。 参考文档&#xff1a; 离线安装vscode Once Day CSDN博客关于x86、x86_64/x64、amd64和arm64/aarch64 Bogon 简书arm64和aarch64之间…...

springcloud-1环境搭建、service provider

搭建项目环境创建新项目&#xff0c;选择archetype-webapp&#xff0c;创建一个父项目&#xff0c;该父项目会去管理多个微服务模块(module)项目设置Settings->Editor->File Encoding:Global/Project Encoding 改为UTF-8Default encoding for properties files:默认属性文…...

光谱仪工作过程及重要参数定义

标题光谱仪工作过程CCD、PDA薄型背照式BT-CCD狭缝Slit暗电流Dark Current分辨率Resolution色散Dispersion光栅和闪耀波长Grating波长精度、重复性和准确度Precision带宽Band widthF数F/#光谱仪工作过程 CCD、PDA 电荷耦合器件&#xff08;Charger Coupled Device&#xff0c;缩…...

W800|iot|HLK-W800-KIT-PRO|AliOS|阿里云| |官方demo|学习(1):板载AliOS系统快速上手

板载系统简介 HLK-W800-KIT-PRO 是海凌科电子面向开发者&#xff0c;采用了联盛德 w800 方案&#xff0c;带有一个RGB三色灯&#xff0c;集成了 CHT8305C 温湿度传感器的多功能开发板&#xff0c;用户可以在上面学习、研究嵌入式系统和物联网产品的开发&#xff0c;本套设备运行…...

字节终面,一道Linux题难住我了

以下是一道难道系数中高并且高频出现的linux面试题&#xff0c;题目具体要求如下&#xff1a; linux面试题&#xff1a; 某文件有多列数据&#xff0c;空格隔开&#xff0c;统计第n列单词&#xff0c;打印出现频率最高的5个单词。 解答这道面试题需要用到3个linux命令&#xff…...

三、NetworkX工具包实战2——可视化【CS224W】(Datawhale组队学习)

开源内容&#xff1a;https://github.com/TommyZihao/zihao_course/tree/main/CS224W 子豪兄B 站视频&#xff1a;https://space.bilibili.com/1900783/channel/collectiondetail?sid915098 斯坦福官方课程主页&#xff1a;https://web.stanford.edu/class/cs224w NetworkX…...

【MySQL】MySQL 架构

一、MySQL 架构 C/S 架构&#xff0c;即客户端/服务器架构。服务器程序直接和我们存储的数据打交道&#xff0c;多个客户端连接这个服务器程序。客户端发送请求&#xff0c;服务器响应请求。 MySQL 数据库实例 &#xff1a;即 MySQL 服务器的进程 &#xff08;我们使用任务管理…...

Python日期时间模块

Python 提供了 日期和时间模块用来处理日期和时间&#xff0c;还可以用于格式化日期和时间等常见功能。 时间间隔是以秒为单位的浮点小数。每个时间戳都以自从 1970 年 1 月 1 日午夜&#xff08;历元&#xff09;经过了多长时间来表示。 一、time模块使用 Time 模块包含了大…...

学以致用——植物信息录入1.0(selenium+pandas+os+tkinter)

目的 书接上文&#xff0c;学以致用——植物信息录入&#xff08;seleniumpandasostkinter) 更新要点&#xff1a; tkinter界面&#xff1a;自动登录、新增&#xff08;核心功能&#xff09;、文件夹选择、流程台selenium自动化操作&#xff1a;验证码识别excel数据&#xf…...

什么是压敏电阻

下面的这些都是压敏电阻&#xff0c;常常用在一些电源和信号的浪涌防护电路中。这个是它的电路符号&#xff0c;电路中常用RV表示。当压敏电阻两端电压小于压敏电压时&#xff0c;压敏电阻相当于一个阻值非常大的电阻。当压敏电阻两端电压大于压敏电压时&#xff0c;压敏电阻相…...

多模态大语言模型arxiv论文略读(111)

SEA: Supervised Embedding Alignment for Token-Level Visual-Textual Integration in MLLMs ➡️ 论文标题&#xff1a;SEA: Supervised Embedding Alignment for Token-Level Visual-Textual Integration in MLLMs ➡️ 论文作者&#xff1a;Yuanyang Yin, Yaqi Zhao, Yaji…...

Android第十三次面试总结基础

Activity生命周期和四大启动模式详解 一、Activity 生命周期 Activity 的生命周期由一系列回调方法组成&#xff0c;用于管理其创建、可见性、焦点和销毁过程。以下是核心方法及其调用时机&#xff1a; ​onCreate()​​ ​调用时机​&#xff1a;Activity 首次创建时调用。​…...

Flask音频处理:构建高效的Web音频应用指南

引言 在当今多媒体丰富的互联网环境中&#xff0c;音频处理功能已成为许多Web应用的重要组成部分。无论是音乐分享平台、语音识别服务还是播客应用&#xff0c;都需要强大的音频处理能力。Python的Flask框架因其轻量级和灵活性&#xff0c;成为构建这类应用的理想选择。 本文…...

powershell 安装 .netframework3.5

在 PowerShell 中安装 .NET Framework 3.5 可以通过几种不同的方法实现&#xff0c;取决于你的操作系统版本。以下是几种常见的方法&#xff1a; 方法1&#xff1a;使用 DISM 命令 对于 Windows 10 和 Windows 8.1&#xff0c;你可以使用 DISM&#xff08;Deployment Image Se…...

源码级拆解:如何搭建高并发「数字药店+医保购药」一体化平台?

在全民“掌上看病、线上购药”已成常态的今天&#xff0c;数字药店平台正在以惊人的速度扩张。而将数字药店与医保系统打通&#xff0c;实现线上医保购药&#xff0c;更是未来互联网医疗的关键拼图。 那么&#xff0c;如何从技术底层搭建一个 支持高并发、可扩展、安全合规的数…...

无人机目标检测与语义分割数据集(猫脸码客)

UAV 无人机数据集&#xff1a;驱动无人机配送研究迈向新高度 在科技浪潮的迅猛推动下&#xff0c;无人机配送这一新兴物流模式正以前所未有的态势&#xff0c;悄然改变着人们的生活图景。为深入挖掘并优化无人机配送技术&#xff0c;名为 UAV Delivery 的无人机数据集应运而生…...

go语言学习 第7章:数组

第7章&#xff1a;数组 数组是一种基本的数据结构&#xff0c;用于存储相同类型的元素集合。在Go语言中&#xff0c;数组的大小是固定的&#xff0c;一旦定义&#xff0c;其长度不可改变。本章将详细介绍Go语言中数组的定义、初始化、访问、遍历以及一些常见的操作。 一、数组…...

pikachu靶场通关笔记20 SQL注入03-搜索型注入(GET)

目录 一、SQL注入 二、搜索型注入 三、源码分析 1、渗透思路1 2、渗透思路2 四、渗透实战 1、渗透准备 2、SQL注入探测 &#xff08;1&#xff09;输入百分号单引号 &#xff08;2&#xff09;万能注入语句 3、获取回显列orderby 4、获取数据库名database 5、获取…...

Java 中 ArrayList、Vector、LinkedList 的核心区别与应用场景

Java 中 ArrayList、Vector、LinkedList 的核心区别与应用场景 引言 在 Java 集合框架体系中&#xff0c;ArrayList、Vector和LinkedList作为List接口的三大经典实现类&#xff0c;共同承载着列表数据的存储与操作功能。然而&#xff0c;由于底层数据结构设计、线程安全机制以…...

.Net Framework 4/C# 属性和方法

一、属性的概述 属性是对实体特征的抽象&#xff0c;用于提供对类或对象的访问&#xff0c;C# 中的属性具有访问器&#xff0c;这些访问器指定在它们的值被读取或写入时需要执行的语句&#xff0c;因此属性提供了一种机制&#xff0c;用于把读取和写入对象的某些特征与一些操作…...