forked from Ritesh25696/interviewBit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove Element from Array
More file actions
33 lines (27 loc) · 891 Bytes
/
Remove Element from Array
File metadata and controls
33 lines (27 loc) · 891 Bytes
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
Remove Element
Given an array and a value, remove all the instances of that value in the array.
Also return the number of elements left in the array after the operation.
It does not matter what is left beyond the expected length.
Example:
If array A is [4, 1, 1, 2, 1, 3]
and value elem is 1,
then new length is 3, and A is now [4, 2, 3]
Try to do it in less than linear additional space complexity.
**********************************************************************************************************************
int Solution::removeElement(vector<int> &A, int B) {
vector<int> res;
int start = 0;
int index = 0;
while(A[start] == B && start<A.size())start++;
if(start == A.size())return 0;
A[index]=A[start];
index++;
start++;
for(int i=start ;i<A.size() ; i++){
if(A[i] != B){
A[index] = A[i];
index++;
}
}
return index;
}