Evaluate Division——LeetCode进阶路

原题链接https://leetcode.com/problems/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& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector.

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
分析:用HashMap存储图的链接表,用Set创建图节点的访问标记,搜索是否有满足关系的路径(笔者使用dfs)。当然使用Floyd算法(就是插点法啦)也OK的,就是他的O(n^3)d的时间复杂度……

  • 其中需要注意以下几种特殊情况:
    • a \ a =1自身相除为1
    • 不连通的情况,返回-1

AC解

class Solution {
    Map<String,HashMap<String,Double>> map = new HashMap<>();
    
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        for(int i=0; i<equations.length;i ++)
        {
            String s1 = equations[i][0];
            String s2 = equations[i][1];
            double d = values[i];
            map.computeIfAbsent(s1, l -> new HashMap<String, Double>()).put(s2, d);
            map.computeIfAbsent(s2, l -> new HashMap<String, Double>()).put(s1, 1.0/d);
        }
        
        double[] result = new double[queries.length];
        
        for(int i=0; i<queries.length;i ++)
        {
            String s1 = queries[i][0];
            String s2 = queries[i][1];
            if(!map.containsKey(s1) || !map.containsKey(s2) )
            {
               result[i] = -1.0;
            }
            else
            {
                result[i] = f(s1,s2,new HashSet<String>());
            }            
        }
        return result;
    }
    
    public double f(String s1,String s2,Set<String> set)
    {
        if(s1.equals(s2))
        {
            return 1.0;
        }
        set.add(s1);
        if(!map.containsKey(s1))
        {
            return -1.0;
        }
        for(String t:map.get(s1).keySet())
        {
            if(set.contains(t))
            {
                continue;
            }
            set.add(t);
            double d = f(t,s2,set);
            if(d>0)
            {
                return d*map.get(s1).get(t);
            }
        }        
        return -1.0;
    }
}

猜你喜欢

转载自blog.csdn.net/Moliay/article/details/88662813
今日推荐