LeetCode_Remove Element
来源:互联网 发布:linux du和df命令 编辑:程序博客网 时间:2024/05/21 05:37
一.题目
Remove Element
Total Accepted: 48066 Total Submissions: 148276My SubmissionsGiven 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.
Show Tags
Have you met this question in a real interview?
Yes
No
Discuss
二.解题技巧
这道题和Remove Duplicates from Sorted Array类似,不同的是这里只要删除值等于给定值的元素即可,可以采用和前面的题相同的做法:可以将原来的数组看作一个栈,设定一个栈顶指针,在对数组进行遍历的时候,判断元素是否等于给定值,如果等于,则直接进行数组的下一个元素,如果不等于,则将该元素放入到栈顶,然后更新指针并处理数组的下一个元素。之所以能这么做,是因为我们在遍历过程中,对于数组元素的访问的下标总是不小于栈顶指针的,因此,可以将原来的数组直接当作一个栈来使用,这样就能做到in-place处理了。
这道题相对比较简单,也没有多少边界条件要考虑,是一道练手的题。这里在进行删除后数组的元素的个数的统计的时候,有一个技巧,即栈顶指针就已经说明了数组中元素的个数了,因此,可以直接返回栈顶指针就可以了(这里的栈顶指针是用数组的下标表示的)。当然,也可以统计等于给定值的元素的个数,然后用原来的数组个数减去该值就可以得到新的数组的值了。
三.实现代码
class Solution{public: int removeElement(int A[], int n, int elem) { int TrueIndex = 0; for (int Index = 0; Index < n; Index++) { if (A[Index] != elem) { A[TrueIndex] = A[Index]; TrueIndex++; } } return TrueIndex; }};
四.体会
这道题还是一道很简单的题目的,代码简短,边界条件也基本没有,很适合练手用。
版权所有,欢迎转载,转载请注明出处,谢谢
0 0
- Leetcode_remove-element
- leetcode_remove element
- LeetCode_Remove Element
- leetcode_Remove Element
- LeetCode_Remove Element
- LeetCode_remove-element
- leetcode_Remove Element
- leetcode_Remove Linked List Elements
- Leetcode_remove-duplicates-from-sorted-array
- LeetCode_Remove Duplicates from Sorted Array
- LeetCode_Remove Duplicates from Sorted List
- leetcode_Remove Duplicates from Sorted Array
- LeetCode_Remove Duplicates from Sorted Array
- LeetCode_remove-duplicates-from-sorted-list
- LeetCode_remove-duplicates-from-sorted-array
- LeetCode_Remove Duplicates from Sorted Array
- Element
- Element
- HDU 2199
- cocos2.x升级到3.x的脚本
- 类的静态成员变量
- Liferay pom.xml报错:Failure to transfer com.liferay.maven.plugins
- 获取数据库当前所有活动连接的脚本
- LeetCode_Remove Element
- 删除GridView中的一行的-----两种操作方法.
- 欢迎使用CSDN-markdown编辑器
- Git常用命令以及用法
- java静态方法,静态初始化块及静态变量的声明和初始化不能使用泛型的原因
- JavaHost:使用虚拟DNS省掉开发环境配置hosts文件
- ios8 定位无效
- 怎样写一个尽可能优雅的equals方法
- 关于resize事件,不同浏览器的触发行为