并查集
考点:
1、使用并查集,计算出每个节点到跟节点的除法;如果2个数根节点不一致,则不能相除;如果是相同根节点, 相对除法为 2个数到根节点的相除
2、注意黄色字体的代码,因为返回的xx, yy均为tmp中的数据位置,所有这2行代码顺序不能错; 如果调换,先执行下面语句,则xx,yy第一个字符串会改变(xx[0]改变),从而影响赋值value
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
tmp = {}
def find(x):
if not x == tmp[x][0]:
next_nodex = find(tmp[x][0])
tmp[x][0] = next_nodex[0]
tmp[x][1] = tmp[x][1] * next_nodex[1]
return tmp[x]
def union(x, y, m):
# print("****", m)
# print(x, y)
# print(tmp)
xx = find(x)
yy = find(y)
# print(xx[0], m*yy[1] / xx[1])
# print(xx, yy)
if not xx[0] == yy[0]:
tmp[xx[0]][1] = m*yy[1] / xx[1]
tmp[xx[0]][0] = yy[0]
# print(tmp)
# 初始化全量集
for equation in equations:
tmp[equation[0]] = [equation[0], 1]
tmp[equation[1]] = [equation[1], 1]
# print(tmp)
# 建立关系
for index, equation in enumerate(equations):
union(equation[0], equation[1], values[index])
# print(tmp)
for key in tmp.keys():
# print(key)
find(key)
result = []
for q in queries:
if q[0] in tmp and q[1] in tmp:
if tmp[q[0]][0] == tmp[q[1]][0]:
result.append(tmp[q[0]][1] / tmp[q[1]][1])
continue
result.append(-1.0)
# print(result)
return result
考点:
1、两两之间可以随意交换,则有关系的两两之间的组成的组,组内均可以随意交换,组的发现使用并查集
2、对组内元素,使用排序之后,由前到后逐个赋值,最后拼接成字符串
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: # 可以互相换位置的组,按照先后排序即可 # 识别是否在一个组里面用 并查集 group = [i for i in range(len(s))] # print(group) def search(x): if not group[x] == x: group[x] = search(group[x]) return group[x] def union(x, y): xx = search(x) yy = search(y) if xx > yy: group[xx] = yy else: group[yy] = xx for pair in pairs: union(pair[0], pair[1]) for i in range(len(s)): search(i) # print(group) index_dict = collections.defaultdict(list) for i in range(len(s)): index_dict[group[i]].append(i) # print(index_dict) result = [0] * len(s) for key,values in index_dict.items(): chs = [] for value in values: chs.append(s[value]) chs.sort() for i in range(len(values)): result[values[i]] = chs[i] return "".join(result)