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.总结
不开辟另外的数组,在原数组上进行去重。
该博客讨论了如何在LeetCode中解决一个问题,即在不使用额外空间的情况下,从给定数组中移除特定值并返回新数组的长度。提供了两种不同的解决方案,时间复杂度均为O(n),空间复杂度为O(1)。方法一通过遍历数组并将非目标值元素移到正确位置,方法二利用C++STL中的distance和remove函数实现。

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



