remove element
1. Topic
Leetcode link
Given you an array nums and a value val, you need to remove all elements whose value is equal to val in place , and return the new length of the removed array.
Don't use extra array space, you have to use only O(1) O(1)O ( 1 ) extra space and modifies the input array in-place.
The order of elements can be changed. You don't need to consider elements in the array beyond the new length.
Example 1: Given nums = [3,2,2,3], val = 3, the function should return the new length 2, and the first two elements in nums are both 2. You don't need to consider elements in the array beyond the new length.
Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, the function should return the new length 5, and the first five elements in nums are 0, 1, 3, 0, 4.
2. Idea
2.1 Violent solution
The violent solution to this problem is two layers of for loops, one for loop traverses the array elements, and the second for loop updates the array.
- Time complexity: O ( n 2 ) O(n^2)O ( n2)
- Space complexity: O ( 1 ) O(1)O(1)
2.2 Double pointer method
The fast pointer traverses the array, and the slow pointer updates the array
- Time complexity: O ( n ) O(n)O ( n )
- Space complexity: O ( 1 ) O(1)O(1)
3. Code implementation
3.1 Violent solution
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
// 循环遍历数组元素
for (int i = 0; i < size; i++){
if (nums[i] == val){
// 循环更新数组元素
for(int j = i + 1; j < size; j++){
nums[j - 1] = nums[j]; // 注意这里需要更新(删除)的元素从i位置开始
}
// 删除一个元素之后,数组的长度-1, (i+1)位置的元素移到了i位置
i--;
size--;
}
}
return size;
}
};
3.2 Double pointer method
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int fastIndex = 0;
int slowIndex;
// fastIndex遍历数组元素
for (slowIndex = 0; fastIndex < nums.size(); fastIndex++){
if(nums[fastIndex] != val){
// slowIndex更新数组元素
nums[slowIndex] = nums[fastIndex];
slowIndex++;
}
}
return slowIndex;
}
};