leetcode 27. Remove Element
来源:互联网 发布:mac电脑转换视频格式 编辑:程序博客网 时间:2024/06/07 07:15
题目描述:
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.
解题思路:利用两个指针,用类似于快排的partition函数的处理方法来处理:
class Solution {public: int removeElement(vector<int>& nums, int val) { int len = 0; for(int index = 0; index < nums.size(); index++){ if(nums[index] != val) nums[len++] = nums[index]; } return len; }};空间复杂度为O(1),时间复杂度为O(n),这种方法是挺好的,所用时间为4ms,但当等于val的数字很少,这样做还是会导致出现很多不必要的赋值操作。
所以,可以用一前一后两个指针,时空复杂度还是一样,运行时间也是4ms,不过在val出现次数很少的情况下,确实能够减少赋值操作次数,但相反的,如果val出现次数增多的时候,赋值操作就会相应地增多,这也是种权衡了。。但注意,如果对于末尾的指针处理方式像快排的partition函数那样具体,时间可能会变为8ms,下面是一种实现方式:
class Solution {public: int removeElement(vector<int>& nums, int val) { int len = 0, last = nums.size()-1; while(len <= last){ if(nums[len] != val) ++len; else nums[len] = nums[last--]; } return len; }};
8ms代码:
class Solution {public: int removeElement(vector<int>& nums, int val) { int len = 0, last = nums.size()-1; while(len <= last){ if(nums[len] != val) ++len; else{ if(nums[last] == val) --last; else swap(nums[len], nums[last]); } } return len; }};
参考:leetcode题解
1 0
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- [Leetcode] 27.Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- Leetcode 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 【LeetCode】27. Remove Element
- leetcode 27. Remove Element
- leetcode 27. Remove Element
- [LeetCode]27. Remove Element
- LeetCode 27. Remove Element
- [leetcode] 27. Remove Element
- [leetcode] 27. Remove Element
- leetcode 27. Remove Element
- Apache服务器配置--Linux
- 数据结构之平衡树(Treap)
- eclipse 提交项目至 github
- 并查集详解(转)
- 使用 Swift 与 Kitura 构建端到端的云应用程序
- leetcode 27. Remove Element
- 数据还原
- Java迭代器注意事项
- Centos安装中文输入法
- 一些有用的资料记录
- 追mm和设计模式:趣解23种设计模式
- 自定义prigressDialog(无丑陋的黑色背景)
- maven学习(四)
- Yii入门