我是一名學生,正在學習資料結構和演算法。我無法解決或縮短這個 GFG 問題。
陣列中缺少數字
給定一個大小為 N-1 的陣列,它只包含 1 到 N 范圍內的不同整數。找到缺失的元素。
我嘗試了這段代碼,但它不適用于所有情況。
def MissingNumber(self,array,n):
missingNumber = 0
for i in range(len(array)):
if array[i] !=i 1:
missingNumber = i 1
return missingNumber

Input:
N = 5
A[] = {1,2,3,5}
Output: 4
請幫助我解決最復雜的代碼。提前致謝。
uj5u.com熱心網友回復:
我不知道這是否是解決這個問題的最佳方法,但這是我的代碼分別具有 O(N) 時間復雜度和 O(1) 空間復雜度。這是我的代碼。希望這可以幫助你。
def MissingNumber(self,array,n):
# The expected sum of the complete array should be ...
expectedSum = (n*(n 1)) //2
total = 0
for i in array:
total =i
# check the difference between expected sum and actual sum of an array that's the missing number in an array.
return expectedSum-total
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508742.html
標籤:Python算法
