gpt4 book ai didi

Java 整数数组中的重复项

转载 作者:行者123 更新时间:2023-12-02 06:41:47 24 4
gpt4 key购买 nike

我需要查找是否有 int[]数组包含重复项。我无法使用集合。

我的解决方案(不起作用)是:

boolean containsDuplicates(int[]list1, int[]list2) {
if (list1.length != list2.length) {
return false;
}
for (int i = 0; i < list1.length; i++) {
if (list1[i] != list2[i]) {
return false;
}
}
return true;
}

最佳答案

一种解决方案,计算周期不是最好的,但没有内存开销:

  1. 使用索引 M 将数组 A 从 0 迭代到 N 的循环
  2. 使用索引 S 将 A 从 M+1 迭代到 N 的嵌套循环
  3. if( A[M]=A[S] ) 返回 true
  4. 返回 false(未找到重复项)

关于Java 整数数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076615/

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