- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_element.py
More file actions
Latest commit
35 lines (30 loc) · 1.01 KB
/
Copy pathremove_element.py
File metadata and controls
35 lines (30 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Task:
Given an array nums and a value val, remove all instances of that value
in-place and return the new length. Do not allocate extra space for
another array, you must do this by modifying the input array in-place with
O(1) extra memory. The order of elements can be changed. It doesn't matter
what you leave beyond the new length.
>>> nums, val = [3, 2, 2, 3], 3
>>> res = remove_element(nums, val)
>>> res, nums[0:res]
(2, [2, 2])
>>> nums, val = [0, 1, 2, 2, 3, 0, 4, 2], 2
>>> res = remove_element(nums, val)
>>> res, nums[0:res]
(5, [0, 1, 3, 0, 4])
"""
defremove_element(nums, val):
size=len(nums)
index_pre, index_post=0, 0
whileindex_pre<size:
whilenums[index_pre] ==val:
index_pre+=1
ifindex_pre>=size:
returnindex_post
nums[index_post] =nums[index_pre]
index_pre, index_post=index_pre+1, index_post+1
returnindex_post
if__name__=="__main__":
importdoctest
doctest.testmod()