[英]Find missing elements in a list created from a sequence of consecutive integers with duplicates in O(n)
这是一个来自 LeetCode 的Find All Numbers Disappeared in an Array问题:
给定一个整数数组,其中
1 ≤ a[i] ≤ n (n = size of array)
,某些元素出现两次,而其他元素出现一次。查找
[1, n]
所有未出现在此数组中的元素。你能在没有额外空间和 O(n) 运行时完成吗? 您可以假设返回的列表不算作额外空间。
例子:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
我的代码如下 - 我认为它是 O(N) 但面试官不同意
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
results_list=[]
for i in range(1,len(nums)+1):
if i not in nums:
results_list.append(i)
return results_list
您可以实现一个算法,在该算法中循环遍历列表的每个元素,如果列表包含元素 i 作为值之一,则将索引 i 处的每个元素设置为负整数。 然后,您可以将每个索引 i 添加到您的缺失项目列表中。 它不占用任何额外空间,最多使用 3 个 for 循环(非嵌套),这使得复杂度为 O(3*n),基本上为 O(n)。 该站点对其进行了更好的解释,并且还提供了源代码。
编辑- 我已经添加了代码以防有人想要它:
#The input list and the output list
input = [4, 5, 3, 3, 1, 7, 10, 4, 5, 3]
missing_elements = []
#Loop through each element i and set input[i - 1] to -input[i - 1]. abs() is necessary for
#this or it shows an error
for i in input:
if(input[abs(i) - 1] > 0):
input[abs(i) - 1] = -input[abs(i) - 1]
#Loop through the list again and append each positive value to output list
for i in range(0, len(input)):
if input[i] > 0:
missing_elements.append(i + 1)
对我来说,使用循环并不是最好的方法,因为循环会增加给定问题的复杂性。 你可以尝试用集合来做。
def findMissingNums(input_arr):
max_num = max(input_arr) # get max number from input list/array
input_set = set(input_arr) # convert input array into a set
set_num = set(range(1,max(input_arr)+1)) #create a set of all num from 1 to n (n is the max from the input array)
missing_nums = list(set_num - input_set) # take difference of both sets and convert to list/array
return missing_nums
input_arr = [4,3,2,7,8,2,3,1] # 1 <= input_arr[i] <= n
print(findMissingNums(input_arr)) # outputs [5 , 6]```
在 Python 中使用哈希表或字典:
def findDisappearedNumbers(self, nums):
hash_table={}
for i in range(1,len(nums)+1):
hash_table[i] = False
for num in nums:
hash_table[num] = True
for i in range(1,len(nums)+1):
if not hash_table[i]:
print("missing..",i)
尝试以下操作:
a=input() #[4,3,2,7,8,2,3,1]
b=[x for x in range(1,len(a)+1)]
c,d=set(a),set(b)
print(list(d-c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.