问题:
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.
解答:先排序,后设定两个指针,first指向第一个等于elem的位置,last指向first之后,第一个不等于elem的元素。
first和last之间就是重复的元素elem。
重点注意:
1 因为第一步是寻找数组中等于elem的第一个位置,如果数组中没有该元素,需要特别的处理。
2 如果输入的数组大小为0,直接返回0.
代码:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
if(n == 0)
return 0;
sort(A, A+n);
int first,last;
first = 0;
while(A[first] != elem)
{
++first;
if(first == n)
return n;
}
last = first;
while(A[last] == elem)
++last;
while(last != n)
A[first++] = A[last++];
return n - (last - first);
}
};
本文介绍了一种在数组中移除指定值并返回新长度的算法。通过排序及双指针技术实现,确保了操作效率。文章详细解释了算法流程,并提供了一段C++代码示例。

1822

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



