您的位置:首页 > 其它

LeetCode:Remove Element(删除数组中的特定元素)

2015-02-03 15:45 351 查看
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.

方法1:一次遍历,遍历过程中如果遇到需要删除的元素,就将此位置的元素与数组末端元素交换。

class Solution {
public:
int removeElement(int A[], int n, int elem) {
if(A==NULL || n<1)
return 0;
int i=0;
while(i<n){
if(A[i]==elem)
//swap(A[i],A[--n]);可以不理会末端的值,将swap优化为直接赋值
A[i] = A[--n];
else
++i;
}
return n;
}
};


方法2:使用双指针解决,在快指针遍历数组的过程中,如果当前元素不等于需要删除的元素,则将此元素复制到慢指针所指位置。

class Solution {
public:
int removeElement(int A[], int n, int elem) {
if(A==NULL || n<1)
return 0;
int slow = -1, fast = -1;
while(++fast<n){
if(A[fast]!=elem)
A[++slow] = A[fast];
}
return slow+1;
}
};


两种方法的时间复杂度均是O(n),方法1适用于数组中需要删除的元素较少的情况,而方法2适用于数组中需要删除的元素较多的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐