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

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

    There are 3 approaches to this solution:

    Let the sum be T and n be the size of array

    Approach 1:
    The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2).

    Approach 2: 
     A better way would be to sort the array. This takes O(n log n)
    Then for each x in array A, use binary search to look for T-x. This will take O(nlogn).
    So, overall search is  O(n log n)

    Approach 3 :
    The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion.
    Then for every x, we can just look up its complement, T-x, which is O(1).
    Overall the run time of this approach is O(n).


    You can refer more here.Thanks.


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

    this is the implementation of O(n*lg n) using binary search implementation inside a loop.

    #include <iostream>
    
    using namespace std;
    
    bool *inMemory;
    
    
    int pairSum(int arr[], int n, int k)
    {
        int count = 0;
    
        if(n==0)
            return count;
        for (int i = 0; i < n; ++i)
        {
            int start = 0;
            int end = n-1;      
            while(start <= end)
            {
                int mid = start + (end-start)/2;
                if(i == mid)
                    break;
                else if((arr[i] + arr[mid]) == k && !inMemory[i] && !inMemory[mid])
                {
                    count++;
                    inMemory[i] = true;
                    inMemory[mid] = true;
                }
                else if(arr[i] + arr[mid] >= k)
                {
                    end = mid-1;
                }
                else
                    start = mid+1;
            }
        }
        return count;
    }
    
    
    int main()
    {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        inMemory = new bool[10];
        for (int i = 0; i < 10; ++i)
        {
            inMemory[i] = false;
        }
        cout << pairSum(arr, 10, 11) << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 10:54

    My Solution - Java - Without duplicates

        public static void printAllPairSum(int[] a, int x){
        System.out.printf("printAllPairSum(%s,%d)\n", Arrays.toString(a),x);
        if(a==null||a.length==0){
            return;
        }
        int length = a.length;
        Map<Integer,Integer> reverseMapOfArray = new HashMap<>(length,1.0f);
        for (int i = 0; i < length; i++) {
            reverseMapOfArray.put(a[i], i);
        }
    
        for (int i = 0; i < length; i++) {
            Integer j = reverseMapOfArray.get(x - a[i]);
            if(j!=null && i<j){
                System.out.printf("a[%d] + a[%d] = %d + %d = %d\n",i,j,a[i],a[j],x);
            }
        }
        System.out.println("------------------------------");
    }
    
    0 讨论(0)
  • 2020-11-22 10:54

    in C#:

            int[] array = new int[] { 1, 5, 7, 2, 9, 8, 4, 3, 6 }; // given array
            int sum = 10; // given sum
            for (int i = 0; i <= array.Count() - 1; i++)
                if (array.Contains(sum - array[i]))
                    Console.WriteLine("{0}, {1}", array[i], sum - array[i]);
    
    0 讨论(0)
  • 2020-11-22 10:55

    Just attended this question on HackerRank and here's my 'Objective C' Solution:

    -(NSNumber*)sum:(NSArray*) a andK:(NSNumber*)k {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        long long count = 0;
        for(long i=0;i<a.count;i++){
    
            if(dict[a[i]]) {
                count++;
                NSLog(@"a[i]: %@, dict[array[i]]: %@", a[i], dict[a[i]]);
            }
            else{
                NSNumber *calcNum = @(k.longLongValue-((NSNumber*)a[i]).longLongValue);
                dict[calcNum] = a[i];
            }
    
        }
        return @(count);
    }
    

    Hope it helps someone.

    0 讨论(0)
  • 2020-11-22 10:56
    # Let arr be the given array.
    # And K be the give sum
    
    
    for i=0 to arr.length - 1 do
      # key is the element and value is its index.
      hash(arr[i]) = i  
    end-for
    
    for i=0 to arr.length - 1 do
      # if K-th element exists and it's different then we found a pair
      if hash(K - arr[i]) != i  
        print "pair i , hash(K - arr[i]) has sum K"
      end-if
    end-for
    
    0 讨论(0)
提交回复
热议问题