27. Remove Element
来源:互联网 发布:idea新建普通java项目 编辑:程序博客网 时间:2024/06/06 16:52
题目
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?
详见注释,均使用STL算法。
class Solution {public: int removeElement(vector<int>& nums, int val) { sort(nums.begin(),nums.end());//先排序,将相同元素集中在一起 vector<int>::iterator it_begin=find(nums.begin(),nums.end(),val);//查找val第一次出现的位置 if(it_begin==nums.end())//不存在val则返回原集合 return nums.size(); vector<int>::iterator it_end=upper_bound(nums.begin(),nums.end(),val);//查找第一个比val大的元素位置 nums.erase(it_begin,it_end);//删除区间[it_begin,it_end),即删除所有val return nums.size(); }};
0 0
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- 27.Remove Element
- [Leetcode] 27.Remove Element
- 27. Remove Element
- 27. Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- 27. Remove Element
- 27. Remove Element
- 27. Remove Element
- Leetcode 27. Remove Element
- 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 27. Remove Element
- 函数类型和函数指针类型
- 重载operator操作符
- 顺序栈学习
- [C/C++]_[初级]_[原子操作]
- Spring框架-->面试问答
- 27. Remove Element
- Too many alarms (500) registered
- CSS表显示值
- JQuery 获取验证上传文件大小代码
- 与AQS有关的并发类
- Web 通信 之 长连接、长轮询(long polling)
- [从头学数学] 第162节 锐角三角函数
- ImageLoader使用详解
- c# log组件 log4net使用介绍