1.问题描述
LeetCode:
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.
2.问题分析
从给定的数组中删除给定的值,返回剩余数组的长度。
3.代码
//时间复杂度O(n),空间复杂度O(1)
class Solution
{
public:
int removeElement(int A[], int n, int elem)
{
int index = 0;
for(int i = 0;i < n;++i)
{
if(A[i] != elem)
A[index++] = A[i];
}
return index;
}
//方法2
int removeElement(int A[],int n,int elem)
{
return distance(A,remove(A, A+n, elem));
}
};
4.总结
不开辟另外的数组,在原数组上进行去重。