Leetcode: Remove Element
1 min readDec 23, 2016
We need to remove the given element and shift the rest of the elements.
- Initialize index at 0
- Fill all the elements except the input number while increasing the index
Remarks:
- O(1) space complexity
- O(n) time complexity
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
j = 0
for n in nums:
if n != val:
nums[j] = n
j += 1
return j