Pac0
0
Q:

find pair in unsorted array which gives sum x

/* Java implementation of simple method to find count of 
pairs with given sum*/
  
import java.util.HashMap; 
  
class Test 
{ 
    static int arr[] = new int[]{1, 5, 7, -1, 5} ; 
      
    // Returns number of pairs in arr[0..n-1] with sum equal 
    // to 'sum' 
    static int getPairsCount(int n, int sum) 
    { 
        HashMap<Integer, Integer> hm = new HashMap<>(); 
  
        // Store counts of all elements in map hm 
        for (int i=0; i<n; i++){ 
              
            // initializing value to 0, if key not found 
            if(!hm.containsKey(arr[i])) 
                hm.put(arr[i],0); 
                  
            hm.put(arr[i], hm.get(arr[i])+1); 
        } 
        int twice_count = 0; 
  
        // iterate through each element and increment the 
        // count (Notice that every pair is counted twice) 
        for (int i=0; i<n; i++) 
        { 
            if(hm.get(sum-arr[i]) != null) 
                twice_count += hm.get(sum-arr[i]); 
  
            // if (arr[i], arr[i]) pair satisfies the condition, 
            // then we need to ensure that the count is 
            // decreased by one such that the (arr[i], arr[i]) 
            // pair is not considered 
            if (sum-arr[i] == arr[i]) 
                twice_count--; 
        } 
  
        // return the half of twice_count 
        return twice_count/2; 
    } 
  
    // Driver method to test the above function 
    public static void main(String[] args) { 
          
        int sum = 6; 
        System.out.println("Count of pairs is " +  
                            getPairsCount(arr.length,sum)); 
          
    } 
} 
// This code is contributed by Gaurav Miglani 
1
// C++ program to check if given array 
// has 2 elements whose sum is equal 
// to the given value 
  
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to check if array has 2 elements 
// whose sum is equal to the given value 
bool hasArrayTwoCandidates(int A[], int arr_size, 
                           int sum) 
{ 
    int l, r; 
  
    /* Sort the elements */
    sort(A, A + arr_size); 
  
    /* Now look for the two candidates in  
       the sorted array*/
    l = 0; 
    r = arr_size - 1; 
    while (l < r) { 
        if (A[l] + A[r] == sum) 
            return 1; 
        else if (A[l] + A[r] < sum) 
            l++; 
        else // A[i] + A[j] > sum 
            r--; 
    } 
    return 0; 
} 
  
/* Driver program to test above function */
int main() 
{ 
    int A[] = { 1, 4, 45, 6, 10, -8 }; 
    int n = 16; 
    int arr_size = sizeof(A) / sizeof(A[0]); 
  
    // Function calling 
    if (hasArrayTwoCandidates(A, arr_size, n)) 
        cout << "Array has two elements with given sum"; 
    else
        cout << "Array doesn't have two elements with given sum"; 
  
    return 0; 
} 
0

New to Communities?

Join the community