算法-数组:移除元素
原地移除数组中所有等于val的元素,要求不能使用额外的辅助空间,即空间复杂度为O(1),返回移除元素后新数组的size。
#include <iostream>
#include <vector>
using namespace std;
//注意:数组中的元素在内存地址上是连续的,不能单独删除数组中的某个元素,只能覆盖!!!
//方法一:暴力解法,使用两个for,一个用于循环遍历,一个用于覆盖更新数组
int method(vector<int>& nums,int target){
int n = nums.size();
for(int i = 0; i < n; i++){
if(target == nums[i]){
for(int j = i+1; j < n; j++){
nums[j-1] = nums[j];
}
i--;//因为数组向前移了一位,所以下标也要向前移一位
n--;
}
}
return n;
}
int main(){
int n;//数组长度
cin>>n;
vector<int> nums;
int num;
for(int i = 0; i < n; i++){
cin>>num;
nums.push_back(num);
}
int target;
cin>>target;
cout<<"数组长度为:"<<method(nums,target);
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
//注意:数组中的元素在内存地址上是连续的,不能单独删除数组中的某个元素,只能覆盖!!!
//方法二:双指针法,使用一个快指针和一个慢指针在一个for里,快指针用于遍历,慢指针用于覆盖满足要求的数组
int method(vector<int>& nums,int target){
int n = nums.size();
int slow = 0;
for(int fast = 0; fast < n; fast++){
if(target != nums[fast]){
nums[slow++] = nums[fast];
}
}
return slow;
}
int main(){
int n;//数组长度
cin>>n;
vector<int> nums;
int num;
for(int i = 0; i < n; i++){
cin>>num;
nums.push_back(num);
}
int target;
cin>>target;
cout<<"数组长度为:"<<method(nums,target);
return 0;
}