[英]How can I find two elements in an array that sum to k
假設給定一個未排序整數數組,如下所示
A = {3,4,5,1,4,2}
輸入: 6
輸出: {5,1}, {4,2}
如何在O(n)或O(log n)中執行此操作。 任何建議將不勝感激。
更新:我們能寫出比這更有效的東西嗎?
for(int i=0;i<array.length-1;i++)
{
if(array[i]+array[i+1]==6)
System.out.println("{"+array[i]+","+array[i+1]+"}");
}
如果存儲在輸入數組中的數字僅為正數,那么我將創建另一個由k + 1個ArrayList元素組成的數組K。 其中k是您需要它們加起來的數字。 只有少於k的兩個數字可以加起來為k(假設我們處理正整數)或在特殊情況下為{0,k}。然后,我將遍歷輸入數組的所有元素,並且對於每個整數m小於或等於k我將獲取其索引,並將該索引添加到索引m處的ArrayList K數組中。然后,我將遍歷數組K的前半部分,對於其中存儲了一些整數的每個索引i,我都會找到互補索引[ ki],看看其中是否有值。如果有,那就是您的對。再者,這是O(n)。
public static void findElemtsThatSumTo( int data[], int k){
List arrayK[]= new List[k+1];
for(int i=0; i<arrayK.length; i++)
arrayK[i]= new ArrayList<Integer>();
for(int i=0; i<data.length; i++){
if(data[i]<=k)
arrayK[data[i]].add(i);
}
for(int i=0; i<arrayK.length/2; i++){
if(!arrayK[i].isEmpty() && !arrayK[k-i].isEmpty())
{
for(Object index: arrayK[i])
for(Object otherIndex: arrayK[k-i])
System.out.println("Numbers at indeces ["+index.toString()+", "+otherIndex.toString()+"] add up to "+k+".");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={4,2,6,8,9,3,1};
int sum=10;
int arr1[]=new int[sum];
for(int x=0;x<arr.length;x++)
{
arr1[arr[x]]++;
}
for(int y=0;y<arr.length;y++)
{
if(arr1[sum-arr[y]]==1)
{
System.out.println(arr[y]+","+(sum-arr[y]));
}
}
}
關於O(n)復雜度和O(n)附加內存,我對此問題的回答不多。 此代碼段返回所有總和為K的元素的唯一索引對。
/**
* Returns indices of all complementary pairs in given {@code arr} with factor {@code k}. Two elements {@code arr[i]} and {@code arr[j]} are
* complementary if {@code arr[i] + arr[j] = k}.
* Method returns set of pairs in format {@literal [i,j]}. Two pairs {@literal [i,j]} and {@literal [j,i]} are treated as same, and only one pair
* is returned.
* Method support negative numbers in the {@code arr}, as wel as negative {@code k}.
* <p>
* Complexity of this method is <t>O(n)</t>, requires <t>O(n)</t> additional memory.
*
* @param arr source array
* @param k factor number
* @return not {@code null} set of all complementary pairs in format {@literal [i,j]}
*/
public static Set<String> getComplementaryPairs(int[] arr, int k) {
if (arr == null || arr.length == 0)
return Collections.emptySet();
Map<Integer, Set<Integer>> indices = new TreeMap<>();
for (int i = 0; i < arr.length; i++) {
if (!indices.containsKey(arr[i]))
indices.put(arr[i], new TreeSet<>());
indices.get(arr[i]).add(i);
}
Set<String> res = new LinkedHashSet<>();
for (Map.Entry<Integer, Set<Integer>> entry : indices.entrySet()) {
int x = entry.getKey();
int y = k - x;
if (x == y) {
int size = entry.getValue().size();
if (size < 2)
continue;
Integer[] ind = entry.getValue().toArray(new Integer[size]);
for (int j = 0; j < size - 1; j++)
for (int m = j + 1; m < size; m++)
res.add(String.format("[%d,%d]", ind[j], ind[m]));
} else if (x < y && indices.containsKey(y))
for (int j : entry.getValue())
for (int m : indices.get(y))
res.add(String.format("[%d,%d]", j, m));
}
return res;
}
與其他問題一樣,O(log n )是不可能的,因為您必須檢查整個數組。 但是O(n)或多或少是可能的。
如果您可能的整數范圍相對較小(也就是說,它在n的恆定因子之內),則可以編寫:
final boolean[] seen = new boolean[max - min + 1];
for(final int a : A)
{
if(seen[input - a - min])
System.out.println("{" + (input - a) + "," + a + "}");
seen[a - min] = true;
}
如果不是,則可以執行相同的操作,但是使用HashSet<Integer>
而不是數組:
final Set<Integer> seen = new HashSet<Integer>();
for(final int a : A)
{
if(seen.contains(input - a))
System.out.println("{" + (input - a) + "," + a + "}");
seen.add(a);
}
但這並不能保證 O(n)時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.