您的位置:首页 > 其它

LeetCode Remove Element 快速删除数组中的某一值

2013-11-26 16:47 302 查看
Remove Element

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.

为初级入门题了。

两种思路:

1 如果找到特定值那么用最后一个元素值覆盖之,最后元素往前进一个元素

2 一个快指针,一个慢指针,不等于特定值的时候,把快指针指向值覆盖慢指针值。这里是用下标表示指针概念了。

我本来以为第一个思路会快点的,不过测试的编译时间差不多,应该速度差别都可以忽略不计。

思路1程序:

int removeElement(int A[], int n, int elem) 
	{
		int k = n-1;
		for (int i = 0; i <= k; i++)
		{
			if (A[i] == elem)
			{
				while (i<=k && A[k] == elem) k--;
				if (i<=k && A[k] != elem) 
				{
					A[i] = A[k];
					k--;
				}
			}
		}
		return k+1;
	}




思路2程序:

int removeElement(int A[], int n, int elem)
	{
		int i = 0, j = 0;
		for (; i < n; i++)
		{
			if (A[i] != elem)
			{
				A[j++] = A[i];
			}
		}
		return j;
	}




//2014-1-25 update
class Solution1 {
public:
	int removeElement(int A[], int n, int elem)
	{
		int i = 0, j = 0;
		for ( ; j < n; j++)
		{
			if (A[j] != elem) A[i++] = A[j];
		}
		return i;
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐