当前位置:网站首页>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;
}
};
边栏推荐
- Immutable
- Game Theory (Depu) and Sun Tzu's Art of War (42/100)
- typescript24-类型推论
- Logitech Mouse Experience Record
- typescript28-枚举类型的值以及数据枚举
- Li Chi's work and life summary in July 2022
- Flutter Tutorial 01 Configure the environment and run the demo program (tutorial includes source code)
- PAT乙级 1002 写出这个数
- Typescript22 - interface inheritance
- 【愚公系列】2022年07月 Go教学课程 025-递归函数
猜你喜欢

UE4 从鼠标位置射出射线检测

怀念故乡的月亮

typescript19-对象可选参数

typescript25 - type assertion

The method of solving stored procedure table name passing through variable in mysql

【kali-信息收集】枚举——DNS枚举:DNSenum、fierce

高数 | 【重积分】线面积分880例题

API Design Notes: The pimpl trick

【愚公系列】2022年07月 Go教学课程 024-函数

A way to deal with infinite debugger
随机推荐
Pyspark Machine Learning: Vectors and Common Operations
typescript20-接口
Article summary: the basic model of VPN and business types
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
UE4 rays flashed from mouse position detection
/etc/fstab
数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
MySQL-数据操作-分组查询-连接查询-子查询-分页查询-联合查询
typescript27-枚举类型呢
怀念故乡的面条
C# | 使用Json序列化对象时忽略只读的属性
【目标检测】YOLOv7理论简介+实践测试
MySQL4
Flink 1.13 (8) CDC
数据比对功能调研总结
Character encoding and floating point calculation precision loss problem
Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]
Mysql中的数据类型和运算符
(2022牛客多校四)K-NIO‘s Sword(思维)
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记