Java with UF


  • 0
    W

    public class Solution {
    """

    HashMap<String, String> parents;
    HashMap<String, Double> nums;
    public double[] calcEquation(String[][] equations, double[] values, String[][] query) {
    	double[] rst = new double[query.length];
    	if (values == null || values.length == 0 ) return rst;
    	parents = new HashMap<>();
    	nums = new HashMap<>();
        for (int i = 0; i < values.length; i++ ) {
        	String up = equations[i][0];
        	String down = equations[i][1];
        	double val = values[i];
        	
        	if (nums.containsKey(up) && nums.containsKey(down)) {
        		String upRoot = findRoot(up);
        		String dowRoot = findRoot(down);
            	// key, value : up, down
            	if (!upRoot.equals(dowRoot)) {
            		double aDd = val;
            		double aDb = findValue(up);
            		double dDc = findValue(down);
            		double tmp = aDd / aDb * dDc;
            		nums.put(upRoot, tmp);
            		parents.put(upRoot, dowRoot);
            	}
    
        	}else if (nums.containsKey(up)) {
        		nums.put(down, 1/val);
        		parents.put(down, up);
        	}else {
        		nums.put(up, val);
        		nums.put(down, 1.0);
        		parents.put(up, down);
        	}
        }
        
        for (int i = 0; i < rst.length ; i++ ) {
        	
        	if (!findRoot(query[i][0]).equals(findRoot(query[i][1])) || !nums.containsKey(query[i][0]) || !nums.containsKey(query[i][1])) {
        		rst[i] = -1.0;
        	}else {
        		double upDR = findValue(query[i][0]);
        		double dowDR = findValue(query[i][1]);
        		rst[i] = upDR/dowDR;
        	}
    
        }
        return rst;
    }
    private String findRoot(String start) {
    	while (parents.containsKey(start)) {
    		start = parents.get(start);
    	}
    	return start;
    }
    private double findValue(String start) {
    	double rst = 1;
    	while (parents.containsKey(start)) {
    		rst *= nums.get(start);
    		start = parents.get(start);
    	}
    	return rst;
    }
    

    """


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.