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(int A[], int n, int elem) {
if(n==0)
return 0;
int *p=&A[0];
int *q=&A[n-1];
while(q>=p)
{
if(*p==elem)
{
if(*q==elem)
{
q--;
}
else
{
*p=*q;
q--;
p++;
}
n--;
}
else
{
p++;
}
}
return n;
}
};class Solution {
public:
int removeElement(int A[], int n, int elem) {
if(A==NULL)
return 0;
for(int i=0;i<n;)
{
if(A[i]==elem)
{
swap(A[i],A[n-1]);
n--;
}
else
i++;
}
return n;
}
};
本文介绍了一种在数组中移除指定值并返回新长度的算法实现。该算法通过双指针技术,有效地将目标值从数组中移除,并允许元素顺序变化。文章提供了两种不同的C++实现方案。
623

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



