399. Evaluate Division
- Total Accepted: 13214
- Total Submissions: 32884
- Difficulty: Medium
- Contributor: LeetCode
Equations are given in the format A / B = k
, where A
and B
are variables represented as strings, and k
is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0
.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries
, where equations.size() == values.size()
, and the values are positive. This represents the equations. Return vector<double>
.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ], values = [2.0, 3.0], queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
Subscribe to see which companies asked this question.
思路:
采用map<string, map<string, double>>的数据结构来记录两个字符串的除法运算结果,第一层的string是位于被除数位置的字符串,第二层的string是代表除数的字符串,double记录对应的结果,这样相当于构造了一个以字符串为顶点的有向图。对于求解的字符串运算式,若出现之前未提及的字符串,则赋值为-1.0,否则利用DFS的算法搜索,若可以得到运算结果则保存到上面的数据结构中,否则也赋值为-1.0。
代码:
class Solution {
public:
vector
calcEquation(vector
> equations, vector
& values, vector
> queries) { int size1 = equations.size(); int size2 = queries.size(); map
> g; vector
results; for(int i = 0; i < size1; i ++){ g[equations[i].first][equations[i].second] = values[i]; g[equations[i].second][equations[i].first] = 1.0 / values[i]; } for(int i = 0; i < size2; i ++){ string f = queries[i].first; string s = queries[i].second; if(g.find(f) == g.end() || g.find(s) == g.end()) results.push_back(-1.0); else{ map
visited; DFS(g, f, f, s, 1.0, visited); if(g[f].find(s) != g[f].end()) results.push_back(g[f][s]); else results.push_back(-1.0); } } return results; } void DFS(map
> &g, string f, string f2, string s, double k, map
&visited){ visited[f] = true; if(g[f].find(s) != g[f].end()){ g[f2][s] = k * g[f][s]; return; } for(map
::iterator iter = g[f].begin(); iter != g[f].end(); iter ++){ string f1 = iter->first; double v = iter->second; double k1 = k * v; if(visited.find(f1) == visited.end()) DFS(g, f1, f2, s, k1, visited); } } };