題目描述從排序數組中刪除重復項題目來源及自己的思路我用這個代碼實現從排序數組中刪除重復項,就是LeetCode上的算法題,我先用for循環寫,感覺思路沒問題,但一直報錯IndexError: list index out of range,后來查了下答案,只是把for改成了while,然后就通過了檢查。這個是不是因為for循環range()函數中只會在第一次調用時計算len(nums),之后range的值就不會改變了。相關代碼// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)這是for循環的:1 nums = [1,1,1,2,3,1,1]2 count = 03 if len(nums) == 1 or len(nums) == 0:4 count = len(nums)5 else:6 for i in range(len(nums)-1):7 print(len(nums))8 if nums[i] == nums[i+1]:9 del nums[i+1]10 else:11 count += 112 13 print(count)error : IndexError: list index out of range這是while正確的版本:class Solution:def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
if len(nums) == 1 or len(nums) == 0: return len(nums) else: while i < (len(nums)-1):
if nums[i] == nums[i+1]: del nums[i+1] else:
i += 1
return你期待的結果是什么?實際看到的錯誤信息又是什么?還有一個小問題,我的while的代碼,最后只寫了return也能返回正確的結果,這是什么原因?是不是因為LeetCode他幫我補上了?新手,只學了下基礎語法,有些地方搞不清楚,多謝各位大佬了!
添加回答
舉報
0/150
提交
取消