class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ for i in xrange(len(nums)-1, -1, -1): if nums[i] == val: nums.pop(i) return len(nums)
@StefanPochmann If you mean "Why don't you just pop as you go," in my experience, popping from a list while iterating over it is problematic. If you mean "Why not just use the remove method," I chose not to do that because it's O(n), so if all of the values to be deleted are at the end of the list, the performance is bad. I'd be happy to learn if you have a better suggestion, or if you think these reasons are not good.
"in my experience, popping from a list while iterating over it is problematic"
Not if you go backwards like you're already doing.
"I chose not to [use the remove method] because it's O(n)"
The pop method is also only O(n).
But what I meant was "pop as you go". I think it's quite a bit better.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.