Remove Element

来源:互联网 发布:中国10月经济数据 编辑:程序博客网 时间:2024/06/06 16:30

题目: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.

思路:

核心的代码是这样的。k一开始为0,保存第一个数据到val,i从1开始,如果此时num的数据是val值,不进行任何操作,如果不是,那么先不k+1,保存到num[k]里面,然后k+1。

代码:

class Solution {public:    int removeElement(vector<int>& nums, int val) {        if(nums.empty()){            return 0;        }                int k=0;        for(int i=0;i<nums.size();i++){            if(nums[i]!=val){                nums[k++]=nums[i];            }        }                return k;    }};


0 0
原创粉丝点击