java - 面试时问的时间复杂度问题
问题描述
int[] a = {3,5,4,3,2,2,1};
System.out.println("Duplicate elements are: ");
for(int i=0; i<a.length; i++) {
for(int j = i+1; j<a.length; j++) {
if(a[i]==a[j] && i!=j){
System.out.println(a[j] + " ");
}
}
}
这段代码时间复杂度是O(n^2),面试官让我把它改成O(n)。我们怎么能做到这一点?
解决方案
这是一种满足O(n)
要求的解决方案,即使用HashSet
-AHashSet
将不接受重复值,因此您只需要一个循环,即如果要求允许使用声明的HashSet
:
int[] a = {3,5,4,3,2,2,1};
// Create a set
Set<Integer> set = new HashSet<Integer>();
//Create a set for storing duplicates
Set<Integer> setDupes = new HashSet<Integer>();
System.out.println("Duplicate elements are: ");
//loop the array once
for (int num : a)
{
if (set.add(num) == false)
{
// your duplicate element
if(setDupes.add(num) == true)
System.out.println(num + " ");
}
}
推荐阅读
- mysql - 在 MySQL 中获取最近的用户喜欢
- opencv - 如何在 Visual Studio 中使用新的 Realsense SDK2 和 openCV 进行面部跟踪?
- deployment - 使用 GitLab CI/CD 将 Angular 5 应用程序部署到自己的基础设施
- python - Python 脚本 (PyMySQL) 未连接到本地主机上的数据库
- python-3.x - 如何不将输入的数据保存到字典
- ruby-on-rails - Ruby on Rails 中的交叉引用表
- javascript - 从 select 的值添加类在 each() 循环中不起作用
- c# - 二进制到否定转换
- javascript - Pa11y 5 可访问性测试使用无法在反应 js 应用程序中设置表单字段的操作
- javascript - 为 url 清漆正则表达式