我正在研究面試問題,遇到了這個問題,這真的讓我很困惑。我知道如何做基本的 O(n^2) 解決方案,但 HashTable O(n) 沒有任何意義。static void printpairs(int arr[],int sum) { HashSet<Integer> s = new HashSet<Integer>(); for (int i=0; i<arr.length; ++i) { int temp = sum-arr[i]; // checking for condition if (temp>=0 && s.contains(temp)) { System.out.println("Pair with given sum " + sum + " is (" + arr[i] + ", "+temp+")"); } s.add(arr[i]); } } 令我困惑的部分是其檢查條件的部分。當哈希表中沒有任何內容時,它會執行 s.contains(temp) 。那么它怎么能包含 sum - i 呢?https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/
對這個 HashMap 算法面試題感到困惑
幕布斯6054654
2022-05-12 17:14:19