Remove Element
Solution 1
上一个题的一个变体,两个指针的功能不变化,当第二个指针遇到非给定值时,和第一个指针完成覆盖操作。由于第二个指针一定在第一个后面,所以覆盖操作不会出现问题。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入序列长度
- 空间复杂度: O ( 1 ) O(1) O(1),原位处理要求
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int length = nums.size();
if (length <= 0) {
return 0;
}
int posA = -1, posB = 0;
while (posB < length) {
if (nums[posB] != val) {
nums[++posA] = nums[posB];
}
posB++;
}
return posA + 1;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
length = len(nums)
if length == 0: return 0
posA, posB = -1, 0
while posB < length:
if nums[posB] != val:
posA += 1
nums[posA] = nums[posB]
posB+= 1
return posA + 1