Find a pair of elements from an array whose sum equals a given number

后端 未结 30 1004
暗喜
暗喜 2020-11-22 10:14

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

The following is my solution, it is O(nLo

相关标签:
30条回答
  • 2020-11-22 10:59

    Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:

    def find_sum(arr,sum)
     result ={}
     h = Hash[arr.map {|i| [i,i]}]
     arr.each { |l| result[l] = sum-l  if h[sum-l] && !result[sum-l]  }
     result
    end
    

    To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l] instruction

    0 讨论(0)
  • 2020-11-22 10:59

    I can do it in O(n). Let me know when you want the answer. Note it involves simply traversing the array once with no sorting, etc... I should mention too that it exploits commutativity of addition and doesn't use hashes but wastes memory.


    using System; using System.Collections.Generic;

    /* An O(n) approach exists by using a lookup table. The approach is to store the value in a "bin" that can easily be looked up(e.g., O(1)) if it is a candidate for an appropriate sum.

    e.g.,

    for each a[k] in the array we simply put the it in another array at the location x - a[k].

    Suppose we have [0, 1, 5, 3, 6, 9, 8, 7] and x = 9

    We create a new array,

    indexes value

    9 - 0 = 9     0
    9 - 1 = 8     1
    9 - 5 = 4     5
    9 - 3 = 6     3
    9 - 6 = 3     6
    9 - 9 = 0     9
    9 - 8 = 1     8
    9 - 7 = 2     7
    

    THEN the only values that matter are the ones who have an index into the new table.

    So, say when we reach 9 or equal we see if our new array has the index 9 - 9 = 0. Since it does we know that all the values it contains will add to 9. (note in this cause it's obvious there is only 1 possible one but it might have multiple index values in it which we need to store).

    So effectively what we end up doing is only having to move through the array once. Because addition is commutative we will end up with all the possible results.

    For example, when we get to 6 we get the index into our new table as 9 - 6 = 3. Since the table contains that index value we know the values.

    This is essentially trading off speed for memory. */

    namespace sum
    {
        class Program
        {
            static void Main(string[] args)
            {
                int num = 25;
                int X = 10;
                var arr = new List<int>();
                for(int i = 0; i <= num; i++) arr.Add((new Random((int)(DateTime.Now.Ticks + i*num))).Next(0, num*2));
                Console.Write("["); for (int i = 0; i < num - 1; i++) Console.Write(arr[i] + ", "); Console.WriteLine(arr[arr.Count-1] + "] - " + X);
                var arrbrute = new List<Tuple<int,int>>();
                var arrfast = new List<Tuple<int,int>>();
    
                for(int i = 0; i < num; i++)
                for(int j = i+1; j < num; j++)
                    if (arr[i] + arr[j] == X) 
                        arrbrute.Add(new Tuple<int, int>(arr[i], arr[j]));
    
    
    
    
                int M = 500;
                var lookup = new List<List<int>>();
                for(int i = 0; i < 1000; i++) lookup.Add(new List<int>());
                for(int i = 0; i < num; i++)        
                {
                    // Check and see if we have any "matches"
                    if (lookup[M + X - arr[i]].Count != 0)
                    {
                        foreach(var j in lookup[M + X - arr[i]])
                        arrfast.Add(new Tuple<int, int>(arr[i], arr[j])); 
                    }
    
                    lookup[M + arr[i]].Add(i);
    
                }
    
                for(int i = 0; i < arrbrute.Count; i++)
                    Console.WriteLine(arrbrute[i].Item1 + " + " + arrbrute[i].Item2 + " = " + X);
                Console.WriteLine("---------");
                for(int i = 0; i < arrfast.Count; i++)
                    Console.WriteLine(arrfast[i].Item1 + " + " + arrfast[i].Item2 + " = " + X);
    
                Console.ReadKey();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:01

    Another solution in Swift: the idea is to create an hash that store values of (sum - currentValue) and compare this to the current value of the loop. The complexity is O(n).

    func findPair(list: [Int], _ sum: Int) -> [(Int, Int)]? {
        var hash = Set<Int>() //save list of value of sum - item.
        var dictCount = [Int: Int]() //to avoid the case A*2 = sum where we have only one A in the array
        var foundKeys  = Set<Int>() //to avoid duplicated pair in the result.
    
        var result = [(Int, Int)]() //this is for the result.
        for item in list {
    
            //keep track of count of each element to avoid problem: [2, 3, 5], 10 -> result = (5,5)
            if (!dictCount.keys.contains(item)) {
                dictCount[item] = 1
            } else {
                dictCount[item] = dictCount[item]! + 1
            }
    
            //if my hash does not contain the (sum - item) value -> insert to hash.
            if !hash.contains(sum-item) {
                hash.insert(sum-item)
            }
    
            //check if current item is the same as another hash value or not, if yes, return the tuple.
            if hash.contains(item) &&
                (dictCount[item] > 1 || sum != item*2) // check if we have item*2 = sum or not.
            {
                if !foundKeys.contains(item) && !foundKeys.contains(sum-item) {
                    foundKeys.insert(item) //add to found items in order to not to add duplicated pair.
                    result.append((item, sum-item))
                }
            }
        }
        return result
    }
    
    //test:
    let a = findPair([2,3,5,4,1,7,6,8,9,5,3,3,3,3,3,3,3,3,3], 14) //will return (8,6) and (9,5)
    
    0 讨论(0)
  • 2020-11-22 11:02

    A simple python version of the code that find a pair sum of zero and can be modify to find k:

    def sumToK(lst):
        k = 0  # <- define the k here
        d = {} # build a dictionary 
    
    # build the hashmap key = val of lst, value = i
    for index, val in enumerate(lst):
        d[val] = index
    
    # find the key; if a key is in the dict, and not the same index as the current key
    for i, val in enumerate(lst):
        if (k-val) in d and d[k-val] != i:
            return True
    
    return False
    

    The run time complexity of the function is O(n) and Space: O(n) as well.

    0 讨论(0)
  • 2020-11-22 11:03

    This prints the pairs and avoids duplicates using bitwise manipulation.

    public static void findSumHashMap(int[] arr, int key) {
        Map<Integer, Integer> valMap = new HashMap<Integer, Integer>();
        for(int i=0;i<arr.length;i++)
            valMap.put(arr[i], i);
    
        int indicesVisited = 0; 
        for(int i=0;i<arr.length;i++) {
            if(valMap.containsKey(key - arr[i]) && valMap.get(key - arr[i]) != i) {
                if(!((indicesVisited & ((1<<i) | (1<<valMap.get(key - arr[i])))) > 0)) {
                    int diff = key-arr[i];
                    System.out.println(arr[i] + " " +diff);
                    indicesVisited = indicesVisited | (1<<i) | (1<<valMap.get(key - arr[i]));
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:05

    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

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

    Enjoy!

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