题目要求:
给定一个数组和一个目标值,在数组内删除所有目标值项并返回不包含目标值的数组长度
不要为另一个数组分配额外的空间,保持空间复杂度是O(1)。
Example:
输入 [3,2,2,3],val=3。输出:2
输入 [0,1,2,2,3,0,4,2],val=2 输出:5
解题思路
1.双指针法
参考26题leetcode26我们用一个指针来从前到后对数组进行遍历,另一个指针来记录非目标元素(最后指向末尾)
主要代码如下c++:
// leetcode 27
// Remove Element
class Solution {
public:
int removeDuplicates(vector<int>& nums, int val) {
int record = 0; // For record.
for(int traverse = 0; traverse < nums.size(); ++traverse)
{
// consider whether is target val.
// record the non-target element and move.
if(nums[traverse] != val)
nums[record++] = nums[traverse];
}
return record;
}
};
2.迭代器法
思路一样,只不过换了更高效的迭代器来实现,最后返回不要弄错。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
vector<int>::iterator record, traverse;
for(record=traverse=nums.begin(); traverse != nums.end(); ++traverse)
{
if(*traverse == val)
{
}
else{
*record = *traverse;
record++; // to the next;
}
}
return record - nums.begin(); // to be noticed!
}
};
python 解法
in-place, two pointers!
注意,你要是使用内置函数remove的话,一次只能删除一个符合的元素,另外所以会进行递补,很容易进坑!!
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
l, r, count = 0, len(nums)-1, len(nums)
while l<=r:
while l<=r and nums[l] == val:
l+=1
while l<=r and nums[r] != val:
r-=1
if l < r:
nums[l], nums[r] = nums[r], nums[l]
for _ in range(l): # 删除前l个 val值
del nums[0]
return count - l