本文实例讲述了java实现删除排序数组中重复元素的方法。分享给大家供大家参考,具体如下:
题目描述:
给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。
不要使用额外的数组空间,必须在原地没有额外空间的条件下完成。
一:通过arraylist解决
时间复杂度和空间复杂度都为o(n)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
arraylist<integer> list = new arraylist<integer>();
// 去掉数组中重复的元素
public int removetheagain01( int [] array) {
if (array == null || array.length == 0 ) {
return 0 ;
} else if (array.length == 1 ) {
return 1 ;
} else {
int i = 0 ;
int n = array.length - 1 ;
while (i <= n) {
if (i == n) {
list.add(array[i]);
i++;
} else {
int j = i + 1 ;
if (array[i] == array[j]) {
while (j <= n && array[i] == array[j]) {
j++;
}
}
list.add(array[i]);
i = j;
}
}
for ( int k = 0 ; k < list.size(); k++) {
array[k] = list.get(k);
}
return list.size();
}
}
|
二:利用system.arraycopy()函数来复制数组
时间复杂度为o(n^2),空间复杂度为o(n)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public int removetheagain02( int [] array) {
if (array == null || array.length == 0 ) {
return 0 ;
} else if (array.length == 1 ) {
return 1 ;
} else {
int end = array.length - 1 ;
for ( int i = 0 ; i <= end; i++) {
if (i < end) {
int j = i + 1 ;
if (array[i] == array[j]) {
while (j <= end && array[i] == array[j]) {
j++;
}
}
system.arraycopy(array, j, array, i + 1 , end - j + 1 );
end -= j - i - 1 ;
}
}
return end + 1 ;
}
}
|
三:借助临时变量解决问题
时间复杂度o(n),空间复杂度o(1)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public int removetheagain03( int [] array) {
if (array == null || array.length == 0 ) {
return 0 ;
} else if (array.length == 1 ) {
return 1 ;
} else {
int temp = array[ 0 ];
int len = 1 ;
for ( int i = 1 ; i < array.length; i++) {
if (temp == array[i]) {
continue ;
} else {
temp = array[i];
array[len] = array[i];
len++;
}
}
return len;
}
}
|
总结:
数组下标(指针)与临时变量,是解决数组相关面试题的两大法宝**
ps:本站还有两款比较简单实用的在线文本去重复工具,推荐给大家使用:
在线去除重复项工具:https://tool.zzvips.com/t/quchong/
在线文本去重复工具:https://tool.zzvips.com/t/txtquchong/
希望本文所述对大家java程序设计有所帮助。
原文链接:https://blog.csdn.net/wu2304211/article/details/52743589
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 71
-
2025-06-04 77
-
2025-05-27 88
-
2025-06-04 17
-
2025-05-29 89
热门评论