LeetCode 448 Find the missing number in the array

LeetCode

448 questions

Title description:

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,
另一些只出现一次。找到所有在 [1, n] 范围之间没有出现在数组中的数字。您能在不使用额外空间且时间
复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:
[4,3,2,7,8,2,3,1]
输出:
[5,6]

answer:

Conventional solution: You can use a dictionary to store the information of the array elements first, and then traverse the list of array lengths. If the created dictionary does not have this element, it means that there is no such element in the array, which is also a missing element.

def finddis(nums):
    dic={
    
    }#新建一个字典用来存储元素
    for num in nums:
        dic[num] =1
    ret = []#函数需要返回的结果列表
    for i in range(1,len(nums)):#对数据进行遍历
        if i not in dic:
            ret.append(i)
    return ret

But the title says try to make it without using extra space, so using a dictionary is definitely not enough. It can only be replaced in situ. You can consider the relationship between the array elements and their corresponding positions. Because the length of the array corresponds to the array, you can put the array elements in their corresponding positions, and then traverse the corresponding positions. If the value and If the index value does not correspond, it means that the array does not exist.

def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        res = []
        for i in range(len(nums)):
            while nums[nums[i] - 1] != nums[i]:
                tmp = nums[i]#当前循环进行到的位置的元素
                loc = nums[i] - 1#当前元素应该出在位置的下标
                nums[i] = nums[nums[i] - 1]
                nums[loc] = tmp
        for idx, val in enumerate(nums, 1):#从索引位置开始 ,如果不相等,则说明是没有的值
            if val != idx:
                res.append(idx)
        return res

In fact, it is to determine whether the current element of the array is at the position where the data is minus one. For example, if there is data 4 in the array, then the index value should be 3 under normal circumstances. If it is not, exchange data and use intermediate variables to store the current element, which is easy to understand.

Guess you like

Origin blog.csdn.net/weixin_38389509/article/details/111935529