Remove Element

来源:互联网 发布:收购淘宝店铺可信吗 编辑:程序博客网 时间:2024/06/06 09:16

每日算法——leetcode系列


问题 Remove Element

Difficulty: Easy

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.

class Solution {public:    int removeElement(vector<int>& nums, int val) {    }};

翻译

删除元素

难度系数:简单

给定一个数组和一个值, 删数组中所跟这个值相同的元素并返回新的长度
可以改变元素的顺序, 数组不用考虑返回的新的长度后面的元素。

思路

这题只管得到正确的长度,遍历数组,如果元素等于指定的值长度就不增加就好
另外可以考虑用distance

代码

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int len = 0;        for (size_t i = 0; i < nums.size(); ++i){            if (nums[i] != val){                nums[len++] = nums[i];            }        }        return len;    }};
0 0
原创粉丝点击