LeeCode: Remove Element
来源:互联网 发布:sql replace替换空值 编辑:程序博客网 时间:2024/06/07 10:36
Title: Remove Element
discription:
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.
solution :
采用快速排序中的方法,从前后两个对立的方向进行搜索,前向后搜索等于查找等于elem的元素,从后向前搜索不等于elem的元素,然后交换两个值。
class Solution {public: int removeElement(int A[], int n, int elem) { int temp,length=0;if(n==1)return A[0]==elem?0:1;if(n==0) return 0; int left=0,right=n-1; while(left<=right) {while(A[left]!=elem&&left<=right){++left;++length;}while(left<=right&&A[right]==elem)--right;if(left<=right){<span style="white-space:pre"></span>temp=A[left]; <span style="white-space:pre"></span>A[left]=A[right];<span style="white-space:pre"></span>A[right]=temp;}length=left; } return length; }};
有几个问题:开始while条件是left<right,length总是出现问题,后面修改while判断条件好了!
最简洁的代码也采用类似于快排的方法,就是一个方向搜索,发现很多LeeCode上面的几个题都可以采用这个方法。
下面是代码是他人的代码,很简洁,拿来对比下,源网址为http://www.cnblogs.com/remlostime/archive/2012/11/14/2770009.html。
class Solution {public: int removeElement(int A[], int n, int elem) { // Start typing your C/C++ solution below // DO NOT write int main() function int start = 0; for(int i = 0; i < n; i++) if (elem != A[i]) { A[start++] = A[i]; } return start; }};
0 0
- LeeCode: Remove Element
- LeeCode-Remove Element
- leecode 解题总结:27 Remove Element
- LeeCode-Majority Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- 2014多校5(1006)hdu4916(树形DP)
- 美国生活(1)
- maven 下载源码
- 几种所的实现 自旋所,排队自旋锁,MCS锁,CLH锁
- MySQL数据文件介绍及存放位置
- LeeCode: Remove Element
- BOW(bag of words)
- C++中实现单例模式方法
- SSIS Lookup 找不到匹配数据
- 5. 线程的实现方式
- Logistic regression (逻辑回归) 概述
- 字节对齐详解
- 【opencv】cvCaptureFromFile的使用
- Hibernate的clear(),flush(),evict()方法详解