Remove Element
Total Accepted: 58916 Total Submissions: 182885Given 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.
Array Two Pointers
这道题目意思是:给一个数组,给一个值,在数组中去除这些值,返回新的数组长度。也就是去除了这些数字后,并且将数组中其他的数都移到数组的前面,新的数组首地址不变,仅仅长度变了。
正常的做法刚开始想到的是排序吧,排好序后将要去除的值的后面的数组整体前移,就好了,不过想了下这样的话复杂度明显大的
优化做法的话,提示其实已经告诉你了,不过我一开始没看提示,不过自己想了一会儿,也想到了,就是:定两个标记first,last,两头一起遍历,先向后遍历数组,直到遇到要去除的值,然后从后向前遍历寻找,如果是要去除的值,就跳过继续向前遍历,直到找到不用去除的值,然后将值赋给前面要去除的值的位置(nums[first] == nums[last]),然后first++,继续向后遍历,就这样当first > last时,停止
这样的话整体只用遍历一遍时间,复杂度只有O(N)
思路想到了,就比较简单了,写的时候注意对first和last处理时进行边界检查
源代码(C语言):
int removeElement(int* nums, int numsSize, int val) {
if(numsSize==0)
return 0;
int i,sum=numsSize;
int first=0,last=numsSize-1;
while(first<=last)
{
if(nums[first]==val)
{
sum--;
while(nums[last]==val)
{
sum--;
if(last>first)
last--;
else
{
sum++;
return sum;
}
}
nums[first]=nums[last];
last--;
}
first++;
}
return sum;
}
if(numsSize==0)
return 0;
int i,sum=numsSize;
int first=0,last=numsSize-1;
while(first<=last)
{
if(nums[first]==val)
{
sum--;
while(nums[last]==val)
{
sum--;
if(last>first)
last--;
else
{
sum++;
return sum;
}
}
nums[first]=nums[last];
last--;
}
first++;
}
return sum;
}