📜  计算数组中正和对的对数

📅  最后修改于: 2021-04-29 03:27:07             🧑  作者: Mango

给定N个整数的数组arr [] ,任务是计算具有正和的对数。

例子:

天真的方法:
天真的方法是遍历每个元素,并检查数组arr []中是否存在另一个可以添加到其上的正数和负数。

下面是上述方法的实现:

C++
// Naive approach to count pairs
// with positive sum.
#include 
using namespace std;
  
// Returns number of pairs in
// arr[0..n-1] with positive sum
int CountPairs(int arr[], int n)
{
    // Initialize result
    int count = 0;
  
    // Consider all possible pairs
    // and check their sums
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
  
            // If arr[i] & arr[j]
            // form valid pair
            if (arr[i] + arr[j] > 0)
                count += 1;
        }
    }
  
    return count;
}
  
// Driver's Code
int main()
{
    int arr[] = { -7, -1, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to find the
    // count of pairs
    cout << CountPairs(arr, n);
    return 0;
}


Java
// Java implementation of the above approach
class GFG 
{
          
    // Naive approach to count pairs
    // with positive sum.
      
    // Returns number of pairs in
    // arr[0..n-1] with positive sum
    static int CountPairs(int arr[], int n)
    {
        // Initialize result
        int count = 0;
      
        // Consider all possible pairs
        // and check their sums
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
      
                // If arr[i] & arr[j]
                // form valid pair
                if (arr[i] + arr[j] > 0)
                    count += 1;
            }
        }
      
        return count;
    }
      
    // Driver's Code
    public static void main (String[] args)
    {
        int []arr = { -7, -1, 3, 2 };
        int n = arr.length;
      
        // Function call to find the
        // count of pairs
        System.out.println(CountPairs(arr, n));
    }
}
  
// This code is contributed by Yash_R


Python3
# Naive approach to count pairs
# with positive sum.
  
# Returns number of pairs in
# arr[0..n-1] with positive sum
def CountPairs(arr, n) :
    # Initialize result
    count = 0;
  
    # Consider all possible pairs
    # and check their sums
    for i in range(n) :
        for j in range( i + 1, n) :
  
            # If arr[i] & arr[j]
            # form valid pair
            if (arr[i] + arr[j] > 0) :
                count += 1;
  
    return count;
  
# Driver's Code
if __name__ == "__main__" :
  
    arr = [ -7, -1, 3, 2 ];
    n = len(arr);
  
    # Function call to find the
    # count of pairs
    print(CountPairs(arr, n));
      
# This code is contributed by Yash_R


C++
// C++ program to count the
// pairs with positive sum
#include 
using namespace std;
  
// Returns number of pairs
// in arr[0..n-1] with
// positive sum
int CountPairs(int arr[], int n)
{
    // Sort the array in
    // increasing order
    sort(arr, arr + n);
  
    // Intialise result
    int count = 0;
  
    // Intialise first and
    // second pointer
    int l = 0, r = n - 1;
  
    // Till the pointers
    // doesn't converge
    // traverse array to
    // count the pairs
    while (l < r) {
  
        // If sum of arr[i] &&
        // arr[j] > 0, then the
        // count of pairs with
        // positive sum is the
        // difference between
        // the two pointers
        if (arr[l] + arr[r] > 0) {
  
            // Increase the count
            count += (r - l);
            r--;
        }
        else {
            l++;
        }
    }
    return count;
}
  
// Driver's Code
int main()
{
    int arr[] = { -7, -1, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to count
    // the pairs with positive
    // sum
    cout << CountPairs(arr, n);
    return 0;
}


Python3
# Python3 program to count the 
# pairs with positive sum 
  
# Returns number of pairs 
# in arr[0..n-1] with 
# positive sum 
def CountPairs(arr, n) : 
  
    # Sort the array in 
    # increasing order 
    arr.sort()
  
    # Intialise result 
    count = 0; 
  
    # Intialise first and 
    # second pointer 
    l = 0; r = n - 1; 
  
    # Till the pointers 
    # doesn't converge 
    # traverse array to 
    # count the pairs 
    while (l < r) :
  
        # If sum of arr[i] && 
        # arr[j] > 0, then the 
        # count of pairs with 
        # positive sum is the 
        # difference between 
        # the two pointers 
        if (arr[l] + arr[r] > 0) :
  
            # Increase the count 
            count += (r - l); 
            r -= 1; 
          
        else :
            l += 1; 
              
    return count; 
  
# Driver's Code 
if __name__ == "__main__" : 
  
    arr = [ -7, -1, 3, 2 ]; 
    n = len(arr); 
  
    # Function call to count 
    # the pairs with positive 
    # sum 
    print(CountPairs(arr, n)); 
  
# This code is contributed by Yash_R


输出:
3

时间复杂度: O(N 2 )

高效方法:
这个想法是使用两个指针技术。步骤如下:

  1. 按给定数组arr []的升序排序。
  2. 取两个指针。一个代表已排序数组的第一个元素,第二个代表最后一个元素。
  3. 如果这些指针处的元素之和大于0,则指针之间的差将为第二个指针处的元素给出具有正和的对数。将第二个指针减少1。
  4. 否则,将第一个指针加1。
  5. 重复上述步骤,直到两个指针都朝彼此收敛。

下面是上述方法的实现:

C++

// C++ program to count the
// pairs with positive sum
#include 
using namespace std;
  
// Returns number of pairs
// in arr[0..n-1] with
// positive sum
int CountPairs(int arr[], int n)
{
    // Sort the array in
    // increasing order
    sort(arr, arr + n);
  
    // Intialise result
    int count = 0;
  
    // Intialise first and
    // second pointer
    int l = 0, r = n - 1;
  
    // Till the pointers
    // doesn't converge
    // traverse array to
    // count the pairs
    while (l < r) {
  
        // If sum of arr[i] &&
        // arr[j] > 0, then the
        // count of pairs with
        // positive sum is the
        // difference between
        // the two pointers
        if (arr[l] + arr[r] > 0) {
  
            // Increase the count
            count += (r - l);
            r--;
        }
        else {
            l++;
        }
    }
    return count;
}
  
// Driver's Code
int main()
{
    int arr[] = { -7, -1, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to count
    // the pairs with positive
    // sum
    cout << CountPairs(arr, n);
    return 0;
}

Python3

# Python3 program to count the 
# pairs with positive sum 
  
# Returns number of pairs 
# in arr[0..n-1] with 
# positive sum 
def CountPairs(arr, n) : 
  
    # Sort the array in 
    # increasing order 
    arr.sort()
  
    # Intialise result 
    count = 0; 
  
    # Intialise first and 
    # second pointer 
    l = 0; r = n - 1; 
  
    # Till the pointers 
    # doesn't converge 
    # traverse array to 
    # count the pairs 
    while (l < r) :
  
        # If sum of arr[i] && 
        # arr[j] > 0, then the 
        # count of pairs with 
        # positive sum is the 
        # difference between 
        # the two pointers 
        if (arr[l] + arr[r] > 0) :
  
            # Increase the count 
            count += (r - l); 
            r -= 1; 
          
        else :
            l += 1; 
              
    return count; 
  
# Driver's Code 
if __name__ == "__main__" : 
  
    arr = [ -7, -1, 3, 2 ]; 
    n = len(arr); 
  
    # Function call to count 
    # the pairs with positive 
    # sum 
    print(CountPairs(arr, n)); 
  
# This code is contributed by Yash_R
输出:
3

时间复杂度: O(N * log N)