当前位置:网站首页>删除有序数组中的重复项 II[双指针--多情况统一]
删除有序数组中的重复项 II[双指针--多情况统一]
2022-06-30 15:48:00 【REN_林森】
前言
很多算法,不需要取模拟,模拟会有很多情况,你就需要很多if,甚至你if不过来,if中有if。
要学会多情况统一处理,让简洁的代码完成才是一条正确的路线。
一、删除有序数组中的重复项 II

二、双指针
package everyday.doublePoint;
public class RemoveDuplicates {
/* target:原地修改数组,让已升序的数组中元素不能超过两个,即1-2个。最后返回前面修改好的有效元素个数。 一个指针指向实际可以赋值的位置,一个指针遍历nums所有元素,把合法的元素都赋值到实际的指针处。 用一个变量记录记录不合法的数字,用nums.length - 不合法个数即为实际长度。 */
public int removeDuplicates(int[] nums) {
// 实际可以赋值的位置。
int real = 0;
// 记录前一个变量是谁,以及已经重复了多少这个变量。
int pre = 1 << 31, sameNum = 0;
// 记录数组的有效长度。
int len = nums.length;
// 第二个指针遍历nums数组,筛选符合条件的数。
for (int i = 0; i < nums.length; i++) {
// 和前面不等,新值,需要重设pre/sameNum,且把符合条件的值赋值到real处。
if (pre != nums[i]) {
pre = nums[i];
sameNum = 1;
nums[real++] = nums[i];
}
// 相同元素还不超过2
else if (sameNum++ < 2) nums[real++] = nums[i];
// 相同元素超过2,无效元素
else --len;
}
return len;
}
}
总结
1)双指针
2)找到一个可以统一的处理方式,就是一种算法。
参考文献
边栏推荐
- How the edge computing platform helps the development of the Internet of things
- MySQL8.0开启远程连接权限的方法步骤
- JS ES5也可以创建常量?
- Anaconda下安装Jupyter notebook
- 2022 Blue Bridge Cup group B - expense reimbursement - (linear dp| status DP)
- 牛客网:最小花费爬楼梯
- 新茶饮“死去活来”,供应商却“盆满钵满”?
- [Verilog quick start of Niuke online question series] ~ bit splitting and operation
- 药品管理系统加数据库,一夜做完,加报告
- POJ Project Summer
猜你喜欢

JS ES5也可以创建常量?
![Halcon knowledge: regional topics [07]](/img/18/680997127047fb24b0ee4f19d8f2c5.png)
Halcon knowledge: regional topics [07]

Go zero micro Service Practice Series (VIII. How to handle tens of thousands of order requests per second)

名单揭晓 | 2021年度中国杰出知识产权服务团队

【微信小程序】小程序的宿主环境

荣盛生物冲刺科创板:拟募资12.5亿 年营收2.6亿

容联云首发基于统信UOS的Rphone,打造国产化联络中心新生态

MC Instruction Decoder

The inspiration from infant cognitive learning may be the key to the next generation of unsupervised machine learning

几百行代码实现一个 JSON 解析器
随机推荐
Explain in detail the use of for loop, break and continue in go language
Installing jupyter notebook under Anaconda
Mysql8.0 method and steps for enabling remote connection permission
【微信小程序】常用组件基本使用(view/scroll-view/swiper、text/rich-text、button/image)
How cloudxr promotes the future development of XR
中航无人机科创板上市:市值385亿 拳头产品是翼龙无人机
【活动报名】探秘元宇宙,就差你了!7月2号我在深圳现场等你!
名单揭晓 | 2021年度中国杰出知识产权服务团队
Dart: string replace related methods to solve replacement characters
容联云首发基于统信UOS的Rphone,打造国产化联络中心新生态
MC Instruction Decoder
JS Es5 can also create constants?
安全帽佩戴检测算法研究
RTP sending PS stream zero copy scheme
[Verilog basics] octal and hexadecimal representation of decimal negative numbers
MySQL transaction / lock / log summary
Does flinkcdc have to be a clustered version if the monitored database is Mongo
【牛客网刷题系列 之 Verilog快速入门】~ 位拆分与运算
Cloud XR, how to help industrial upgrading
药品管理系统加数据库,一夜做完,加报告