1. 程式人生 > >[LeetCode] 399. Evaluate Division Java

[LeetCode] 399. Evaluate Division Java

always osi turn 記錄 result urn 關系 positive ==

題目:

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.

題意及分析:給出一系列字符串之間的比率關系,求任意兩個字符串之間的比率,若不存在則返回-1.0,若兩個字符串相等,則返回1.0。從本質來看是要遍歷圖,查找是否存在頂點A到另一個頂點的路徑,這裏我們用鄰接表法表示圖,然後用一個對應的hashmap保存一個點和其鄰接點的比率。然後查找兩個字符串之間的比率就變成了求圖中一個頂點到一個頂點的路徑,然後路徑上的值乘積。這裏需要註意的是若a/b = c,那麽b/a = 1/c;在遍歷的時候用一個hashset記錄當前被遍歷過的點,當當前點已經被遍歷過那麽這條路徑不通,返回0.0。

代碼:

public class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {

        int length = equations.length;
        HashMap<String,ArrayList<String>> neighbors = new HashMap<>();      //記錄每個點的鄰接頂點
        HashMap<String,ArrayList<Double>> neighborsValue = new HashMap<>();//記錄個點鄰接頂點對應的值

        for(int i=0;i<length;i++){      //若a/b = c,那麽b/a = 1/c;
            if(!neighbors.containsKey(equations[i][0])){
                neighbors.put(equations[i][0],new ArrayList<>());
                neighborsValue.put(equations[i][0],new ArrayList<>());
            }
            if(!neighbors.containsKey(equations[i][1])){
                neighbors.put(equations[i][1],new ArrayList<>());
                neighborsValue.put(equations[i][1],new ArrayList<>());
            }

            neighbors.get(equations[i][0]).add(equations[i][1]);
            neighborsValue.get(equations[i][0]).add(values[i]);

            neighbors.get(equations[i][1]).add(equations[i][0]);
            neighborsValue.get(equations[i][1]).add(1/values[i]);
        }

        double[] res = new double[queries.length];
        for(int i=0;i<queries.length;i++){
            String a = queries[i][0];
            String b = queries[i][1];
            res[i] = dfs(1.0,a,b,neighbors,neighborsValue,new HashSet<>());//hashset用來保存已經遍歷過的點
            if (res[i] == 0.0) res[i] = -1.0;
        }
        return res;
    }

    public double dfs(double value,String a,String b,HashMap<String,ArrayList<String>> neighbors,HashMap<String,ArrayList<Double>> neighborsValue,HashSet<String> hashSet){
        if(hashSet.contains(a))     //已經遍歷過該點
            return 0.0;
        if(!neighbors.containsKey(a)) return 0.0;       //不存在該點
        if(a.equals(b)) return value;
        hashSet.add(a);     //標記為已遍歷
        List<String> neigh = neighbors.get(a);
        List<Double> neighValues = neighborsValue.get(a);
        double tmp = 0.0;
        for(int i=0;i<neigh.size();i++){
            String dot = neigh.get(i);
            double dotValue = neighValues.get(i);
            tmp = dfs(value*dotValue,dot,b,neighbors,neighborsValue,hashSet);
            if(tmp!=0.0)        //不為0,那麽找到了結果,直接break,不需要繼續查找
                break;
        }
        hashSet.remove(a);
        return tmp;
    }
}

[LeetCode] 399. Evaluate Division Java