Leetcode 23.移除元素
2021/12/18 23:27:52
本文主要是介绍Leetcode 23.移除元素,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
传送门:力扣移除元素
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
你可以假设 nums 中的所有元素是不重复的。
n 将在 [1, 10000]之间。
nums 的每个元素都将在 [-9999, 9999]之间。
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<vector> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { //快慢指针 int slowIndex = 0; for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) { if (nums[fastIndex] != val) { nums[slowIndex++] = nums[fastIndex]; //快指针覆盖慢指针,在锁定到val的时候! } } return slowIndex; } }; int main() { Solution solution; int a[] = { 1,2,2,4,5,3,7,8,1,0,5,7,2,4,2 }; vector<int> nums (a, a + sizeof(a) / sizeof(int)); cout << "原本长度" << sizeof(a) / sizeof(int) << endl; cout << "之后长度" << solution.removeElement(nums, 2) << endl; }
这篇关于Leetcode 23.移除元素的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享