一.问题描述
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.
二.我的解题思路
这道题目有点像上一道题,都比较简单。我的做法是每次都记录之前一个非value数的下标pri,当遇到新的非value数的时候,直接放在pri后面即可。测试通过的程序如下:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int cnt=0;int len=nums.size();
int st=0;int pri=-1;
if (len==0) return 0;
if(len==1&&nums[0]==val) return 0;
if(len==1&&nums[0]!=val) return 1;
if(nums[0]==val) pri=-1;
else {pri=0;cnt=1;}
for(int i=1;i<len;i++){
if(nums[i]!=val){
nums[pri+1]=nums[i];
pri++;
cnt++;
}
}
return cnt;
}
};