Find 2 numbers in an unsorted array equal to a given sum

前端 未结 18 746
太阳男子
太阳男子 2020-11-29 19:56

We need to find pair of numbers in an array whose sum is equal to a given value.

A = {6,4,5,7,9,1,2}

Sum = 10 Then the pairs are - {6,4} ,

相关标签:
18条回答
  • 2020-11-29 20:15

    The following code returns true if two integers in an array match a compared integer.

     function compareArraySums(array, compare){
    
            var candidates = [];
    
            function compareAdditions(element, index, array){
                if(element <= y){
                    candidates.push(element);
                }
            }
    
            array.forEach(compareAdditions);
    
            for(var i = 0; i < candidates.length; i++){
                for(var j = 0; j < candidates.length; j++){
                    if (i + j === y){
                        return true;
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-29 20:20

    Use in-place radix sort and OP's first solution with 2 iterators, coming towards each other.

    If numbers in the array are not some sort of multi-precision numbers and are, for example, 32-bit integers, you can sort them in 2*32 passes using practically no additional space (1 bit per pass). Or 2*8 passes and 16 integer counters (4 bits per pass).


    Details for the 2 iterators solution:

    First iterator initially points to first element of the sorted array and advances forward. Second iterator initially points to last element of the array and advances backward.

    If sum of elements, referenced by iterators, is less than the required value, advance first iterator. If it is greater than the required value, advance second iterator. If it is equal to the required value, success.

    Only one pass is needed, so time complexity is O(n). Space complexity is O(1). If radix sort is used, complexities of the whole algorithm are the same.


    If you are interested in related problems (with sum of more than 2 numbers), see "Sum-subset with a fixed subset size" and "Finding three elements in an array whose sum is closest to an given number".

    0 讨论(0)
  • 2020-11-29 20:21
    `package algorithmsDesignAnalysis;
    
     public class USELESStemp {
     public static void main(String[] args){
        int A[] = {6, 8, 7, 5, 3, 11, 10}; 
    
        int sum = 12;
        int[] B = new int[A.length];
        int Max =A.length; 
    
        for(int i=0; i<A.length; i++){
            B[i] = sum - A[i];
            if(B[i] > Max)
                Max = B[i];
            if(A[i] > Max)
                Max = A[i];
    
            System.out.print(" " + B[i] + "");
    
        } // O(n) here; 
    
        System.out.println("\n Max = " + Max);
    
        int[] Array = new int[Max+1];
        for(int i=0; i<B.length; i++){
            Array[B[i]] = B[i];
        } // O(n) here;
    
        for(int i=0; i<A.length; i++){  
        if (Array[A[i]] >= 0)
            System.out.println("We got one: " + A[i] +" and " + (sum-A[i]));
        } // O(n) here;
    
    } // end main();
    
    /******
    Running time: 3*O(n)
    *******/
    }
    
    0 讨论(0)
  • 2020-11-29 20:22
    public static ArrayList<Integer> find(int[] A , int target){
        HashSet<Integer> set = new HashSet<Integer>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        int diffrence = 0;
        for(Integer i : A){
            set.add(i);
        }
        for(int i = 0; i <A.length; i++){
            diffrence = target- A[i];
        if(set.contains(diffrence)&&A[i]!=diffrence){
            list.add(A[i]);
            list.add(diffrence);
            return list;
        }
         }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-29 20:24

    If you assume that the value M to which the pairs are suppose to sum is constant and that the entries in the array are positive, then you can do this in one pass (O(n) time) using M/2 pointers (O(1) space) as follows. The pointers are labeled P1,P2,...,Pk where k=floor(M/2). Then do something like this

    for (int i=0; i<N; ++i) {
      int j = array[i];
      if (j < M/2) {
        if (Pj == 0)
          Pj = -(i+1);   // found smaller unpaired
        else if (Pj > 0)
          print(Pj-1,i); // found a pair
          Pj = 0;
      } else
        if (Pj == 0)
          Pj = (i+1);    // found larger unpaired
        else if (Pj < 0)
          print(Pj-1,i); // found a pair
          Pj = 0;
      }
    }
    

    You can handle repeated entries (e.g. two 6's) by storing the indices as digits in base N, for example. For M/2, you can add the conditional

      if (j == M/2) {
        if (Pj == 0)
          Pj = i+1;      // found unpaired middle
        else
          print(Pj-1,i); // found a pair
          Pj = 0;
      } 
    

    But now you have the problem of putting the pairs together.

    0 讨论(0)
  • 2020-11-29 20:24

    // Java implementation using Hashing import java.io.*;

    class PairSum { private static final int MAX = 100000; // Max size of Hashmap

    static void printpairs(int arr[],int sum)
    {
        // Declares and initializes the whole array as false
        boolean[] binmap = new boolean[MAX];
    
        for (int i=0; i<arr.length; ++i)
        {
            int temp = sum-arr[i];
    
            // checking for condition
            if (temp>=0 && binmap[temp])
            {
                System.out.println("Pair with given sum " +
                                    sum + " is (" + arr[i] +
                                    ", "+temp+")");
            }
            binmap[arr[i]] = true;
        }
    }
    
    // Main to test the above function
    public static void main (String[] args)
    {
        int A[] = {1, 4, 45, 6, 10, 8};
        int n = 16;
        printpairs(A,  n);
    }
    

    }

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