Skip to content

Commit cc045b3

Browse files
Question 27
1 parent e728cd4 commit cc045b3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

27. Remove Element.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''
2+
Given an array nums and a value val, remove all instances of that value in-place and
3+
return the new length.
4+
Do not allocate extra space for another array, you must do this by modifying the input
5+
array in-place with O(1) extra memory.
6+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
7+
8+
Example 1:
9+
Given nums = [3,2,2,3], val = 3,
10+
Your function should return length = 2, with the first two elements of nums being 2.
11+
It doesn't matter what you leave beyond the returned length.
12+
13+
Example 2:
14+
Given nums = [0,1,2,2,3,0,4,2], val = 2,
15+
Your function should return length = 5, with the first five elements of nums containing
16+
0, 1, 3, 0, and 4.
17+
Note that the order of those five elements can be arbitrary.
18+
19+
It doesn't matter what values are set beyond the returned length.
20+
21+
Clarification:
22+
Confused why the returned value is an integer but your answer is an array?
23+
Note that the input array is passed in by reference, which means modification to the
24+
input array will be known to the caller as well.
25+
Internally you can think of this:
26+
27+
// nums is passed in by reference. (i.e., without making a copy)
28+
int len = removeElement(nums, val);
29+
30+
// any modification to nums in your function would be known by the caller.
31+
// using the length returned by your function, it prints the first len elements.
32+
for (int i = 0; i < len; i++) {
33+
print(nums[i]);
34+
}
35+
'''
36+
37+
class Solution:
38+
def removeElement(self, nums, val):
39+
l = 0
40+
for i in range(len(nums)):
41+
if nums[i]!=val:
42+
nums[l]=nums[i]
43+
l += 1
44+
return l

0 commit comments

Comments
 (0)