leetcode:399. Evaluate Division

分手后的思念是犯贱 2022-09-26 02:13 245阅读 0赞

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

  1. import java.util.Arrays;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class Solution {
  5. static boolean[][] vis = null;
  6. static double[][] graph;
  7. public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
  8. double[] ans = new double[queries.length];
  9. HashMap<String, Integer> map = new HashMap<String, Integer>();
  10. int index = 0;
  11. index = this.map(map, index, equations);
  12. // index = this.map(map, index, queries);
  13. graph = new double[index][index];
  14. vis = new boolean[index][index];
  15. for (int i = 0; i < graph.length; ++i) {
  16. Arrays.fill(graph[i], -1);
  17. }
  18. index = 0;
  19. for (String[] s : equations) {
  20. int a = map.get(s[0]);
  21. int b = map.get(s[1]);
  22. graph[a][b] = values[index];
  23. graph[b][a] = 1.0 / values[index];
  24. ++index;
  25. }
  26. for(int i = 0; i < graph.length; ++i){
  27. graph[i][i] = 1.0;
  28. vis[i][i] = true;
  29. dfs(i, i, graph[i][i]);
  30. }
  31. for(int i = 0 ; i < graph.length; ++i){
  32. System.out.println(Arrays.toString(graph[i]));
  33. }
  34. index = 0;
  35. for(String[] s : queries){
  36. Integer a = map.get(s[0]);
  37. Integer b = map.get(s[1]);
  38. if(a == null || b == null){
  39. ans[index++] = -1;
  40. continue;
  41. }
  42. ans[index ++] = graph[a][b];
  43. }
  44. return ans;
  45. }
  46. public static void dfs(int a, int b, double value) {
  47. for(int i = 0; i < graph.length; ++i){
  48. if(graph[b][i] > 0 && !vis[a][i]){
  49. vis[a][i] = true;
  50. graph[a][i] = value * graph[b][i];
  51. dfs(a, i, graph[a][i]);
  52. }
  53. }
  54. }
  55. private int map(Map<String, Integer> map, int index, String[][] equations) {
  56. for (String[] ss : equations) {
  57. String a = ss[0];
  58. String b = ss[1];
  59. if (map.get(a) == null) {
  60. map.put(a, index++);
  61. }
  62. if (map.get(b) == null) {
  63. map.put(b, index++);
  64. }
  65. }
  66. return index;
  67. }
  68. public static void main(String[] args) {
  69. String[][] equations= new String[][]{
  70. {
  71. "a", "b"}, {
  72. "b", "c"}};
  73. double values[] = new double[]{
  74. 2, 3};
  75. String[][] queries = { {
  76. "a", "c"}, {
  77. "b", "a"}, {
  78. "a", "e"}, {
  79. "a", "a"}, {
  80. "x", "x"} };
  81. Solution s = new Solution();
  82. double[] ans = s.calcEquation(equations, values, queries);
  83. System.out.println(Arrays.toString(ans));
  84. }
  85. }

发表评论

表情:
评论列表 (有 0 条评论,245人围观)

还没有评论,来说两句吧...

相关阅读