leetcode 27: Remove 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.

思路:

由于题目并没有限制最后的 array 的尾部有否其他元素,所以可以很容易想到调换 val 值的元素到末尾即可,这是下面代码二实现的。

一开始查阅了 vector 的函数,想到用 erase 函数,于是一个简单版本方案就是直接删除即可,代码一实现。

代码:

//code I
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int newLength = nums.size();
        int temp;
        for(vector<int>::iterator it = nums.begin(); it != nums.end(); it++ )
        {
            if(*it == val)
            {
                nums.erase(it); //simle and direct
                it--;
                newLength--;
            }
        }
        return newLength;
    }
};
//code II
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int newLength = nums.size();
        int temp;
        vector<int>::iterator rit = nums.end();
        rit--;
        for(vector<int>::iterator it = nums.begin(); it != nums.end(); it++ )
        {
            if(*it == val)
            {
                temp = *rit;
                *rit = val;
                *it = temp;
                it--;
                newLength--;
                rit--;
            }
            if(it == rit)
                break;
        }
        return newLength;
    }
};

“`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值