arrays - LeetCode 查找数组中所有消失的数字问题

标签 arrays algorithm

我正在做的问题陈述如下:

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

我找到了一个相当快地占用 O(n) 空间的解决方案,但是这个问题有一个找到恒定空间解决方案的条件,并且我不理解给出的解决方案。此处重新创建恒定空间解决方案,如下所示:

    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
                
        # Iterate over each of the elements in the original array
        for i in range(len(nums)):
            
            # Treat the value as the new index
            new_index = abs(nums[i]) - 1
            
            # Check the magnitude of value at this new index
            # If the magnitude is positive, make it negative 
            # thus indicating that the number nums[i] has 
            # appeared or has been visited.
            if nums[new_index] > 0:
                nums[new_index] *= -1
        
        # Response array that would contain the missing numbers
        result = []    
        
        # Iterate over the numbers from 1 to N and add all those
        # that have positive magnitude in the array 
        for i in range(1, len(nums) + 1):
            if nums[i - 1] > 0:
                result.append(i)       
        return result     

我不明白这段代码是如何工作的。对我来说,似乎每个元素在第一遍中都会被设为负数,因此不会将任何值附加到答案列表中。我通过调试器运行它,似乎并不是发生了什么。我希望有人能向我解释它在做什么。

最佳答案

举个例子:

nums = [4,3,2,7,8,2,3,1]

现在让我们迭代它,

Index-1: Value = 4 -> 将 (Value - 1) -> (4-1) 索引元素标记为负,前提是该元素为正。

现在,nums = [4,3,2,-7,8,2,3,1]

在此对每个索引执行此操作,

你会看到这个:

nums = [-4,-3,-2,-7,8,2,-3,-1]

索引 = 4 和索引 = 5 处的元素为正。

所以,答案是 [4+1,5+1] = [5,6]。


希望你明白这一点🔑。

关于arrays - LeetCode 查找数组中所有消失的数字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67851954/

相关文章:

algorithm - 初始解接近最优的多元函数优化

image - 在灰度图像中找到十字的算法

c# - 比较两个数组并返回它们的余数

c - 非常基本,尝试从带有数字的文本文件中读取并将它们存储在数组中

java - JNI 中的二维数组

algorithm - 强调实用细节的 C4.5 和 ID3 算法

javascript - 如何将 3d 数组转换为 2d 数组

java - 我的扫雷器 dot java 出了什么问题

c++ - STL字符串比较方法与手动编写的方法之间存在巨大的时间差异

R:识别相邻单元格的簇(0-1 值的二维矩阵中的连续区域)