当前位置:网站首页>LeetCode 27. 移除元素
LeetCode 27. 移除元素
2022-08-01 04:49:00 【PUdd】
我的思路
由于数据是有范围的,则把所有需要删除的数据替换成超出范围的一个数,然后进行排序。(不清楚sort会不会导致空间复杂度不满足要求…)排完之后输出超出范围的数前面的值的个数,如果没有则会一直遍历到vector末尾然后输出个数。个数用的是iter-nums.begin()
代码
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
vector<int>::iterator iter; // 声明迭代器iter
//把等于val的值全改成很大的值(如101)
for(iter = nums.begin(); iter != nums.end(); iter++)
{
if (*iter == val)
{
iter =nums.erase(iter);
iter = nums.insert(iter,101);
}
}
//排序
sort(nums.begin(),nums.end());
//返回个数
iter = nums.begin();
while( iter!=nums.end() && (*iter)!=101 ){
iter++;}
return iter - nums.begin();
}
};
标准解法:双指针法
通过这一题学习了快慢指针的思路。本题实际上用的是数组下标。
1 3 2 1 5 2 1
快指针:i不断向后移
慢指针:碰到nums[j]==val时,就跳过;其余时间一直是nums[j]=nums[i],即快指针所指的位置。
1 3 跳过 1 5 跳过 1
代码
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
int slow = 0;
for(int fast = 0; fast < nums.size(); fast++)
{
if(nums[fast] != val)
{
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
};
边栏推荐
- 程序员代码面试指南 CD15 生成窗口最大值数组
- 雪糕和轮胎
- 微软 Win10 照片磁贴后的又一“刺客”,谷歌 Chrome 浏览器将在新标签页展示用户照片
- (2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
- Mysql中的数据类型和运算符
- Excel做题记录——整数规划优化模型
- 请问shake数据库中想把源的db0的数据同步到目的db5,参数怎么设置呢?
- Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
- 基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
- Message queue design based on mysql
猜你喜欢
高数 | 【重积分】线面积分880例题
最新 955 不加班的公司名单
【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
leetcode:126. Word Solitaire II
API Design Notes: The pimpl trick
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
2022-07-31: Given a graph with n points and m directed edges, you can use magic to turn directed edges into undirected edges, such as directed edges from A to B, with a weight of 7.After casting the m
(Codeforce 757)E. Bash Plays with Functions(积性函数)
7 行代码搞崩溃 B 站,原因令人唏嘘!
随机推荐
Typescript20 - interface
56:第五章:开发admin管理服务:9:开发【文件上传到,MongoDB的GridFS中,接口】;(把文件上传到GridFS的SOP)
开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
MySQL-数据操作-分组查询-连接查询-子查询-分页查询-联合查询
动态规划 01背包
Optional parameters typescript19 - object
typescript26 - literal types
How to write a high-quality digital good article recommendation
请问shake数据库中为什么读取100个collection 后,直接就退出了,不继续读了呢?
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
产品经理访谈 | 第五代验证码的创新与背景
请问表格储存中用sql只能查询到主键列,ots sql非主键不支持吗?
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
[kali-information collection] enumeration - DNS enumeration: DNSenum, fierce
PMP 相关方管理必背总结
C# | 使用Json序列化对象时忽略只读的属性
Mysql中的数据类型和运算符
UE4 rays flashed from mouse position detection
The method of solving stored procedure table name passing through variable in mysql