当前位置:网站首页>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;
}
};
边栏推荐
- typescript25-类型断言
- 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
- 25. 这三道常见的面试题,你有被问过吗?
- "ArchSummit: The cry of the times, technical people can hear"
- 请问表格储存中用sql只能查询到主键列,ots sql非主键不支持吗?
- 产品经理访谈 | 第五代验证码的创新与背景
- MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
- Character encoding and floating point calculation precision loss problem
- [kali-information collection] enumeration - DNS enumeration: DNSenum, fierce
- Typescript20 - interface
猜你喜欢
随机推荐
typescript28 - value of enumeration type and data enumeration
typescript19-对象可选参数
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
Immutable
Advice given by experts with four years of development experience in Flutter tutorial
请问shake数据库中想把源的db0的数据同步到目的db5,参数怎么设置呢?
Immutable
typescript26-字面量类型
程序员代码面试指南 CD15 生成窗口最大值数组
PMP 项目质量管理
In the shake database, I want to synchronize the data of the source db0 to the destination db5, how to set the parameters?
Flink 1.13 (8) CDC
leetcode:126. Word Solitaire II
请问表格储存中用sql只能查询到主键列,ots sql非主键不支持吗?
The kernel's handling of the device tree
时时刻刻保持敬畏之心
lambda
万字逐行解析与实现Transformer,并进行德译英实战(二)
Game Theory (Depu) and Sun Tzu's Art of War (42/100)








