Skip to content

Commit 3eae7ef

Browse files
authored
Remove Element Function
1 parent edf507b commit 3eae7ef

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

remove-Element/removeElement.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#include <vector>
2+
class solution{
3+
public:
4+
int removeElement(std::vector<int>& nums, int val){
5+
int k = 0;
6+
for(int i = 0; i < nums.size(); i++){
7+
if(nums[i] != val){
8+
nums[k] = nums[i];
9+
k++;
10+
}
11+
}
12+
return k;
13+
}
14+
};

remove-Element/removeElement.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Remove Element Function
2+
3+
This repository contains a C++ implementation of the `removeElement` function, which removes all occurrences of a specified value from a vector and returns the new length of the vector.
4+
5+
## Function Explanation
6+
7+
- **Function Name**: `removeElement`
8+
- **Parameters**:
9+
- `std::vector<int>& nums`: The input vector of integers.
10+
- `int val`: The value to be removed from the vector.
11+
- **Return Type**: `int`
12+
- The function returns the new length of the vector after removing all instances of `val`.
13+
14+
### Algorithm
15+
The function iterates through the vector and copies each element that is not equal to `val` to the beginning of the vector. It uses a pointer `k` to keep track of the position where the next non-val element should be placed. At the end of the iteration, `k` will be the length of the new vector with all instances of `val` removed.
16+
17+
## Usage
18+
19+
To use this function, include it in your C++ project and call `removeElement` by passing the vector and the value to be removed.
20+
21+
## Example
22+
23+
```cpp
24+
std::vector<int> nums = {3, 2, 2, 3};
25+
int val = 3;
26+
solution sol;
27+
int newLength = sol.removeElement(nums, val);
28+
// The result will be `newLength = 2`, and `nums` will be modified to {2, 2}.

0 commit comments

Comments
 (0)