find pair of numbers in array that add to given sum

前端 未结 19 2154
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  一整个雨季
    2020-11-30 20:44

    Here is a solution witch takes into account duplicate entries. It is written in javascript and runs using sorted and unsorted arrays. The solution runs in O(n) time.

    var count_pairs_unsorted = function(_arr,x) {
      // setup variables
      var asc_arr = [];
      var len = _arr.length;
      if(!x) x = 0;
      var pairs = 0;
      var i = -1;
      var k = len-1;
      if(len<2) return pairs;
      // tally all the like numbers into buckets
      while(i-1){
        var y;
        if(i1) {
            if(_arr[i]==y) {
              var comb = 1;
              while(--asc_arr[_arr[i]] > 0) {pairs+=(comb++);}
            } else pairs+=asc_arr[_arr[i]]*asc_arr[y];
            asc_arr[y] = 0;
            asc_arr[_arr[i]] = 0;
          }
    
        }
        if(k>-1) {
          y = x-_arr[k];
          if(asc_arr[y]!=undefined&&(asc_arr[y]+asc_arr[_arr[k]])>1) {
            if(_arr[k]==y) {
              var comb = 1;
              while(--asc_arr[_arr[k]] > 0) {pairs+=(comb++);}
            } else pairs+=asc_arr[_arr[k]]*asc_arr[y];
            asc_arr[y] = 0;
            asc_arr[_arr[k]] = 0;
          }
    
        }
        i++;
        k--;
      }
      return pairs;
    }
    

    Start at both side of the array and slowly work your way inwards keeping a count of how many times each number is found. Once you reach the midpoint all numbers are tallied and you can now progress both pointers counting the pairs as you go.

    It only counts pairs but can be reworked to

    • find the pairs
    • find pairs < x
    • find pairs > x

    Enjoy!

提交回复
热议问题