![](/img/trans.png)
[英]Find sum of possible subarray combinations given min and max values don't exceed k
[英]Given a list 1, 4, 5,9,2 write a program to find possible combinations of two values where sum = 6
給定數組a = [1,4,5,9,2]。我需要查找/打印兩個總和為6的值的組合。
我的代碼如下:(它是O(n ^ 2),效率不高)。 任何更好的解決方案-
for(int out=0;out<a.length-1;out++)
{
for(int in=out+1;in<N;in++)
{
if(a[out]+a[in]==6)
{
System.out.println("The 2 numbers are: "+ a[out] +", "+ a[in]);
}
}
}
HashSet
。 val
檢查HashSet
是否包含6-val
。 我沒有顯示代碼,因為這看起來像是作業(如果是的話,請這樣標記)。
同樣,對於短數組,您幾乎可以肯定的是O(n^2)
解決方案會比這快。
for(int out=0;out<a.length-1;out++)
{
int value = a[out];
int required = 6 - value;
//now check if the required number is in the array
}
首先,srock給出的解決方案應如下所示
int length = a.length;
for(int out = 0; out < length ; out++) {
for(int inn = 0; inn < length; inn ++) {
if ((inn != out) && ((a[inn] + a[out]) == 6))
sysout("The valid combination is "+a[inn]+" "+a[out])
}
}
當然,這需要迭代length * length次。 正如aix所提到的,如果我們將Hashset與contains一起使用,則只會重復長度no次,並且contains方法將使用哈希碼直接轉到存儲桶位置,並將獲取要比較的數據。 因此,此HashSet :: contains方法最適合無大量數據的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.