881655. Remove from vector
Basic
Remove from Vector
Summary
Given a vector and an integer, remove all occurrences of that integer from the vector. This problem is about manipulating a vector (a dynamic array) using Standard Template Library (STL) algorithms.
Detailed Explanation
The problem can be solved by iterating through the vector and removing elements that match the given integer. We'll use the erase method to remove elements, which returns an iterator pointing to the element following the removed one.
Here's a step-by-step breakdown of the solution:
- Iterate through the vector using an iterator.
- For each element, check if it matches the given integer.
- If it does, use the
erasemethod to remove that element from the vector. This will shift all subsequent elements down by one position. - Repeat steps 2-3 until the end of the vector is reached.
Time complexity analysis: O(n), where n is the size of the vector, because we're iterating through each element once.
Space complexity analysis: O(1), because we're not using any extra space that scales with the input size.
Optimized Solutions
Java
public static void removeFromVector(int[] arr, int num) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
arr = Arrays.copyOfRange(arr, 0, i);
arr = Arrays.copyOfRange(arr, i + 1, arr.length);
i--; // adjust the loop variable
}
}
}