当前位置:网站首页>LeetCode26:删除有序数组中的重复项
LeetCode26:删除有序数组中的重复项
2022-08-09 21:35:00 【哆啦k梦0219】
给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。
由于在某些语言中不能改变数组的长度,所以必须将结果放在数组nums的第一部分。更规范地说,如果在删除重复项之后有 k 个元素,那么 nums 的前 k 个元素应该保存最终结果。
将最终结果插入 nums 的前 k 个位置后返回 k 。
不要使用额外的空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-array
本题目采用双指针法,在力扣评论区看到这样一段话非常有意思,可以帮助我们理解这个双指针法:
双指针法 (C++)
双指针法在数组、链表题目中都有很大的用处。
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
int fast = 1;//快指针
int slow = 0;//慢指针
if(nums.size()==0)
return 0;
for(fast = 1;fast<nums.size();fast++)//注意C++容器中是.size()获得容量,没有.length()
{
if(nums[fast]!=nums[slow])
{
slow++;
nums[slow]=nums[fast];
}
}
return slow+1;//长度 = 下标+1
}
};
边栏推荐
- MySQL:错误1153(08S01):得到的数据包大于“ max_allowed_packet”字节
- PHP 二维数组根据某个字段排序
- 技术分享 | 接口自动化测试如何处理 Header cookie
- Acrel5000web能耗系统在某学院的应用-Susie 周
- LeetCode Daily Question (321. Create Maximum Number)
- 企业数据打通有什么好处?不同行业怎么解决数据打通难题?
- CMake installation upgrade higher version
- Byte side: Can TCP and UDP use the same port?
- [Essay] To the friends of the 19th issue
- [Deep learning] pix2pix GAN theory and code implementation
猜你喜欢
安科瑞支持以太网通讯、profibus通讯嵌入式电能表APM指导性技术要求-Susie 周
kvm虚拟机出现启动不了,NOT available,PV大于分区
cad图纸怎么复制到word文档里面?Word里插CAD图怎么弄?
Puyuan Jingdian turned losses into profits in the first half of the year, and high-end products continued to develop!Are you optimistic about "Huawei" in the instrument industry?
痛击面试官 CURD系统也能做出技术含量
Number of daffodils within a thousand
抽象类 or 接口
Don't tell me to play, I'm taking the PMP exam: what you need to know about choosing an institution for the PMP exam
DSPE-PEG-Azide,DSPE-PEG-N3,磷脂-聚乙二醇-叠氮可和DBCO直接反应
Application of Acrel5000web Energy Consumption System in a College-Susie Week
随机推荐
[corctf 2022] 部分
Reverse Analysis of Unknown Cryptographic Protocol Based on Network Data Flow
poj 3070 Fibonacci(简单矩阵连乘)
Photometric Stereo 光度立体法三维重建
How are data integration APIs key to enterprise digital transformation?
[Graphic and textual] How to reinstall Win7 system
Ankerui supports Ethernet communication, profibus communication embedded energy meter APM guiding technical requirements-Susie Week
json事例
访问控制知识
PMP每日一练 | 考试不迷路-8.9(包含敏捷+多选)
Problems with compiling SIP with QGIS
小黑leetcode清爽雨天之旅,刚吃完宇飞牛肉面、麻辣烫和啤酒:112. 路径总和
hdu 1333 Smith Numbers(暴力思路)
Next second data: the transformation of the modern data stack brought about by the integration of lake and warehouse has begun
Unity2D_背景粒子效果
Jmeter 使用正则表达式提取器将返回值全部保存到一个文件中
Error when source install/setup.bash
DSPE-PEG-Silane, DSPE-PEG-SIL, phospholipid-polyethylene glycol-silane modified silica particles
C语言中的文件是什么?
Cookie、session、token