[英]How to make java nested loops efficient
我目前需要編寫一個程序來進行成對比較以在 int 列表中找到匹配對,但我能想到的唯一方法是通過嵌套的 for 循環。 有沒有辦法使嵌套 for 循環的時間復雜度為 O(n) 而不是 O(n^2)?
int[] arr = new int[n];
int total = 0;
for (int i=0; i<n; i++){
for (int j=i+1; j<n; j++){
if (arr[i] == arr[j]){
total++;
}
}
}
看起來你只擔心計數。 因此,如果修改數組不是問題,則在 O(nlog(n)) 中應用快速排序,然后在 O(n) 中計算鄰居。
您可以使用具有O(1)
復雜度的HashSet
contains
方法 - 因為 Java 中Integer
值的hashCode
分布良好(它只是Integer
的值)您應該始終具有恆定的復雜性
HashSet<Integer> set = new HashSet();
for (int i=0; i<n; i++) {
if(set.contains(arr[i])) {
total++;
} else {
set.add(arr[i]);
}
}
在這里閱讀更多:
還有一種可以在此處實現的附加算法,但它需要一些數據限制(由於您機器上數組的最大長度)。
您可以只創建一個 int 數組yourarray
並用0
初始化,長度為max(arr) + 1
。 然后你在每次執行yourarray[arr[i]]++
時迭代arr
然后你在迭代yourarray
檢查值大於1
的位置 - 如果是這樣那么它意味着這個值必須重復
O(n) 解決方案。 嘗試這個。
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 3, 2, 3};
int total = arr.length - (int)IntStream.of(arr).distinct().count();
System.out.println(total);
}
output:
3
我認為您可以使用 HashSet 來解決此問題。 JAVA 中的 HashSet 不允許插入重復元素。 所以你可以用它來使時間復雜度變成 O(n)。
int[] arr = new int[n];
Set<Integer> set = new HashSet<Integer>();
Integer total = 0;
for (int x: arr)
{
if (!set.add(x))
{
total++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.