27.RemoveElement(删除一个元素)--Array
来源:互联网 发布:语音识别 算法 编辑:程序博客网 时间:2024/05/23 15:05
RemoveElement(删除一个元素)
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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Hint:
- Try two pointers.
- Did you use the property of "the order of elements can be changed"?
- What happens when the elements to remove are rare?
class Solution {public: int removeElement(vector<int>& nums, int val) { int sz = nums.size();// 不用在循环里每次都算 int newIndex = 0; for(int oldIndex = 0; oldIndex < sz; ++oldIndex) {//--------------------------------// 法1/*if (A[oldIndex] == val)continue;A[newIndex++] = A[oldIndex];*///--------------------------------// 法2 if(nums[oldIndex] != val) nums[newIndex++] = nums[oldIndex]; // 先newIndex,再++ }// nums.reserve(newIndex); // 最终的数组大小 return newIndex; }}
0 0
- 27.RemoveElement(删除一个元素)--Array
- 【Array】数组删除最后一个元素;
- removeElement
- RemoveElement
- 删除array元素
- JS array 删除元素
- js Array 删除指定元素
- c删除一个元素
- Flex 中Array的插入删除元素
- Flex 中Array的插入删除元素
- Flex 中Array的插入删除元素
- Array数组技术总结 删除指定元素
- flex Array如何删除所有元素
- js删除Array数组中的某个元素
- 删除Array重复元素的方法
- 使用Array对数组元素删除其中某个元素
- 对Array数组新增、删除重复及删除元素
- vector中删除一个元素
- shell删除当前目录及递归目录下文件指定字符串
- HDU 2577 How to Type 简单dp
- 各种杂物
- NOIP2016 DAY2
- 11gr2 rac改IP系列之一:修改公网IP为同网段其它IP
- 27.RemoveElement(删除一个元素)--Array
- 软件设计基础
- Android基础第二天
- [leetcode]204. Count Primes
- android的m、mm、mmm编译命令的使用
- 2016书单总结--JVM虚拟机之概述篇
- Java中普通代码块,构造代码块,静态代码块区别及代码示例
- JNI Java 入门篇——传递&&接收基本数据类型
- 11gr2 rac改IP系列之二:修改VIP为同网段其它IP