leetcode 27 Remove Element
2015-06-24 15:56
411 查看
Remove Element
Total Accepted: 60351
Total Submissions: 187833
My Submissions
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.
Show Tags
c++ 解决方案:
python解决方案:
史上最简洁的解决方案:
Remove Element
Total Accepted: 60351
Total Submissions: 187833
My Submissions
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.
Show Tags
c++ 解决方案:
class Solution { public: int removeElement(vector<int>& nums, int val) { int n = nums.size(); int i = 0; while( i < n ) { if( nums[i] == val ) { swap(nums[i], nums[n-1]); n--; } else { i++; } } return n; } };
int removeElement(vector<int>& nums, int val) { vector<int>::iterator itr = nums.begin(); while (itr != nums.end()) { if (*itr == val) itr = nums.erase(itr); else ++itr; } return nums.size(); }
int removeElement(int A[], int n, int elem) { int begin=0; for(int i=0;i<n;i++) if(A[i]!=elem) A[begin++]=A[i]; return begin; }
python解决方案:
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): i = 0 for j in range(len(A)): if A[j] != elem: A[i] = A[j] i += 1 return i
史上最简洁的解决方案:
def removeElement(self, nums, val): nums[:] = [x for x in nums if x!=val] return len(nums)
相关文章推荐
- js 回调函数的摘抄
- 一些常用的JS方法
- 【Objective-C 】音频 API 一览
- LeetCode96:Unique Binary Search Trees
- leetcode 27 Remove Element
- cpu架构
- 等比压缩图片的方法
- Win10触控板手势操作能够实现哪些常见的功能
- 关闭OSSIM防火墙
- 关闭OSSIM防火墙
- iPhone和ipad去掉按钮默认样式
- Log4配置
- httpd基于用户的站点访问控制
- ajax+jquery+ashx如何实现上传文件
- 小小点儿
- vs widows服务的发布
- SAT数学常用公式之面积和体积
- 关于EL表达式中requestScope和param区别,el表达式与jstl标签
- Leetcode--easy系列4
- Linux环境下ARM交叉编译找不到libz.so.1的动态库