C++ use hashmap


  • 0
    Y
    class Solution {
    public:
        unordered_map<string, unordered_map<string, double>> calculatedMap;
        unordered_map<string, string> visited;
        double calcEquation_helper(pair<string, string> query)
        {
            if(visited[query.first] == query.second || visited[query.second] == query.first)return -1.0f;
            visited[query.first] = query.second;
        	if (calculatedMap.find(query.first) != calculatedMap.end())
        	{
        	    if (calculatedMap[query.first].find(query.second) != calculatedMap[query.first].end())
        	        return calculatedMap[query.first][query.second];
        		for (auto iter = calculatedMap[query.first].begin(); iter != calculatedMap[query.first].end(); iter++)
        		{
        		    if(iter->first == query.first)continue;
        			pair<string, string> newQuery = make_pair(iter->first, query.second);
        			double temp = calcEquation_helper(newQuery);
        			if (temp > 0.0f)
        				return iter->second * temp;
        		}
        	}
        	
        	if (calculatedMap.find(query.second) != calculatedMap.end())
        	{
        	    if (calculatedMap[query.second].find(query.first) != calculatedMap[query.second].end())
        		    return (1.0f/calculatedMap[query.second][query.first]);
        		for (auto iter = calculatedMap[query.second].begin(); iter != calculatedMap[query.second].end(); iter++)
        		{
        		    if(iter->first == query.second)continue;
        			pair<string, string> newQuery = make_pair(query.first, iter->first);
        			double temp = calcEquation_helper(query);
        			if (temp > 0.0f)
        				return temp * (1.0f/iter->second);
        		}
        	}
        	return -1.0f;
        }
        vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        	vector<double> result;
        	for (int i = 0; i < equations.size(); i++)
        	{
        		calculatedMap[equations[i].first][equations[i].second] = values[i];
        		calculatedMap[equations[i].second][equations[i].first] = 1.0f / values[i];
        		calculatedMap[equations[i].first][equations[i].first] = 1.0f;
        		calculatedMap[equations[i].second][equations[i].second] = 1.0f;
        	}
        	for (int i = 0; i<queries.size(); i++)
        	{
        	    visited.clear();
        		result.push_back(calcEquation_helper(queries[i]));
        	}
        	return result;
        }
    };

Log in to reply
 

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