[英]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.