![](/img/trans.png)
[英]Count number of pairs of two numbers less than or equal to N such that Sum of the digits of numbers of pair is Prime
[英]Sum of two numbers equal to the given number
我有一個隨機順序為正整數的數組。 給定列表中的數字x ,我們需要在列表中找到兩個總和等於x的數字。運行時間必須小於n ^ 2。
{edit}我所做的是,我將所有小於x的一半的數字放在一個數組中,並將大於x的一半的數字放在另一個數組中,所有大於x的數字都被丟棄,然后得出的想法是必須從兩個數組(不是來自單個數組),通過迭代,我可以得到兩個數字。
現在,對於最壞的情況,我幾乎不會感到困惑,因為這種方法很好嗎? 或者,如果有人向我提供了比這更好的指導,我們也可以實現log n或n * log n嗎?
您的解決方案都是錯誤的,並且在O(n^2)
。
x=5
和
arr=[1,2,3,5]
-所需的兩個數字來自一個數組,而不是兩個數組。
arr=[3,3,6]
, x=6
怎么arr=[3,3,6]
,您會將兩個3
s放在一個列表中(例如,不大於x/2
),並且將找不到3+3=6
。 O(n^2)
,因為假定正好有一半的元素大於x
1 ,而一半的元素小於x
。 然后,您需要檢查的組合數為(n/2*n/2) /2 = n^2/8
要在O(nlogn)
解決該問題,請考慮一下,如果給定一個數字arr[i]
來對數據進行排序會發生什么,是否可以有效地找到現在已排序的數組中是否存在一個數字x-arr[i]
?
您甚至可以通過將元素放在哈希集中來將上述情況提高到O(n)
平均情況,現在給定數字y
,是否可以有效地找到xy
是否也在集合中?
編輯:
自從OP編輯問題以來,刪除的部分不再相關,而是添加了新的關注點。
(1)大於已編輯問題中的x/2
。
這是O(n)解決方案,用於找到總和預期目標的第一對數組索引。 當解決方案找到找到總和等於目標的前兩個索引時,該解決方案將停止,如果您需要所有加總到目標的對,則可以使用ArrayList甚至Map,而不是使用int []結果,而是處理完整的數組並返回所有成對的索引。 有一個明顯的假設,即Map的哈希碼功能確實很好,並且沒有太多沖突,因此map操作在O(1)時間內執行。
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] array = new int[] {1,2,4,7,12,67,12,5,9,1,10};
System.out.println(Arrays.toString(sum(array, 68)));
}
public static int[] sum(int[] array, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// n iterations
for (int index = 0; index < array.length; index++) {
// constant
if (map.containsKey(target - array[index])) {
result[1] = index;
// constant
result[0] = map.get(target - array[index]);
return result;
}
// constant
map.put(array[index], index);
}
return result;
}
}
干得好,
使用合並排序對數組進行排序(時間復雜度: n logn
)。 取兩個指針/計數器,例如i
& j
,一個從索引0
開始,另一個從n-1
(假設array的n
大小為n
)。
if array[i]+array[j]=sum
return;
else if (array[i]+array[j]<sum) i++;
else j--;
直到i>j
為止。
總時間復雜度: n logn
/ *時間復雜度= O(n),因為HashMap操作需要O(1)時間* /
public static ArrayList<Integer> twoSum(int[] arr , int target){
if (arr == null){
throw new IllegalArgumentException();
}
ArrayList<Integer> targetHolder = new ArrayList<>();
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0 ; i < arr.length ; i++){
if (map.containsKey(arr[i])){
int index = map.get(arr[i]);
targetHolder.add(index+1);
targetHolder.add(i+1);
}
else{
map.put(target-arr[i], i);
}
}
return targetHolder;
}
public static void main(String[] args) {
int[] A = {1,2,3,4,5,6};
System.out.println(twoSum(A, 6));
}
}
公共無效函數(int []數組,整數和){
for(int i = 0; i < array.length/2; i ++){
for(int j = array.length-1;; j--){
if(array[i]+array[j] < sum) break;
if(array[i]+array[j] == sum) System.out.println(array[i]+" + "+array[j]+" = "+sum);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.