1+ // 399. 除法求值
2+
3+
4+ class Solution {
5+ public double [] calcEquation (List <List <String >> equations , double [] values , List <List <String >> queries ) {
6+ int size = equations .size ();
7+ Map <String , Integer > map = new HashMap <>(2 * size );
8+ UnionFind unionFind = new UnionFind (2 * size );
9+ int id = 0 ;
10+ double [] res = new double [queries .size ()];
11+ for (List <String > list : equations ) {
12+ String val1 = list .get (0 );
13+ String val2 = list .get (1 );
14+ if (!map .containsKey (val1 )) {
15+ map .put (val1 , id );
16+ id ++;
17+ }
18+ if (!map .containsKey (val2 )) {
19+ map .put (val2 , id );
20+ id ++;
21+ }
22+ }
23+ for (int i = 0 ; i < size ; i ++) {
24+ int val1 = map .get (equations .get (i ).get (0 ));
25+ int val2 = map .get (equations .get (i ).get (1 ));
26+ unionFind .union (val1 , val2 , values [i ]);
27+ }
28+ for (int i = 0 ; i < queries .size (); i ++) {
29+ if (map .containsKey (queries .get (i ).get (0 )) && map .containsKey (queries .get (i ).get (1 ))) {
30+ int val1 = map .get (queries .get (i ).get (0 ));
31+ int val2 = map .get (queries .get (i ).get (1 ));
32+ res [i ] = unionFind .getValue (val1 , val2 );
33+ } else {
34+ res [i ] = -1.0d ;
35+ }
36+ }
37+ return res ;
38+ }
39+ }
40+
41+ class UnionFind {
42+ int [] parent ;
43+ double [] weight ; // 表示当前节点到根节点的值
44+
45+ public UnionFind (int size ) {
46+ this .parent = new int [size ];
47+ this .weight = new double [size ];
48+ for (int i = 0 ; i < size ; i ++) {
49+ parent [i ] = i ;
50+ weight [i ] = 1.0d ;
51+ }
52+ }
53+
54+ //找到当前节点的根节点,在查询的同时进行路径压缩
55+ public int find (int x ) {
56+ if (x != parent [x ]) {
57+ int temp = parent [x ];
58+ parent [x ] = find (parent [x ]);
59+ weight [x ] = weight [x ] * weight [temp ];
60+ }
61+ return parent [x ];
62+ }
63+
64+ //将两个节点进行合并
65+ public void union (int x , int y , double value ) {
66+ int rootX = find (x );
67+ int rootY = find (y );
68+ if (rootX == rootY ) {
69+ return ;
70+ } else {
71+ parent [rootX ] = rootY ;
72+ weight [rootX ] = value * weight [y ] / weight [x ];
73+ }
74+ }
75+
76+ //判断两个节点是否属于同一个分组
77+ public boolean isConnected (int x , int y ) {
78+ return find (x ) == find (y );
79+ }
80+
81+ //返回连个节点的比值
82+ public double getValue (int x , int y ) {
83+ if (!isConnected (x , y )) {
84+ return -1.0d ;
85+ } else {
86+ return weight [x ] / weight [y ];
87+ }
88+ }
89+ }
0 commit comments