簡體   English   中英

遞歸:確定數組A中是否有兩個元素的總和為k

[英]Recursion: Determine if there are two elements in an array A that sum to k

我看到這個問題問了很多。 我知道它是如何工作的:我們檢查第一個和最后一個的和。 如果該總和大於k,則為最后一個;如果其小於k,則為first ++。 遞歸進行直到第一個== last或找到總和k為止。 **請注意,數組中的值始終已經按升序排序。

我嘗試使用遞歸,但是每當我運行它時,它總是返回“ false”。 我試過各種大小的數組,所有測試用例都返回false。 例如Array [1 2 3 4 5 6],大小n = 6,k = 7,當它為true時返回false。 我似乎找不到該錯誤。 有人可以給我指示我在哪里犯錯嗎? 如果我沒記錯的話,這可以花O(n)的時間?

public static boolean sum( int[] A, int n, int k ) //where k is the sum needed and n the size of the array
{
     if (k <= A[0] || k >= A[n]*2)
     {
          return false;
     }
     int i = 0;
     int j = n-1;
     return sum_Recursion(A, n, k, i, j);
}


private static boolean sum_Recursion(int[] A, int n, int k, int i, int j) 
{
    if(i == j)
    {
         return false;
    } else if((A[i] + A[j]) == k)       
    {
        return true;
    } else if ((A[i] + A[j]) > k)
    {
        return sum_Recursion(A, n, k, i, j--);
    }
        return sum_Recursion(A, n, k, i++, j);
}

兩個問題:

  1. j--將首先使用j,然后使用-。 它應該是j-1或--j。 與i ++相同。

  2. n參數似乎沒用。 當使用它時,請為邊界索引。

具有正確結果的固定版本:

public static void main(String[] args) {
    int[] a = {1, 2, 3, 4, 5, 6};
    System.out.println(sum(a, 6, 7)); // ==> true
}

public static boolean sum(int[] A, int n, int k) //where k is the sum needed and n the size of the array
{
    if (k <= A[0] || k >= A[n - 1] * 2) {
        return false;
    }
    int i = 0;
    int j = n - 1;
    return sum_Recursion(A, n, k, i, j);
}


private static boolean sum_Recursion(int[] A, int n, int k, int i, int j) {
    if (i == j) {
        return false;
    } else if ((A[i] + A[j]) == k) {
        return true;
    } else if ((A[i] + A[j]) > k) {
        return sum_Recursion(A, n, k, i, j - 1);
    }
    return sum_Recursion(A, n, k, i + 1, j);
}

O(n)算法:

  1. 將數組元素插入到哈希表或哈希圖中
  2. 遍歷數組,然后看到k - currentElement哈希數據結構中存在k - currentElement

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM