如何解决交换操作后最小化汉明距离
我正在尝试解决 Leetcode problem #1722。我的直觉是
- 使用联合查找对源数组中可以相互交换的一组数字进行分组。
- 保持源数组中的数字计数。 (比如
node --version v15.14.0
) - 对于
count_map
数组中的每个索引i
(a_i,b_i)
。其中(source,target)
是a_i
中的元素,source
是索引b_i
中target
中的元素。如果 a_i 和 b_i 的父母相同,则它们在同一组中。我从i
中减少了元素b_i
的数量。由于此元素用于在当前位置交换。
代码:
count_map
我能想出的大多数测试用例都通过了,但是,当我提交时,我有一个失败的测试用例。我无法找出逻辑中的错误。我的方法与所有提交的内容不同,所以我在这里怀疑我的方法。你们看到我的逻辑有缺陷吗?
class Solution:
def minimumHammingdistance(self,source: List[int],target: List[int],allowedSwaps: List[List[int]]) -> int:
res = len(source)
# Step-1: Use UF to group numbers in source list that can be grouped together
num_set = set(source)
uf = UF(num_set,source,allowedSwaps)
# Step-2: Maintain a count of all numbers in the sources list
count_map = collections.Counter(source)
for a,b in zip(source,target):
# b is not an element in source,so we ignore.
if b not in count_map:
continue
# Both a & b have same parent,then they are part of the same group.
if uf.find(a) == uf.find(b):
# Reduce the count of element b,since we are using it to swap at the current location
if count_map[b] > 0:
count_map[b] -= 1
res -= 1
return res
class UF:
def __init__(self,num_set,swaps):
self.parents = {i:i for i in num_set}
self.ranks = {i:1 for i in num_set}
# Step-1: Union numbers that can be swapped with each other from the sources arr.
for a,b in swaps:
self.union(source[a],source[b])
def find(self,p):
while p != self.parents[p]:
self.parents[p] = self.find(self.parents[p])
p = self.parents[p]
return p
def union(self,p,q):
parent_p = self.find(p)
parent_q = self.find(q)
if parent_p == parent_q: return
if self.ranks[parent_p] >= self.ranks[parent_q]:
self.parents[parent_q] = parent_p
if self.ranks[parent_p] == self.ranks[parent_q]:
self.ranks[parent_p] += 1
else:
self.parents[parent_p] = parent_q
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。