2024.1.22【数组】2.移除元素
- 函数erase():时间复杂度 O(n)
- 数组:元素在内存地址中是连续的,不能单独删除某个元素,只能 覆盖。
解法1:暴力解法
//两层for循环,一个for循环遍历数组元素 ,第二个for循环更新数组
// 时间复杂度:O(n^2)
// 空间复杂度:O(1)
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--; // 因为下标i以后的数值都向前移动了一位,所以i也向前移动一位
size--; // 此时数组的大小-1
}
}
return size;
}
};
解法2:双指针法(快慢指针法)
// 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
// 慢指针:指向更新 新数组下标的位置
// 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0;
for (int fast = 0; fast < nums.size(); fast++) {
if (val != nums[fast]) {
nums[slow] = nums[fast];
slow ++;
}
}
return slow; //slow 即新数组的长度
}
};
练习1
//题目要求:原地修改;解法:双指针
//空间复杂度:O(n)
//空间复杂度:O(1)
class Solution{
public:
int removeDuplicates(vector<int>& nums) {
int index = 0;
for (int i = 1; i < nums.size(); i++) {
//找到不重复的元素,赋值到数组的开头
if (nums[i] != nums[index]) {
nums[++index] = nums[i];//index先自加1,再进行语句的赋值
}
}
return index + 1;
}
};
官方答案:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if (n == 0) {
return 0;
}
int fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
};
若采用暴力解法,时间复杂度O(n),空间复杂度O(n)