[LeetCode] Evaluate Division 求除法表達式的值


 

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.

 

這道題作為第四次編程比賽的壓軸題,感覺還是挺有難度的,個人感覺難度應該設為hard比較合理。這道題已知條件中給了一些除法等式,然后給了另外一些除法等式,問我們能不能根據已知條件求出結果,不能求出來的用-1表示。問題本身是很簡單的數學問題,但是寫代碼來自動實現就需要我們用正確的數據結構和算法,通過觀察題目中的例子,我們可以看出如果需要分析的除法式的除數和被除數如果其中任意一個沒有在已知條件中出現過,那么返回結果-1,所以我們在分析已知條件的時候,可以使用set來記錄所有出現過的字符串,然后我們在分析其他除法式的時候,可以使用遞歸來做。通過分析得出,不能直接由已知條件得到的情況主要有下面三種:

1) 已知: a / b = 2, b / c = 3, 求 a / c
2) 已知: a / c = 2, b / c = 3, 求 a / b
3) 已知: a / b = 2, a / c = 3, 求 b / c

雖然有三種情況,但其實后兩種情況都可以轉換為第一種情況,對於每個已知條件,我們將其翻轉一下也存起來,那么對於對於上面美中情況,就有四個已知條件了:

1) 已知: a / b = 2,b / a = 1/2,b / c = 3,c / b = 1/3,求 a / c
2) 已知: a / c = 2,c / a = 1/2,b / c = 3,c / b = 1/3,求 a / b
3) 已知: a / b = 2,b / a = 1/2a / c = 3,c / a = 1/3,求 b / c

我們發現,第二種和第三種情況也能轉化為第一種情況,只需將上面加粗的兩個條件相乘即可。對於每一個需要解析的表達式,我們需要一個HashSet來記錄已經訪問過的表達式,然后對其調用遞歸函數。在遞歸函數中,我們在HashMap中快速查找該表達式,如果跟某一個已知表達式相等,直接返回結果。如果沒有的話,那么就需要間接尋找了,我們在HashMap中遍歷跟解析式中分子相同的已知條件,跳過之前已經遍歷過的,否則就加入visited數組,然后再對其調用遞歸函數,如果返回值是正數,則乘以當前已知條件的值返回,就類似上面的情況一,相乘以后b就消掉了。如果已知找不到解,最后就返回-1,參見代碼如下:

 

解法一:

class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        vector<double> res;
        for (int i = 0; i < equations.size(); ++i) {
            m[equations[i].first][equations[i].second] = values[i];
            m[equations[i].second][equations[i].first] = 1.0 / values[i];
        }
        for (auto query : queries) {
            unordered_set<string> visited;
            double t = helper(query.first, query.second, visited);
            res.push_back((t > 0.0) ? t : -1);
        }
        return res;
    }
    double helper(string up, string down, unordered_set<string>& visited) {
        if (m[up].count(down)) return m[up][down];
        for (auto a : m[up]) {
            if (visited.count(a.first)) continue;
            visited.insert(a.first);
            double t = helper(a.first, down, visited);
            if (t > 0.0) return t * a.second;
        }
        return -1.0;
    }

private:
    unordered_map<string, unordered_map<string, double>> m;
};

 

此題還有迭代的寫法,用鄰接列表的表示方法建立了一個圖,然后進行bfs搜索,需要用queue來輔助運算,參見代碼如下:

 

解法二:

class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        vector<double> res;
        unordered_map<string, unordered_map<string, double>> g;
        for (int i = 0; i < equations.size(); ++i) {
            g[equations[i].first].emplace(equations[i].second, values[i]);
            g[equations[i].first].emplace(equations[i].first, 1.0);
            g[equations[i].second].emplace(equations[i].first, 1.0 / values[i]);
            g[equations[i].second].emplace(equations[i].second, 1.0);
        }
        for (auto query : queries) {
            if (!g.count(query.first) || !g.count(query.second)) {
                res.push_back(-1.0);
                continue;
            }
            queue<pair<string, double>> q;
            unordered_set<string> visited{query.first};
            bool found = false;
            q.push({query.first, 1.0});
            while (!q.empty() && !found) {
                for (int i = q.size(); i > 0; --i) {
                    auto t = q.front(); q.pop();
                    if (t.first == query.second) {
                        found = true;
                        res.push_back(t.second);
                        break;
                    }
                    for (auto a : g[t.first]) {
                        if (visited.count(a.first)) continue;
                        visited.insert(a.first);
                        a.second *= t.second;
                        q.push(a);
                    }
                }
            }
            if (!found) res.push_back(-1.0);
        }
        return res;
    }
};

 

參考資料:

https://leetcode.com/problems/evaluate-division/

https://leetcode.com/problems/evaluate-division/discuss/88347/c-bfs-solution-easy-to-understand

https://leetcode.com/problems/evaluate-division/discuss/88287/esay-understand-java-solution-3ms

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM