题目描述:
Given an array and a value, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
例子:
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2.
分析:
题意:给定一个有序数组,一个目标值,移除所有和目标值相等的元素,并且返回新的数组长度。空间复杂度要求为O(1)。
思路:此题是LeetCode 26的简化版本。不需要采用双指针法,只需要单指针即可。我们先初始化指针left=0,并且用cnt表示每个和目标值不相等的元素在数组中的新位置,初始化为0。我们先查找第一个和目标值不同的元素位置,更新该元素到cnt位置,cnt加一,然后继续重复该操作(与此同时,每一步查找指针left都加一,顺序向右遍历),直到更新完成所有元素。cnt的最终值就是新数组的长度。
假设原数组总共有n个元素,那么时间复杂度为O(n),空间复杂度为O(1)。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
// Exceptional Case:
if(n == 0){
return 0;
}
int left = 0, cnt = 0;
while(left <= n - 1){
if(nums[left] != val){
nums[cnt++] = nums[left];
}
left++;
}
return cnt;
}
};