当前位置:网站首页>删除数组中的重复项(保留最后一次出现的重复元素并保证数组的原有顺序)
删除数组中的重复项(保留最后一次出现的重复元素并保证数组的原有顺序)
2022-07-22 20:30:00 【斯沃福德】
链接
第21题;

方法一:栈
逆向遍历,遍历时用contain方法判断是否已存在;(Stack继承于Vector类;Vector实现了Iterable和Collection接口)
接收再弹出给新的数组,最后返回新数组;
结果:通过6/8,运行超时
public int[] removeDuplicate (int[] array) {
// 暴力
//最后一次出现,那就逆向遍历
Stack<Integer> s=new Stack<>();
for(int i=array.length-1;i>=0;i--){
if(!s.contains(array[i])){
s.push(array[i]);
}
}
//放入新数组
int n=s.size();
int[] r=new int[n];
//弹栈,正好顺序颠倒过来
for(int j=0;j<n;j++){
r[j]=s.pop();
}
return r;
}
方法二:Set判断是否重复 + 快慢指针
先逆序遍历,使用Set判断是否重复,重复就置为0;
使用快慢指针删除0;
将长度为slow的所有元素放至新数组并返回;
public int[] removeDuplicate (int[] array) {
int n=array.length;
Set<Integer> s=new HashSet<>();
// 倒序遍历,将重复的置为0
for(int i=n-1;i>=0;i--){
if(s.contains(array[i])){
array[i]=0;
}else{
s.add(array[i]);
}
}
// 快慢指针删除数组中的0
int slow=0;
int fast=0;
while(fast<n){
if(array[fast]==0){
fast++;
}else{
array[slow]=array[fast];
slow++;
fast++;
}
}
//0~slow移到新数组
int[] r=new int[slow];
for(int i=0;i<slow;i++){
r[i]=array[i];
}
return r;
}
结果:通过6/8
边栏推荐
猜你喜欢

10个Live Demo都展示了啥?看过没看过的都值得再看一遍

基于以太坊状态数据库的攻击与防御方案

postman “status“: 500, “error“: “Internal Server Error“, “message“: “The request was rejecte“

基于API调用管理的SDN应用层DDoS攻击防御机制

VR全景动物园,成就不一样的动物园名片

图像处理解决方案 veImageX 技术演进之路

企业生产线改善毕业论文【Flexsim仿真实例】

Ambire 钱包开启 Twitter Spaces 系列

Kotlin learning quick start (8) - Delegation

ES6 solves asynchronous problems
随机推荐
启牛老师说给开的vip账户安全吗?
局域网SDN技术硬核内幕 - 02 前传 多核技术为摩尔定律续一秒
Google cloud and Oracle cloud are "hot"? It is imperative to deploy cross cloud disaster recovery!
Cloudwego's design practice in the background platform of flybook management
直播预告 | openGauss的自治运维平台DBMind实践分享
W25Q128FV译文(二)
支持多数不规则用户的隐私保护联邦学习框架
STM32CubeIDE链接脚本讲解
聪明人的游戏提高篇:第三章第二课:因子个数(factor)
Inside the hard core of LAN SDN technology - 15 MPLS implementation of user roaming in the three from thing to person Park
Computer CMD reset network settings CMD command to reset the network
Null and nullptr
面向商用活体检测平台的鲁棒性评估
Persistence of redis
【无标题】
J9数字论:什么是 Web3.0?Web3.0 有哪些特征?
How to adjust the resolution of the computer with two monitors? Skills of setting different resolutions for two monitors
redis的持久化
接口-Fiddler-简介与安装
IP第二次实验 MGRE OSPF