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) {
vector<int>a;
for(int i=0;i<nums.size();i++)
{
if(nums[i]!=val)
a.push_back(nums[i]);
}
nums=a;
return a.size();
}
};
别人的答案:
int rm(vector<int> &arr, int value)
{
int cnt=0;
for(int i=0; i<arr.size(); i++)
{
if(arr[i]==value) cnt++;
else if (cnt>0)
{
arr[i-cnt] = arr[i];
}
}
return size-cnt;
}
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (n == 0 ) return 0;
int len = n;
for (int i = 0, pos = 0; i < n; ++i)
{
if (A[i] == elem)
--len;
else
A[pos++] = A[i];
}
return len;
}
};
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (n == 0 ) return 0;
int len = n;
for (int i = 0, pos = 0; i < n; ++i)
{
if (A[i] == elem)
--len;
else
A[pos++] = A[i];
}
return len;
}
};
Remove Element(删除数组某一元素)
最新推荐文章于 2022-11-26 13:24:24 发布
本文探讨了如何在数组中删除特定元素的方法,包括不同编程语言的实现技巧和效率分析,帮助开发者掌握这一常见操作。
&spm=1001.2101.3001.5002&articleId=48750723&d=1&t=3&u=cc4a5fb68e024660b4b6257082dd3eef)
1158

被折叠的 条评论
为什么被折叠?



