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:( C++ ) 顺序查找,利用 vector 的 erase 方法删除找到的元素,但是每次循环需要获取新的数组长度。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int numSize = nums.size();
vector<int>::iterator it = nums.begin();
for(int i = 0; i < numSize;)
{
if(nums[i] == val)
{
nums.erase(it + i);
numSize = nums.size();//删除元素后重新获取数组大小
}
else
{
++i;
}
}
return nums.size();
}
};法2:( C语言 ) 顺序查找,找到相同的值后用数组末端的不等于val的值替换,可避免删除元素后数组元素的移动。
int removeElement(int* nums, int numsSize, int val) {
int index = 0, end = numsSize-1;
if(!nums)/*空指针*/
{
return 0;
}
/*从头开始顺查找,找到等于val的值,用数组末端不等于val的值替换*/
while(index <= end)
{
if(nums[index] == val)
{
if(nums[end] != val)/*找到相等值,用末尾不相等值替换*/
{
nums[index++] = nums[end--];
}
else/*末尾值相等,找到不等于val的值*/
{
--end;
}
}
else
{
++index;
}
}
return index;
}
本文介绍了一种在数组中移除特定值并返回新长度的算法。提供了两种方法:一种使用C++的vector erase方法,另一种是C语言风格的替换方法,后者更高效地避免了元素移动。
4306

被折叠的 条评论
为什么被折叠?



