[LeetCode] Remove Element题解

时间:2023-03-08 19:22:50
[LeetCode] Remove Element题解

Remove Element:

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 in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

这道题如果没有其他限制,另开一条数组,将不等于val的数存进去就ok了,但是它限制了我们另开一条数组,所以可以用c++ STL中vector的erase函数直接在原数组中更改:

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
while(remove(nums,val)){
}
return nums.size();
}
bool remove(vector<int>& nums, int val){
vector<int>::iterator iter;
for(iter=nums.begin();iter!=nums.end();iter++){
if(*iter==val){
nums.erase(iter);
return true;
}
}
return false;
}
};

而在一些语言中没有erase函数可以用,这么办?不用erase函数的话,我们可以这样处理:

int removeElement(vector<int>& nums, int val) {
int cnt = 0;
for(int i = 0 ; i < nums.size() ; ++i) {
if(nums[i] == val)
cnt++;
else
nums[i-cnt] = nums[i];
}
return nums.size()-cnt;
}

或者

int removeElement(int A[], int n, int elem) {
int begin=0;
for(int i=0;i<n;i++){
if(A[i]!=elem){
A[begin++]=A[i];
}
}
return begin;
}