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

后端 未结 8 1191
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: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=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!

提交回复
热议问题