删除数组中给定的元素

来源:互联网 发布:关于windows api的书籍 编辑:程序博客网 时间:2024/05/22 07:08
题目:

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.

代码:

int removeElement(vector<int>& nums, int val) {
     int n=nums.size();
int res=0;
for(int i=0;i<n;i++){
if(nums[i]!=val)
nums[res++]=nums[i];//后面非删除元素前移
}
return res; //返回个数
        
        
    }

0 0
原创粉丝点击