当前位置:网站首页>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;
}
};
边栏推荐
- Make your Lottie support word wrapping in text fields
- 解决ffmpeg使用screen-capture-recorder录屏,有屏幕缩放的情况下录不全的问题
- 基于STM32设计的UNO卡牌游戏(双人、多人对战)
- 今日睡眠质量记录68分
- 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
- How to promote new products online?
- Risk strategy important steps of tuning method
- Immutable
- 这里有110+公开的专业数据集
- Game Theory (Depu) and Sun Tzu's Art of War (42/100)
猜你喜欢

产品经理访谈 | 第五代验证码的创新与背景

剑指 Offer 68 - II. 二叉树的最近公共祖先

typescript28-枚举类型的值以及数据枚举

Excel做题记录——整数规划优化模型

Error using ts-node

Risk strategy important steps of tuning method

(2022牛客多校四)H-Wall Builder II(思维)

typescript20-接口

MySQL-数据定义语言-DDLdatebase define language

The difference between scheduleWithFixedDelay and scheduleAtFixedRate
随机推荐
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
万字逐行解析与实现Transformer,并进行德译英实战(二)
Difference Between Compiled and Interpreted Languages
Mysql基础篇(Mysql数据类型)
[kali-information collection] enumeration - DNS enumeration: DNSenum, fierce
Immutable
力扣(LeetCode)212. 单词搜索 II(2022.07.31)
Risk strategy important steps of tuning method
MySQL-数据定义语言-DDLdatebase define language
typescript21 - Comparison of Interfaces and Type Aliases
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
"ArchSummit: The cry of the times, technical people can hear"
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
SQL Analysis of ShardingSphere
(2022牛客多校四)H-Wall Builder II(思维)
开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
typescript24-类型推论
typescript27-枚举类型呢
深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!