topic description
remove duplicates from the sorted array
sources of topics and their own ideas
I use this code to remove duplicates from the sorted array, which is the algorithm problem on LeetCode. I first use the for loop to write, and I feel that the train of thought is fine, but I always reported an error IndexError: list index out of range, and then checked the answer. I just changed for to while, and then passed the check. Is this because the for loop range () function only evaluates len (nums), on the first call and the value of range does not change.
related codes
/ / Please paste the code text below (do not replace the code with pictures)
this is the for loop:
1 nums = 1]
2 count = 0
3 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 [iTunes 1]:
9 del nums
10 else:
11 count + = 1
12
13 print (count)
error: IndexError: list index out of range
this is the correct version of 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
what result do you expect? What is the error message actually seen?
there is also a small problem, my while code, finally only wrote return can return the correct result, what is the reason? Is it because of LeetCode that he made it up for me? Novice, only learned the basic grammar, some places are not clear, thank you!