Leetcode——27. Remove Element

1. 概述

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.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.

本题如上面所说的,你要返回一个数组和一个长度(答案检查中不管这个长度之后的元素),因而只需要使得到的数组在返回回来的长度内没有包含规定的数组就可以了。

2. 编码

2.1 方法1

这个方法的思想:从最后一个开始遍历,如果当前数不是规定的数,那么将其弹出并且添加到最前;如果等于规定的数,直接弹出
class Solution {
public:
    int removeElement(vector<int>& nums, int val)
    {
        int len(nums.size());
        if(0 == len) return 0;
        
        //方法1 开销大 重新分配
        for(int i=0; i<len; i++)
        {
            int temp_size(nums.size());
            if(nums[temp_size-1] == val)
            {
                nums.pop_back();
            }
            else
            {
                int num = nums.back();
                nums.pop_back();
                nums.insert(nums.begin(), num);
            }
        }

        return static_cast<int>(nums.size());
    }
};
性能

2.2 方法2

这个方法的思想:填一个计数数字,从第一个开始遍历,如果当前数不是规定的数,那么将其赋值到计数位置的位置,计数加加;如果等于规定的数,不做操作
class Solution {
public:
    int removeElement(vector<int>& nums, int val)
    {
        int len(nums.size());
        if(0 == len) return 0;
        
        //方法1
        int count(0);
        auto it = nums.begin();
        for(int i=0; i<len; i++)
        {
            if(val != nums[i])
            {
                nums[count++] = nums[i];
            }
        }
        return count;
    }
};
性能

2.3 方法3

这个方法的思想:直接删除删除数组中规定的数字
class Solution {
public:
    int removeElement(vector<int>& nums, int val)
    {
        int len(nums.size());
        if(0 == len) return 0;
        
        //方法3 
        int pos(0);
        while(true)
        {
            auto it = nums.begin();
            if(nums[pos] == val)
            {
                nums.erase(it+pos);
                if(0 == nums.size()) break;
                pos = 0;
                continue;
            }
            ++pos;
            if(pos >= nums.size()) break;
        }
        
        
        return static_cast<int>(nums.size());
    }
};
性能



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值