Find all pairs of integers within an array which sum to a specified value

前端 未结 15 1921
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:00

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

I have tried this problem using a hash

相关标签:
15条回答
  • 2020-12-01 08:34

    Hashtable solution, in Ruby (quite straightforward to understand):

    value = 100
    pairs = [1,99,5,95]
    hash_of_pairs = {}
    
    pairs.map! do |pair|
      # Adds to hashtable the pair
      hash_of_pairs[pair] = pair
    
      # Finds the value the pair needs
      new_pair = hash_of_pairs[value - pair]
    
      # Returns the pair whenever the pair exists, or nil
      [new_pair, pair] if !new_pair.nil?
    end.compact! # Cleans up the array, removing all nil values
    
    print pairs # [[1,99], [5,95]]
    
    0 讨论(0)
  • 2020-12-01 08:35

    Implemented in Python 2.7:

    import itertools
    list = [1, 1, 2, 3, 4, 5,]
    uniquelist = set(list)
    targetsum = 5
    for n in itertools.combinations(uniquelist, 2):
        if n[0] + n[1] == targetsum:
        print str(n[0]) + " + " + str(n[1])
    

    Output:

    1 + 4
    2 + 3
    
    0 讨论(0)
  • 2020-12-01 08:38

    How about sorting the array, then marching in from both ends?

    0 讨论(0)
  • 2020-12-01 08:41
    #include <iostream>
    using namespace std;
    
    #define MAX 15
    
    int main()
    {
     int array[MAX] = {-12,-6,-4,-2,0,1,2,4,6,7,8,12,13,20,24};
     const int find_sum = 0;
     int max_index = MAX - 1;
     int min_index = 0;
     while(min_index < max_index)
     {
      if(array[min_index] + array[max_index-min_index] == find_sum)
      {
       cout << array[min_index] << " & " << array[max_index-min_index] << " Matched" << endl;
       return 0;
      }
      if(array[min_index]+array[max_index-min_index] < find_sum)
      {
       min_index++;
       //max_index++;
      }
      if(array[min_index]+array[max_index-min_index] > find_sum)
      {
       max_index--;
      }
     }
     cout << "NO MATCH" << endl;
     return 0;
    }
    //-12 & 12 matched
    
    0 讨论(0)
  • 2020-12-01 08:42

    Assume required sum = R

    1. sort the array
    2. for each number in the array A(n), do a binary search to find the number A(x) such that A(n) + A(x) = R
    0 讨论(0)
  • 2020-12-01 08:45
    #python 3.x
    def sum_pairs(list_data, number):    
        list_data.sort()
        left = 0
        right = len(list_data)-1
        pairs = []
        while left < right:        
            if list_data[left]+list_data[right] == number:
                find_pairs = [list_data[left], list_data[right]]
                pairs.append(find_pairs)
                right = right-1
            elif list_data[left]+list_data[right] < number:
                left = left+1
            else:
                right = right-1
        return pairs
    
    0 讨论(0)
提交回复
热议问题