gpt4 book ai didi

java - 不使用嵌套循环查找数组中的重复元素

转载 作者:行者123 更新时间:2023-12-01 11:18:53 24 4
gpt4 key购买 nike

我最近接受了一次采访,其中包括以下问题。请帮助提供可能的解决方案。

用 Java 编写一个方法来查找整数数组中的重复元素,而无需使用嵌套循环(for/while/do while 等),也无需使用库函数或标准 API。

最佳答案

嘿,下面的解决方案复杂度为 O(n) 并且工作正常。检查是否有帮助。

public class Main {
public static void main(String[] args) {
int a[] = new int[]{10,3,5,10,5,4,6};
String distinctElement="";
String repetitiveTerms="";
for(int i=0;i<a.length;i++){
if(i==0){
distinctElement+=a[i]+" ";
}
else if(distinctElement.contains(""+a[i])){
repetitiveTerms+=a[i]+" ";
}
else{
distinctElement+=a[i]+" ";
}
}

}
}

关于java - 不使用嵌套循环查找数组中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com