Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9106bf9

Browse files
committed
Create remove_elements.py
1 parent 8e30069 commit 9106bf9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎arrays_hashing/remove_elements.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# You are given an integer array nums and an integer val. Your task is to remove all occurrences of val from nums in-place.
2+
# After removing all occurrences of val, return the number of remaining elements, say k, such that the first k elements of nums do not contain val.
3+
# Note:
4+
# The order of the elements which are not equal to val does not matter.
5+
# It is not necessary to consider elements beyond the first k positions of the array.
6+
# To be accepted, the first k elements of nums must contain only elements not equal to val.
7+
# Return k as the final result.
8+
# Example :
9+
# Input: nums = [1,1,2,3,4], val = 1
10+
# Output: [2,3,4]
11+
12+
# Method 1: (Brute Force)
13+
class Solution:
14+
def removeElement(self, nums: list[int], val: int) -> int:
15+
tmp = []
16+
for num in nums:
17+
if num == val:
18+
continue
19+
tmp.append(num)
20+
21+
for i in range(len(tmp)):
22+
nums[i] = tmp[i]
23+
24+
return len(tmp)
25+
26+
# Method 2: (Two Pointers)
27+
class Solution:
28+
def removeElement(self, nums: list[int], val: int) -> int:
29+
k = 0
30+
for i in range(len(nums)):
31+
if nums[i] != val:
32+
nums[k] = nums[i]
33+
k += 1
34+
return k

0 commit comments

Comments
 (0)