Leetcode: Remove Element
来源:互联网 发布:pokemon go 辅助软件 编辑:程序博客网 时间:2024/06/06 07:03
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.
比较简单,可以直接遍历往前拷贝, O(n)。考虑到题目允许元素顺序变动,可以采用填坑的方式减少元素移动次数。
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int j = n-1;
for (int i = 0; i <= j; ++i) {
while (A[j] == elem) {
--j;
}
if (A[i] == elem && i < j) {
A[i] = A[j];
--j;
}
}
return (j+1);
}
};
==============第二次============
class Solution {public: int removeElement(int A[], int n, int elem) { int i = 0; while (i < n) { if (A[i] == elem) { A[i] = A[--n]; } else { ++i; } } return n; }};
0 0
- LeetCode:Remove Element
- LeetCode: Remove Element
- [Leetcode] Remove Element
- LeetCode: Remove Element
- leetcode 39: Remove Element
- [LeetCode] Remove Element
- Leetcode: Remove Element
- Leetcode:Remove Element
- Leetcode:Remove Element
- Leetcode:Remove Element
- [LeetCode]Remove Element
- LeetCode-Remove Element
- LeetCode - Remove Element
- LeetCode | Remove Element
- leetcode之Remove Element
- LeetCode - Remove Element
- LeetCode: Remove Element
- 【LeetCode】Remove Element
- ios notification
- Visitor——访问者模式
- Cocos2d-x教程 CocoStudio篇 (2) UIButton控件
- 基于visual Studio2013解决面试题之0801对称字符串
- 第二十四天【java虐我千百遍,我待java如初恋】
- Leetcode: Remove Element
- 这就是爱
- HTML5实战与剖析之判断移动端横屏竖屏功能
- 给用户只能操作某一数据库权限
- MIPS 的寄存器
- 高性能 JavaScript 编程 读书笔记
- 移植于电脑圈圈的fsmc_nand代码
- [原][译][转]Floyd算法(待续)
- 基于visual Studio2013解决面试题之0802数字最多元素