当前位置:网站首页>Delete the duplicate items in the array (keep the last duplicate elements and ensure the original order of the array)
Delete the duplicate items in the array (keep the last duplicate elements and ensure the original order of the array)
2022-07-23 07:36:00 【Swarford】
link
The first 21 topic ;

Method 1 : Stack
Backward Traversal , For traversal contain Method to determine whether it already exists ;(Stack Inherited from Vector class ;Vector Realized Iterable and Collection Interface )
Receive and pop up to the new array , Finally, a new array is returned ;
result : adopt 6/8, Run timeout
public int[] removeDuplicate (int[] array) {
// violence
// For the last time , Then reverse traversal
Stack<Integer> s=new Stack<>();
for(int i=array.length-1;i>=0;i--){
if(!s.contains(array[i])){
s.push(array[i]);
}
}
// Put the new array
int n=s.size();
int[] r=new int[n];
// Bomb stack , Just reverse the order
for(int j=0;j<n;j++){
r[j]=s.pop();
}
return r;
}
Method 2 :Set To judge whether or not to repeat + Speed pointer
First traverse in reverse order , Use Set To judge whether or not to repeat , Repeat and set as 0;
Use the speed pointer to delete 0;
The length will be slow Put all the elements of the new array and return ;
public int[] removeDuplicate (int[] array) {
int n=array.length;
Set<Integer> s=new HashSet<>();
// Reverse traversal , Set the repeated to 0
for(int i=n-1;i>=0;i--){
if(s.contains(array[i])){
array[i]=0;
}else{
s.add(array[i]);
}
}
// The speed pointer deletes 0
int slow=0;
int fast=0;
while(fast<n){
if(array[fast]==0){
fast++;
}else{
array[slow]=array[fast];
slow++;
fast++;
}
}
//0~slow Move to new array
int[] r=new int[slow];
for(int i=0;i<slow;i++){
r[i]=array[i];
}
return r;
}
result : adopt 6/8
边栏推荐
猜你喜欢
随机推荐
VR全景动物园,成就不一样的动物园名片
【每日一题】757. 设置交集大小至少为2
银行虚拟人技术应用领域及作用介绍
redis的持久化
Redis common basic configuration files
7. Learn Mysql to select a database
Utools recommendation
[daily question] 757. Set the intersection size to at least 2
《postgresql指南--内幕探索》第一章 数据库集簇、数据库和数据表
Uno/esp8266 for tca9548a module dual channel drive 2 sh1106 1.3 "displays
小程序毕设作品之微信酒店预订小程序毕业设计(6)开题答辩PPT
Custom view: levitation ball and accelerator ball
J9数字论:什么是 Web3.0?Web3.0 有哪些特征?
IP第二次实验 MGRE OSPF
“外卖员的时间没有程序员值钱”:读过书就把自己当人上人?得电
Google cloud and Oracle cloud are "hot"? It is imperative to deploy cross cloud disaster recovery!
面向商用活体检测平台的鲁棒性评估
String in SQL Server_ Implementation of split function
tensorflow2.0稀疏矩阵输入操作
93.(leaflet篇)leaflet态势标绘-进攻方向修改






![[ssm] unified result encapsulation](/img/ff/9528a062d464acee52047598af40c3.png)

