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

后端 未结 8 1071
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 19:47

    I think hash is ok, for example, 1,3,7,9,12,14,33...

    if we want sum=21, we hash the numbers into a hash table, So, O(n).

    we iterator them, when we get 7, we let 21-7=14, so we hash 14, we can find it. so 7+14=21,

    we got it!

    0 讨论(0)
  • 2021-01-16 19:51

    Here is the recursion method to perform the groupSum

    public boolean groupSum(int start, int[] nums, int target) 
    {
        if (start >= nums.length) {
        return (target == 0);
    }
    return groupSum(start + 1, nums, target - nums[start]) || groupSum(start + 
    1,nums,target) 
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-16 20:01

    Here is a solution witch takes into account duplicate entries. It is written in javascript and assumes array is sorted. The solution runs in O(n) time and does not use any extra memory aside from variable.

    var count_pairs = function(_arr,x) {
      if(!x) x = 0;
      var pairs = 0;
      var i = 0;
      var k = _arr.length-1;
      if((k+1)<2) return pairs;
      var halfX = x/2; 
      while(i<k) {
        var curK = _arr[k];
        var curI = _arr[i];
        var pairsThisLoop = 0;
        if(curK+curI==x) {
          // if midpoint and equal find combinations
          if(curK==curI) {
            var comb = 1;
            while(--k>=i) pairs+=(comb++);
            break;
          }
          // count pair and k duplicates
          pairsThisLoop++;
          while(_arr[--k]==curK) pairsThisLoop++;
          // add k side pairs to running total for every i side pair found
          pairs+=pairsThisLoop;
          while(_arr[++i]==curI) pairs+=pairsThisLoop;
        } else {
          // if we are at a mid point
          if(curK==curI) break;
          var distK = Math.abs(halfX-curK);
          var distI = Math.abs(halfX-curI);
          if(distI > distK) while(_arr[++i]==curI);
          else while(_arr[--k]==curK);
        }
      }
      return pairs;
    }
    

    I solved this during an interview for a large corporation. They took it but not me. So here it is for everyone.

    Start at both side of the array and slowly work your way inwards making sure to count duplicates if they exist.

    It only counts pairs but can be reworked to

    • use recursion
    • find the pairs
    • find pairs < x
    • find pairs > x

    Enjoy!

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

    Sort the array. Search for the complement of each number (sum-number). Complexity O(nlogn).

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