leetcode解题方案--027--Remove Element
来源:互联网 发布:linux 批量删除进程 编辑:程序博客网 时间:2024/05/20 16:32
题目
Given an array and a value, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
分析
从前向后遍历数组,如果遇到相同的就将后面的元素复制过来。因此需要维持一个尾指针。
class Solution { public int removeElement(int[] nums, int val) { int end = nums.length-1; int ans = 0; for (int i = 0; i<=end;i++) { if (nums[i] != val) { ans++; } else { while (end>i&&nums[end]==val) { end--; } if (nums[end]!=val) { nums[i] = nums[end]; end--; ans++; } } } return ans; }}
阅读全文
0 0
- leetcode解题方案--027--Remove Element
- LeetCode Remove Element 解题报告
- LeetCode解题报告--Remove Element
- [LeetCode] Remove Element 解题报告
- 【LeetCode】Remove Element 解题报告
- Leetcode Remove Element解题报告
- LeetCode 027 Remove Element
- LeetCode 027 Remove Element
- [LeetCode]027-Remove Element
- LeetCode 027 Remove Element
- LeetCode 027 Remove Element
- LeetCode 027 Remove Element
- LeetCode-027 Remove Element
- [leetcode] 27. Remove Element 解题报告
- leetcode解题集锦之 Remove Element
- [Leetcode] 27. Remove Element 解题报告
- 【LeetCode】27.Remove Element(Easy)解题报告
- 【LeetCode OJ 027】Remove Element
- 11.5 T1.attack(拓扑+lca)
- 我的Spring学习记录(五)
- 【bzoj2590】[Usaco2012 Feb]Cow Coupons
- 锋利的jQuery第二版
- Windows下TensorFlow-gpu版安装教程
- leetcode解题方案--027--Remove Element
- 2017年11月5日 CCS布局基础 自学
- Mybatis(一对多查询)
- python 模拟登录CSDN
- [bzoj1047][HAOI2007]理想的正方形(单调队列)
- HDFS的运行基本原理
- 字符串操作
- 欢迎使用CSDN-markdown编辑器
- <python核心编程第二版第10章>习题