1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
evaluate-division.cpp 1.59 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 9年前 . Update evaluate-division.cpp
// Time: O(e + q * |V|!), |V| is the number of variables
// Space: O(e)
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations,
vector<double>& values, vector<pair<string, string>> query) {
unordered_map<string, unordered_map<string, double>> lookup;
for (int i = 0; i < values.size(); ++i) {
lookup[equations[i].first].emplace(equations[i].second, values[i]);
if (values[i] != 0) {
lookup[equations[i].second].emplace(equations[i].first, 1 / values[i]);
}
}
vector<double> result;
for (const auto& i : query) {
unordered_set<string> visited;
const auto tmp = check(i.first, i.second, lookup, &visited);
if (tmp.first) {
result.emplace_back(tmp.second);
} else {
result.emplace_back(-1);
}
}
return result;
}
private:
pair<bool, double> check(string up, string down,
unordered_map<string, unordered_map<string, double>> &lookup,
unordered_set<string> *visited) {
if (lookup[up].find(down) != lookup[up].end()) {
return {true, lookup[up][down]};
}
for (const auto& q : lookup[up]) {
if (!visited->count(q.first)) {
visited->emplace(q.first);
const auto tmp = check(q.first, down, lookup, visited);
if (tmp.first) {
return {true, q.second * tmp.second};
}
}
}
return {false, 0};
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助