码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 27 Remove Element(移除元素)

时间:2015-11-14 08:43:43      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:leetcode   remove   vector   array   element   

翻译

给定一个数组和一个值,删除该值的所有实例,并返回新的长度。

元素的顺序可以被改变,也不关心最终的数组长度。

原文

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) {
        if (nums.begin() == nums.end()) return 0;
        vector<int>::iterator itor;
        for (itor = nums.begin(); itor + 1 != nums.end(); )
        {
            if (*(itor + 1) == val) {
                nums.erase(itor + 1);
            }
            else {
                itor++;
            }
        }
        itor = nums.begin();
        if (*itor == val) {
            nums.erase(itor);
            return nums.size();
        }
        return nums.size();
    }
};

版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp

LeetCode 27 Remove Element(移除元素)

标签:leetcode   remove   vector   array   element   

原文地址:http://blog.csdn.net/nomasp/article/details/49824687

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!