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
原创粉丝点击