Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int x[100];
int length = nums.size();
int j = 0;
for (int i = 0; i < length; i++){
if (nums[i] != val) {
x[j] = nums[i];
j++;
}
}
nums.clear();
for(int i = 0; i< j; i++){
nums[i] = x[i];
}
return j;
}
};
也可以再建立一个vector容器,帮助实现功能;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
vector<int > x;
int length = nums.size();
int j = 0;
for (int i = 0; i < length; i++){
if (nums[i] != val) {
x.push_back(nums[i]);
j++;
}
}
nums.clear();
for(int i = 0; i< j; i++){
nums[i] = x[i];
}
return j;
}
};