题目链接: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、反思
题目简单,效果不错~
本文解决了一个LeetCode问题,题目要求从数组中删除指定元素并返回新数组的长度。通过使用双指针技巧,实现O(n)的时间复杂度。文章详细分析了解题思路和代码实现,提供了深入理解数组操作和双指针方法的实例。
671

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



