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

后端 未结 30 1048
暗喜
暗喜 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:41

    Javascript solution:

    var sample_input = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51];
    var result = getNumbersOf(100, sample_input, true, []);
    
    function getNumbersOf(targetNum, numbers, unique, res) {
        var number = numbers.shift();
    
        if (!numbers.length) {
            return res;
        }
    
        for (var i = 0; i < numbers.length; i++) {
            if ((number + numbers[i]) === targetNum) {
                var result = [number, numbers[i]];
                if (unique) {
                  if (JSON.stringify(res).indexOf(JSON.stringify(result)) < 0) {
                    res.push(result);                
                  }
                } else {
                  res.push(result);
                }
                numbers.splice(numbers.indexOf(numbers[i]), 1);
                break;
            }
        }
        return getNumbersOf(targetNum, numbers, unique, res);
    }
    
    0 讨论(0)
  • 2020-11-22 10:42

    Here is Java code for three approaches:
    1. Using Map O(n), HashSet can also be used here.
    2. Sort array and then use BinarySearch to look for complement O(nLog(n))
    3. Traditional BruteForce two loops O(n^2)

    public class PairsEqualToSum {
    
    public static void main(String[] args) {
        int a[] = {1,10,5,8,2,12,6,4};
        findPairs1(a,10);
        findPairs2(a,10);
        findPairs3(a,10);
    
    }
    
    
    //Method1 - O(N) use a Map to insert values as keys & check for number's complement in map
        static void findPairs1(int[]a, int sum){
            Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
            for(int i=0; i<a.length; i++){
                if(pairs.containsKey(sum-a[i]))
                    System.out.println("("+a[i]+","+(sum-a[i])+")");
                else
                   pairs.put(a[i], 0);
            }
        }
    
    
    
    //Method2 - O(nlog(n)) using Sort
    static void findPairs2(int[]a, int sum){
            Arrays.sort(a);
            for(int i=0; i<a.length/2; i++){
                int complement = sum - a[i];
                int foundAtIndex = Arrays.binarySearch(a,complement);
                if(foundAtIndex >0 && foundAtIndex != i) //to avoid situation where binarySearch would find the original and not the complement like "5"
                    System.out.println("("+a[i]+","+(sum-a[i])+")");
            }
     }
    
    //Method 3 - Brute Force O(n^2)
    static void findPairs3(int[]a, int sum){
    
        for(int i=0; i<a.length; i++){
            for(int j=i; j<a.length;j++){
                if(a[i]+a[j] == sum)
                    System.out.println("("+a[i]+","+a[j]+")");
            }
        }
    }
    
    }
    
    0 讨论(0)
  • 2020-11-22 10:42

    A simple Java code snippet for printing the pairs below:

        public static void count_all_pairs_with_given_sum(int arr[], int S){
            if(arr.length < 2){
            return;
        }        
        HashSet values = new HashSet(arr.length);
        for(int value : arr)values.add(value);
        for(int value : arr){
            int difference = S - value;
        if(values.contains(difference) && value<difference){
            System.out.printf("(%d, %d) %n", value, difference);
            }
        }
        }
    
    0 讨论(0)
  • 2020-11-22 10:43

    Solution in java. You can add all the String elements to an ArrayList of strings and return the list. Here I am just printing it out.

    void numberPairsForSum(int[] array, int sum) {
        HashSet<Integer> set = new HashSet<Integer>();
        for (int num : array) {
            if (set.contains(sum - num)) {
                String s = num + ", " + (sum - num) + " add up to " + sum;
                System.out.println(s);
            }
            set.add(num);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:47

    C++11, run time complexity O(n):

    #include <vector>
    #include <unordered_map>
    #include <utility>
    
    std::vector<std::pair<int, int>> FindPairsForSum(
            const std::vector<int>& data, const int& sum)
    {
        std::unordered_map<int, size_t> umap;
        std::vector<std::pair<int, int>> result;
        for (size_t i = 0; i < data.size(); ++i)
        {
            if (0 < umap.count(sum - data[i]))
            {
                size_t j = umap[sum - data[i]];
                result.push_back({data[i], data[j]});
            }
            else
            {
                umap[data[i]] = i;
            }
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 10:50

    int [] arr = {1,2,3,4,5,6,7,8,9,0};

    var z = (from a in arr from b in arr where 10 - a == b select new { a, b }).ToList;

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