Reputation: 13
i practice a test of "Remove Duplicates from Sorted Array" in leetcode.Everything is fine but when i test input[1,1] ,it failed with:
IndexError: list index out of range
May i know why?(i already got a correct solution but i still wonder this error.)
here is my code:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
index_o=0
i=1
while i <len(nums):
if nums[index_o]==nums[i]:
nums.remove(nums[i])
index_o-=1
i-=1
print("nums[index_o]:",nums[index_o])
print("index_o:",index_o)
print("nums[i]:",nums[i])
print("i:",i)
print("nums:",nums)
else:
index_o+=1
i+=1
return len(nums)
n=[1,1]
a=Solution()
print(a.removeDuplicates(n))
print(n)
here is the result:
f:leetcode>python 190626.py
nums[index_o]: 1
index_o: -1
nums[i]: 1
i: 0
nums: [1]
Traceback (most recent call last):
File "190626.py", line 228, in <module>
print(a.removeDuplicates(n))
File "190626.py", line 217, in removeDuplicates
print("nums[index_o]:",nums[index_o])
IndexError: list index out of range
here is a correct solution:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
index_o=0
i=1
while i <len(nums):
if nums[index_o]==nums[i]:
nums.remove(nums[index_o])
else:
index_o+=1
i+=1
return len(nums)
Upvotes: 1
Views: 235
Reputation: 33
When the first time arrives to execute the while
loop and the statement of if
is true, then the variable index_o
will take the value -1, the variable i
will be 0 and the while
loop will be run again as i=0 < len(nums)=1
. So the next time, if
statement will check if nums[-1] == nums[0]
which is out of index. I suggest you to add an if
statement just to make sure your array pointers will not get negative values.
Upvotes: 0
Reputation: 1375
In the third iteration of the loop, you have the variables i=-1
and n=[]. Your code enters to first if
as -1 < 0
equals True
.*
At this point you try to access your array with the variable index_o
, which is -2. Because your array is empty, n[-2] returns IndexError: list index out of range
error.
Some comments on your code:
- The algorithm does not do what it supposed to do but I can understand your thinking.
- Why would remove duplicates function would return the length of the output array, and not the array itself ?
- To test that algorithm, you can use the set()
built-in, that will remove the duplicates from an array. Then you can compare them.
- When developing algorithms, always use debugging by printing the values, as advised by @Mark-meyer in the comments.
*I didn't run your algorithm locally and debugged, I just tracked it from head. So some values might be off by one.
Upvotes: 1