题目
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并原地修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。
示例 2: 给定 nums = [0,1,2,2,3,0,4,2], val = 2, 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0;
for (int fast = 0; fast < nums.size(); fast++) {
if (nums[fast] != val) {
nums[slow++] = nums[fast];
}
}
return slow;
}
};
慢指针永远指向自己需要的,满足条件的元素。
知识点:数组的地址的元素是连续的,不能移除,只能覆盖。
类似题目LeetCode26
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return 1;
int slowIndex = 1;
for(int fastIndex = 1; fastIndex < nums.size(); fastIndex++) {
if (nums[fastIndex] != nums[fastIndex-1]) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};
LeetCode283-移动零
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int slowIndex = 0;
int n = nums.size();
for (int fastIndex = 0; fastIndex < n; fastIndex++) {
if (nums[fastIndex] != 0) {
nums[slowIndex++] = nums[fastIndex];
}
}
for (slowIndex ;slowIndex < n; slowIndex++) {
nums[slowIndex] = 0;
}
}
};
LeetCode844-比较含退格符的字符串
class Solution {
public:
bool backspaceCompare(string s, string t) {
int len1 = s.size();
int len2 = t.size();
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < len1; fastIndex++) {
if (s[fastIndex] != '#') {
s[slowIndex++] = s[fastIndex];
}
else {
if (slowIndex != 0) {
slowIndex--;
}
}
}
string str1 = s.substr(0,slowIndex);
slowIndex = 0;
for (int fastIndex = 0; fastIndex < len2; fastIndex++) {
if (t[fastIndex] != '#') {
t[slowIndex++] = t[fastIndex];
}
else {
if (slowIndex != 0) {
slowIndex--;
}
}
}
string str2 = t.substr(0,slowIndex);
return str1 == str2;
}
};
注意:当slowIndex为0的时候它不能减一。
时间复杂度为O(N)
空间复杂度为O(1)