前情提要:在养成写一些博客的习惯,同时练习英文表述和分析问题的能力,所以内容均为英文。
Problem statement(leetcode 27):
Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The order of the elements may be changed. Then return the number of elements in nums
which are not equal to val
.
Consider the number of elements in nums
which are not equal to val
be k
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
Problem Discussion:
The keyword for this problem is "in-place," which means you need to solve it without using extra space. In-place algorithms modify the input data structure directly, without requiring additional memory allocation.
The spirit of my solution is to create two "pointers" (not actual pointers, but rather indices) that point to different indices of the vector, both starting from index 0. The "slow" pointer keeps track of the position where the next non-target element should be placed, while the "fast" pointer iterates through the array to find non-target elements.
How this work:
- Initialize two pointers,
slow
andfast
, both pointing to index 0. - Iterate through the array using the
fast
pointer:
- Copy the fast element to the position pointed to by theslow
pointer, and increment theslow
pointer.
- Increment thefast
pointer regardless of whether the element is equal toval
or not.
Time: O(n)
Space: O(1)
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int fast = 0, slow = 0, counter = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != val) {
nums[slow] = nums[fast];
slow++;
counter++;
}
fast++;
}
return counter;
}
};