您的位置:首页 > 其它

关于leetcode中对数组O(1)空间消耗操作的几道题

2015-04-21 09:05 197 查看
其实这几道题在leetcode中都是比较容易的,但是如果刚开始不理解题意的话可能就会进入陷阱。

整数数组中的几个操作如下面所示,无非是怎样进行数组元素的的交换。

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.
这道题是删除一个整数数组中的与给定元素相同的元素。题目提示可以将原有元素的顺序打乱,最后返回的是数组的长度
同时不能有其他的空间消耗。
其实我当初的思路还是很简单的:
我是用一个头指针,一个尾指针分别从两端开始,每一次如果前面的元素出现了elem,那么从尾指针当前位置
向前找到第一个出现的非elem的元素进行交换,这样的时间复杂度是O(m)其中m是非elem的个数,但是代码的实现上稍显复杂:
/*---------------------O(m)时间消耗,O(1)空间消耗-------------------------------------*/
//首尾两个指针,向中间扫描。用后面元素向前面元素进行替换,会改变元素的位置
//By Lingtao 2015/04/21
int removeElement(int A[], int n, int elem) {
int length = 0;
int head = 0, tail = n - 1;
while (head <= tail)
{
if (A[head] == elem)
{
while (tail > head)
{
if (A[tail] != elem)
{
swap(A[head], A[tail]);
length++;
break;
}
tail--;
}
}
else
length++;
head++;
}
cout << endl;
return length;
}
//下面的代码不用改变数组元素的顺序,但是需要进行o(n)的时间度,即需要对整个元素进行扫描一次。
简洁了许多。
int removeElement2(int A[], int n, int elem) {
int count = 0;
for (int i = 0; i<n; i++)
if (A[i] != elem)
swap(A[i], A[count++]);
return count;
}
其实,对于这种问题,解法二才是最正宗的解法,两个point一前一后,一个用来遍历数组,一个用来记录有效元素的位置。下面这道题依然是类似的题目:


Remove Duplicates from Sorted Array

 

Given a sorted array, remove the duplicates in place such that each element appear only once and
return the new length.

这里面要求数组元素的顺序是不能变的。那么就可以采用一中的方法。
仍然是两个指针:
int removeDuplicates(int A[], int n) {
if (n == 0 || n==1)
return n;
int count = 1;
for (int i = 1; i < n; i++)
{
if (A[i - 1] == A[i])
continue;
else
{
A[count] = A[i];
count++;
}
}
return count;
}

未完待续。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: