交换操作后最小化汉明距离

问题描述

我正在尝试解决 Leetcode problem #1722。我的直觉是

  1. 使用联合查找对源数组中可以相互交换的一组数字进行分组。
  2. 保持源数组中的数字计数。 (比如node --version v15.14.0
  3. 对于 count_map 数组中的每个索引 i (a_i,b_i)。其中 (source,target)a_i 中的元素,source 是索引 b_itarget 中的元素。如果 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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...