問題:https ://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
基本上,排序陣列中的重復項需要在不創建新陣列的情況下洗掉。我已經測驗了我的解決方案,當有 3、5、7(等等)相同數量的重復項時,它會動搖。請給我一些見解。我不知道這是問這個問題的好地方,還是其他任何地方問這個問題的好地方。任何更多相關的建議表示贊賞。謝謝你。
代碼:
def removeDuplicates(nums):
i = 0 # moving pointer
end = len(nums)-1 # points to the end of the array
# iterates over the array
while i != end:
# if current number is equal to the next
if (nums[i] == nums[i 1]):
# pop it off
nums.pop(i)
# decrement the length of array
end -= 1
i = 1 # increments the moving pointer
return i 1
nums = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicates(nums))
uj5u.com熱心網友回復:
在 O(1) 空間和 O(n) 時間內從排序串列中洗掉重復項的方法是將唯一元素打包在串列的開頭,然后截斷串列:
def removeDuplicates(nums):
#new length
newlen = 0
for val in nums:
if newlen == 0 or nums[newlen-1] != val:
# no matter what, we've already retrieved nums[newlen],
# so this write doesn't interfere with the rest of the loop
nums[newlen] = val
newlen = 1
# delete the unused space at the end of the list, all at once
if newlen < len(nums):
del nums[newlen:]
return newlen
nums = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicates(nums))
print(nums)
您的原始代碼失敗,因為您在迭代結束時從陣列的開頭洗掉了元素。迭代會記住它在陣列中的位置i,當你洗掉一個元素時,它后面的元素會被移動到較低的位置。
您可以通過將i = 1放入 a來解決此問題else,但生成的實作仍需要 O(N^2) 時間,這實際上是不可接受的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514848.html
上一篇:均勻分布演算法
下一篇:如何解決串列索引超出范圍的錯誤?
