LeetCode27: Remove Element

本文介绍如何使用C++ STL中的remove和distance函数高效地从数组中移除特定值,通过具体示例展示了两种实用的方法,并对比了其性能表现。

题目链接:Remove Element

1. Description

  • Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

Example 1:

Given nums = [3,2,2,3], val = 3,

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

  • It doesn’t matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn’t matter what values are set beyond the returned length.

2. 方法1

因为这里是删除元素的问题,所以我们就搜索vector有没有删除元素的函数,还真有, erase和remove,所以我们写出了第一种代码。

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        nums.erase(remove(nums.begin(), nums.end(), val), nums.end());
        return nums.size();
        
    }
};

速度相当快,超过100%
在这里插入图片描述
注意:

  1. 这里的remove函数不是真的删除vector元素,和erase是不同的,直观理解remove返回是一个迭代器,然后的话它把需要删除的元素放到最后,然后返回的是最后一个和需要删除元素不等的元素。然后我们结合erase函数可以达到删除元素的效果~
  2. remove用法直接就是std::remove而不是使用这里的nums.remove,注意和nums.erase用法的区别。
  3. 这里的话删除的剩下的元素是不需要去重的。

参考文章:

  1. C++中vector的remove用法
  2. C++中Vector的erase()操作以及与remove的区别

3. 方法2

在题目的solution下面看到了distance,然后我们改进一下我们的代码。

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        return distance(nums.begin(), 
                             remove(nums.begin(), nums.end(), val));;
        
    }
};

结果都差不多~
在这里插入图片描述
参考文献:

  1. 使用stl中的 advance和 distance 方法来进行iterator的加减
  2. distance函数

好吧,好的函数的会事半功倍啊,代码也很简洁~

【通用视觉框架】基于Qt+Halcon开发的仿Visionmaster的通用视觉框架软件,全套源码,开箱即用1.1 背景​ 本项目软件开发意图为实现对Halcon、Opencv算子及其它视觉软件的便捷使用,由于Halcon和Opencv使用相比VisionPro较为麻烦,故此本软件仿照海康VisionMaster的流程图式操作,实现对Halcon、Opencv及其它视觉软件的二次开发。2.1 软件概述本软件使用Qt框架进行开发,实现对视觉流程的自由搭配,市场上对标海康威视的VisionMaster;本软件使用插件化开发框架,可使用提供的二次开发库自行添加新功能算子和新模块(将生成的插件放置到对应目录下即可);2.2 功能概述:视觉流程图式编程:实现对视觉/数据处理算子的自由编程,从而实现各类复杂的视觉需求项目读取保存:将编程的视觉项目进行保存或者读取图像显示:主界面中可以显示及监控视觉算子的图像处理情况日志消息显示:显示软件运行过程中出现的日志消息多语言:可进行多种语言切换2.3 开发平台主开发语言:Qt(C++)C++语言标椎:C++17开发环境:Window/Linux编程平台:Qt Creator编译器:|版本 | MSVC | Qt 6.4.0 MSVC2019 64bit | | Mingw | Qt 6.4.0 MinGW 64-bit |视觉工具:Halcon19.11 Progress X64资源介绍请查阅:https://blog.csdn.net/m0_37302966/article/details/146980317更多视觉框架资源:https://blog.csdn.net/m0_37302966/article/details/146583453
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值