当前位置:网站首页>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;
}
};
边栏推荐
- FFmpeg 搭建本地屏幕录制环境
- The difference between scheduleWithFixedDelay and scheduleAtFixedRate
- PMP 相关方管理必背总结
- ICML2022 | Deep Dive into Permutation-Sensitive Graph Neural Networks
- (2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
- Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
- 【愚公系列】2022年07月 Go教学课程 024-函数
- Typescript22 - interface inheritance
- What is a programming language
- PMP子过程定义总结
猜你喜欢

typescript24 - type inference

High Numbers | 【Re-integration】Line Area Score 880 Examples

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

时时刻刻保持敬畏之心

Make your Lottie support word wrapping in text fields

This article takes you to understand the past and present of Mimir, Grafana's latest open source project

博客系统(完整版)

Interview Blitz 69: Is TCP Reliable?Why?

What is dynamic programming and what is the knapsack problem

出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
随机推荐
一个往年的朋友
(2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
动态规划 01背包
Optional parameters typescript19 - object
时时刻刻保持敬畏之心
Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
Mysql中的数据类型和运算符
数据比对功能调研总结
博客系统(完整版)
scheduleWithFixedDelay和scheduleAtFixedRate的区别
(2022牛客多校四)H-Wall Builder II(思维)
The kernel's handling of the device tree
typescript19-对象可选参数
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
【愚公系列】2022年07月 Go教学课程 024-函数
万字逐行解析与实现Transformer,并进行德译英实战(二)
文件的异步读写
August 22 Promotion Ambassador Extra Reward Rules
Immutable
leetcode:126. Word Solitaire II