Remove Element
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.
解题方法:
采用双指针的思想。一个指针用来遍历数组,另个一个指针用于指示当前合法数据的位置。
Code:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int pElem=0;
for(int i=0;i<n;i++)
if(elem!=A[i])
{
A[pElem++]=A[i];
}
return pElem;
}
};
本文介绍了一种使用双指针技巧来移除数组中特定值并返回新长度的方法。通过遍历数组,若元素不等于指定值,则将其移动到数组的合法区域。此算法简单高效,适用于多种编程场景。
433

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



