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

后端 未结 8 1198
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条回答
  •  旧时难觅i
    2021-01-16 19:59

    Normally I'd use a Map, but since one of the requirements is to use a linear data structure, I think that's excluded, so I'd go about using a boolean array.

    public boolean hasSum( int[] numbers, int target )
    {
        boolean[] hits = new boolean[ target + 1 ];
        return hasSumRecursive( 0, numbers, target, hits );
    }
    
    public boolean hasSumRecursive( int index, int[] numbers, int target, boolean[] hits )
    {
        ...
    }
    

    Hopefully this is a good enough hint.

提交回复
热议问题