LeetCode - 399 除法求值

LeetCode - 399 除法求值_第1张图片
LeetCode - 399 除法求值_第2张图片

class Solution {
    Map<String,Integer> strToIndex = new HashMap<String,Integer>();//将equations中的字符串转为index
    //String 转为 Integer 
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        //若两个字母在同一个并查集它们就可以互相做除法
        int index = 0;
        UnionFind uf = new UnionFind(2*equations.size());
        for(int i =0;i<equations.size();i++)
        {
            List<String> equation = equations.get(i);
            String e1 = equation.get(0);
            String e2 = equation.get(1);
            if(strToIndex.get(e1) == null)
               strToIndex.put(e1,index++);
            if(strToIndex.get(e2) == null)
               strToIndex.put(e2,index++);
            uf.union(strToIndex.get(e1),strToIndex.get(e2),values[i]);
        }
        double[] ans = new double[queries.size()];
        for(int i =0;i<queries.size();i++){
            List<String> querie = queries.get(i);
            String q1 = querie.get(0);
            String q2 = querie.get(1);
            int index1 = strToIndex.getOrDefault(q1,-1);
            int index2 = strToIndex.getOrDefault(q2,-1);
            if(index1== -1 || index2 == -1)
                ans[i] = -1.00000;
            else
                ans[i] = uf.isConnected(index1, index2);
        }
        return ans;

    }
    public class UnionFind{
        private int[] parent;
        private double[] weight;
        public UnionFind(int n){
            this.parent = new int[n];
            this.weight = new double[n];
            for(int i = 0;i < n; i++){
                this.parent[i] = i;
                this.weight[i] = 1.0d;
            }
        }
        public int find(int x){
            if(x != parent[x]){//当不是根节点时
                int origin = parent[x];
                parent[x] = find(parent[x]);
                weight[x] *= weight[origin];
            }
            return parent[x];
        }
       public void union(int x, int y, double value) {
             int rootX = find(x);
             int rootY = find(y);
             if(rootX == rootY)
                return ;
            parent[rootX] = rootY;
            weight[rootX] = weight[y] * value / weight[x];
       }
        public double isConnected(int x, int y) {
            int rootX = find(x);
            int rootY = find(y);
            if(rootX == rootY)
            {
                return weight[x] / weight[y];
            }
            else
              return -1d;
        }
    }
}

你可能感兴趣的:(leetcode,leetcode,算法,职场和发展)