leetcode: 27. Remove Element
方法一:暴力,时间复杂度O(n^2)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
for (int i = 0; i < n; i++) {
if (nums[i] == val) {
for (int j = i + 1; j < n; j++)
nums[j - 1] = nums[j];
n--;
i--; // 用于两个val连续出现的情况
}
}
return n;
}
};
方法二:快慢指针,时间复杂度O(n)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (nums[fastIndex] != val) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};