Link: https://leetcode.com/problems/remove-element/
Content:
Attention:
- return length
- first n elements, no matter what leave beyond elements
- the order can be arbitrary
Method 1: Two pointers
Algorithm: same with P26
- one pointer cur record the position of array
- second pointer i traverse the whole array
Code:
class Solution:
def removeElement(self,nums,val):
cur = 0
for i in range(len(nums)):
if nums[i] != val:
nums[cur] = nums[i]
cur += 1
return cur
Time complexity:
O(n): if n elements in array, both cur and i traverse 2n at most.
Method 2: Counter (record the number of val)
same with P26
Code:
class Solution:
def removeElement(self,nums,val):
count = 0
for i in range(len(nums)):
if nums[i] == val:
count += 1
else:
nums[i-count] = nums[i]
return len(nums)-count
Method 3: last fill (in the use of the order can be arbitrary)
Algorithm:
- n means the length of nums
- i traverse the whole array, condition (i<n)
- if nums[i] == val, nums[i] = the last number of array, decrease n at the same time, if not, i++
- return n
Code:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
n = len(nums)
i = 0
while i<n:
if nums[i] == val:
nums[i] = nums[n-1]
n -= 1
else:
i += 1
return n
Best situation:
In this approach, the number of assignment operations is equal to the number of elements to remove. So it is more efficient if elements to remove are rare.
Time complexity:
O(n), both i and n traverse at most n times.