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

后端 未结 8 1062
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:09

    You can convert any iterative algorithm into a recursive one by using (for instance) tail recursion. I'd be more expansive, if it weren't homework. I think you'll understand it from the other post.

    0 讨论(0)
  • 2021-01-16 20:10

    Here is my solution: I iterate until the first number is greater than the expected sum, then until to second one or the sum of two is greater than the expected sum. If I do not want a correct answer, I return {-1,-1} (assuming all numbers are positive integers)

    {
    
    private static int[] sumOfTwo(int[] input, int k) {
        for (int i = 0; i < input.length - 1; i++) {
            int first = input[i];
            for (int j = 1; j < input.length; j++) {
                int second = input[j];
                int sum = first + second;
                if (sum == k) {
                    int[] result = {first, second};
                    return result;
                }
                if (second > k || sum > k) {
                    break;
                }
            }
            if (first > k) {
                break;
            }
        }
        int[] begin = {-1, -1};
        return begin;
    }
    

    }

    0 讨论(0)
提交回复
热议问题