A recursive algorithm to find two integers in an array that sums to a given integer

后端 未结 8 1075
Happy的楠姐
Happy的楠姐 2021-01-16 19:36

I need an algorithm to determine if an array contains two elements that sum to a given integer.

The array is sorted.

The algorithm should be recursiv

8条回答
  •  粉色の甜心
    2021-01-16 20:00

    It is pretty easy. It is important for array to be sorted.

    Correct algorithm with O(n) time complexity and no additional space is:

    public static boolean isContainsSum(int[] arr, int sum) {
        for (int i = 0, j = arr.length - 1; i < j; ) {
            if (arr[i] + arr[j] == sum)
                return true;
            if (arr[i] + arr[j] < sum)
                i++;
            else
                j--;
        }
    
        return false;
    }
    

    To make it recursive, you need just replace i and j iterations with recursive call:

    public static boolean isContainsSumRecursive(int[] arr, int sum) {
        return isContainsSumRecursive(arr, sum, 0, arr.length - 1);
    }
    
    private static boolean isContainsSumRecursive(int[] arr, int sum, int i, int j) {
        if (i == j)
            return false;
        if (arr[i] + arr[j] == sum)
            return true;
        if (arr[i] + arr[j] < sum)
            return isContainsSumRecursive(arr, sum, i + 1, j);
        return isContainsSumRecursive(arr, sum, i, j - 1);
    }
    

提交回复
热议问题