LeeCode: Remove Element

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;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章