Monday, April 14, 2025

721. Accounts Merge --- M !!!!!!

Given a list of accounts where 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 common email 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","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third 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.

Example 2:

Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]

 

Constraints:

  • 1 <= accounts.length <= 1000
  • 2 <= accounts[i].length <= 10
  • 1 <= accounts[i][j].length <= 30
  • accounts[i][0] consists of English letters.
  • accounts[i][j] (for j > 0) is a valid email.

 A:

先遍历一个账号,如果所有的边都没有被找到。那么就新建一个。 

代码如下: (可是是的)

class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
// map each email to account + One of the email (connect via $)
unordered_map<string, string> M;
for(auto account : accounts){
auto name = account[0];
// check all email to find an overlap.
string target_account_name = "";
for(int j = 1; j < account.size(); j++){
auto email = account[j];
if(M.find(email) != M.end()){ // found it
target_account_name = M[email];
break;
}
}
if(target_account_name == ""){ // not found , create
target_account_name = name + "$" + account[1];
}
for(int j = 1; j < account.size(); j++){
auto email = account[j];
M[email] = target_account_name;
}
}
// reverse back
unordered_map<string, vector<string>> M2;
for(auto& [key, value] : M){
M2[value].push_back(key);
}
vector<vector<string>> res;
for(auto& [key, value] : M2){
auto name = key.substr(0, key.find('$'));
vector<string> tmp{name};
sort(value.begin(), value.end());
tmp.insert(tmp.end(), value.begin(), value.end());
res.push_back(tmp);
}
return res;
}
};



逻辑错误在于。 【A, 1,2】 【A , 3,4】 会建立2个账号。可是如果再来个【A,1,3】 就会把上面的都merge起来。


 另一种思路:  

每次有一行,就增加一个map 的行。然后对新增加的这一行,开始看那些key可以做merge。 再一起merge起来。

class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
// for each row, map the line# + account to a set of emails. Then for
// each email, begin the merge
unordered_map<string, unordered_set<string>> M; // name+line# to email set
for (int i = 0; i < accounts.size(); i++) {
auto account = accounts[i];
auto name = account[0];
unordered_set<string> S{account.begin() + 1, account.end()};
M[name + "$" + to_string(i)] = S;
unordered_set<string> tobeMerged;
for (int j = 1; j < account.size(); j++) {
for (auto& [key, emails] : M) {
if (emails.find(account[j]) != emails.end()) {
tobeMerged.insert(key);
}
}
}
vector<string> V{tobeMerged.begin(), tobeMerged.end()};
for (int k = 1; k < V.size(); k++) {
M[V[0]].insert(M[V[k]].begin(), M[V[k]].end());
M.erase(V[k]);
}
}
vector<vector<string>> res;
for (auto& [key, emails] : M) {
vector<string> tmp{key.substr(0, key.find('$'))};
tmp.insert(tmp.end(), emails.begin(), emails.end());
sort(tmp.begin() + 1, tmp.end());
res.push_back(tmp);
}
return res;
}
};


Learned:

how to traversing an unordered_map

1: use iterator


unordered_map<int, string> um = {{1, "Geeks"}, {2, "For"}, {3, "C++"}}; // Traversing using iterators with loop for(auto it = um.begin(); it != um.end(); it++) cout << it->first << ": " << it->second << endl;

2: use [ key, value] pair 

for (auto& [key, emails] : M) {}


下面的思路我第二次想的方法: 但是没做下去。

(因为我发现了如果是3个set 来merge,会fail) 。

写了写,就改写👆的,直接做merge,不去找parent了

👇 这是别人的代码

class Solution {
int findPar(int node, vector<int>& prnt) {
if (prnt[node] == node)
return node;
return prnt[node] = findPar(prnt[node], prnt);
}

void unionn(int u, int v, vector<int>& rank, vector<int>& prnt) {
u = findPar(u, prnt), v = findPar(v, prnt);

if (rank[u] < rank[v])
prnt[u] = v;
else if (rank[u] > rank[v])
prnt[v] = u;
else
prnt[v] = u, rank[u]++;
}

public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
int n = accounts.size();

vector<int> rank(n, 0), prnt(n);
for (int i = 0; i < n; i++)
prnt[i] = i;

unordered_map<string, int> em;
for (int i = 0; i < n; i++) {
for (int j = 1; j < accounts[i].size(); j++) {
if (em.find(accounts[i][j]) == em.end())
em[accounts[i][j]] = i;
else
unionn(em[accounts[i][j]], i, rank, prnt);
}
}
vector<set<string>> merge(n);
for (auto i : em)
merge[findPar(i.second, prnt)].insert(i.first);

vector<vector<string>> ans;
for (int i = 0; i < n; i++) {
if (!merge[i].size())
continue;

vector<string> t;
t.push_back(accounts[i][0]);
for (string s : merge[i])
t.push_back(s);
ans.push_back(t);
}

return ans;
}
};

Saturday, April 12, 2025

695. Max Area of Island. --- M

 You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

 

Example 1:

Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

Example 2:

Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1.


A:

就是经典的dfs

class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int res = 0;
for(int i =0; i<grid.size(); i++){
for(int j = 0 ;j < grid[0].size(); j++){
if(grid[i][j] == 1){
int curSize = 0;
dfs(grid, i, j, curSize);
res = max(res, curSize);
}
}
}
return res;
}
private:
void dfs(vector<vector<int>>& grid, int i, int j , int &curSize){
int m = grid.size(), n = grid[0].size();
if(i<0 || i >= m || j < 0 || j >= n || grid[i][j] == 0)
return;
grid[i][j] = 0;
curSize++;
vector<vector<int>> V = {{-1,0}, {1,0}, {0,1}, {0, -1}};
for(auto p : V){
dfs(grid, p[0] + i, p[1] + j, curSize );
}
}
};



Thursday, April 10, 2025

994. Rotting Oranges -- M

 You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

 

Example 1:

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2:

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.

Example 3:

Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 01, or 2.

A:

典型的BFS, 需要注意的就是 极端的,全空, 全1, 的情况

class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<pair<int, int>> V;
bool hasOrange = false;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (grid[i][j] == 2)
V.push_back({i, j});
if (grid[i][j] == 1)
hasOrange = true;
}
if (not hasOrange)
return 0;
if (V.empty()) // else has only 1
return -1;
int res = -1;
while (not V.empty()) {
res++;
V = bfs(grid, V);
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (grid[i][j] == 1)
return -1;
return res;
}

private:
vector<pair<int, int>> bfs(vector<vector<int>>& grid,
vector<pair<int, int>>& V) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> step = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
vector<pair<int, int>> newV;
for (const auto& v : V) {
for (auto s : step) {
int x = v.first + s[0], y = v.second + s[1];
if (x >= 0 && x < m && y >= 0 && y < n) {
if (grid[x][y] == 1) {
newV.push_back({x, y});
grid[x][y] = 2;
}
}
}
}
return newV;
}
};

但是,上面的效率不行。 才beat  5%   感觉是因为每次生成的新的数组。 需要一层层地跑。

----------------------- 把递归改成循环----------

class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<pair<int, int>> V;
int freshOrange = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (grid[i][j] == 2)
V.push_back({i, j});
if (grid[i][j] == 1)
freshOrange++;
}
if (freshOrange == 0)
return 0;
if (V.empty()) // has no rotten orange
return -1;
int res = 0, start = 0;
vector<vector<int>> Step = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (true) {
int oldSize = V.size();
for (int i = start; i < oldSize; i++) {
for (auto s : Step) {
int x = V[i].first + s[0], y = V[i].second + s[1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
V.push_back({x, y});
grid[x][y] = 2;
freshOrange--;
}
}
}
if (oldSize < V.size()) { // check with the new
res++;
} else {
break;
}
start = oldSize;
}
return freshOrange == 0 ? res : -1;
}
};