当前位置:网站首页>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;
}
};
边栏推荐
- (2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
- API设计笔记:pimpl技巧
- The Flow Of Percona Toolkit pt-table-checksum
- 高数 | 【重积分】线面积分880例题
- EntityFramework saves to SQLServer decimal precision is lost
- What is a programming language
- 基于Arduino制作非接触式测温仪
- UE4 制作遇到的问题
- 请问表格储存中用sql只能查询到主键列,ots sql非主键不支持吗?
- 云服务器下载安装mongo数据库并远程连接详细图文版本(全)
猜你喜欢

Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers

怀念故乡的月亮

【无标题】

y83.第四章 Prometheus大厂监控体系及实战 -- prometheus告警机制进阶(十四)

JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors

typescript24 - type inference

UE4 制作遇到的问题

Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)

scheduleWithFixedDelay和scheduleAtFixedRate的区别

博客系统(完整版)
随机推荐
Optional parameters typescript19 - object
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
状态压缩dp
请问表格储存中用sql只能查询到主键列,ots sql非主键不支持吗?
Flutter Tutorial 01 Configure the environment and run the demo program (tutorial includes source code)
Pyspark Machine Learning: Vectors and Common Operations
A way to deal with infinite debugger
safari浏览器怎么导入书签
PMP工具与技术总结
(Codeforce 757)E. Bash Plays with Functions(积性函数)
PAT乙级 1002 写出这个数
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
Visual Studio提供的 Command Prompt 到底有啥用
今日睡眠质量记录68分
Immutable
MySQL-数据操作-分组查询-连接查询-子查询-分页查询-联合查询
【无标题】
初识shell脚本
项目风险管理必备内容总结
API Design Notes: The pimpl trick