Skip to content

Commit 49246ba

Browse files
committed
D. J.:
- Added leetcode problem and solution for 27. Remove Element
1 parent 0adf523 commit 49246ba

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def removeElement(self, nums: List[int], val: int) -> int:
6+
"""
7+
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place.
8+
The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
9+
10+
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
11+
- Change the array nums such that the first k elements of nums contain the elements which are not equal to val.
12+
The remaining elements of nums are not important as well as the size of nums.
13+
- Return k.
14+
"""
15+
left, right, length = 0, len(nums) - 1, 0
16+
while left <= right:
17+
if nums[right] == val:
18+
right -= 1
19+
elif nums[left] == val:
20+
nums[left], nums[right] = nums[right], nums[left]
21+
left += 1
22+
right -= 1
23+
length += 1
24+
else:
25+
left += 1
26+
length += 1
27+
return length

tests/test_27_remove_element.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._27_remove_element import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "val", "expected"],
10+
argvalues=[
11+
([3, 2, 2, 3], 3, [2, 2]),
12+
([0, 1, 2, 2, 3, 0, 4, 2], 2, [0, 1, 4, 0, 3]),
13+
],
14+
)
15+
def test_func(nums: List[int], val: int, expected: List[int]):
16+
length = Solution().removeElement(nums, val)
17+
assert nums[:length] == expected

0 commit comments

Comments
 (0)