题目链接:https://leetcode.com/problems/remove-element/
Runtimes:6ms
1、问题
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、分析
删除A数组中所有elem的数字,并且返回数组长度。为了降低复杂度,有个小技巧就是讲出现的数字elem换到数组尾部即可~
3、小结
应该返回i值而不是j值,测试用例没有执行完成就submit,不认真哟~
4、实现
class Solution {
public:
int removeElement(int A[], int n, int elem) {
if (n <= 0)
return 0;
int j = n - 1, i = 0;
for (; i <= j;)
{
while (i <= j && A[i] != elem)
{
++i;
}
if (i > j)
break;
if (A[i] == elem)
{
A[i] = A[j];
--j;
}
}
return i;
}
};
5、反思
题目简单,效果不错~