📜  在不改变平均值的情况下可以从 Array 中移除的对数

📅  最后修改于: 2022-05-13 01:56:09.482000             🧑  作者: Mango

在不改变平均值的情况下可以从 Array 中移除的对数

给定一个大小为N的数组arr[]任务是找出数组的对数,删除后数组的均值(即所有元素的平均值)保持不变。

例子:

方法:考虑以下观察:

可以按照以下步骤来解决问题 -

  • 计算给定数组的平均值
  • 计算所需的总和S2*mean
  • 如果S不是整数,则返回0 ,因为不会有任何对具有非整数和。
  • 否则,通过散列找到许多所需的对。

下面是上述方法的实现:

C++
// C++ code to implement the above approach
#include 
using namespace std;
 
// Function to calculate the number
// of pairs of positions [i, j] (i 0) {
        return 0;
    }
    else {
 
        // Initialising count variable to
        // store total number of valid pairs
        int count = 0;
 
        // Declaring a map to calculate
        // number of pairs with required sum
        map mp;
 
        // Standard procedure to calculate
        // total number of pairs
        // of required sum
        for (int i = 0; i < n; i++) {
            if (i > 0) {
                count += mp[required_sum
                            - A[i]];
            }
            mp[A[i]]++;
        }
 
        // Returning count
        return count;
    }
 
    // If no pairs with required sum
    return 0;
}
 
// Driver code
int main()
{
    int N = 5;
    int arr[] = { 1, 4, 7, 3, 5 };
    int numberOfPairs = countPairs(N, arr);
    cout << numberOfPairs;
    return 0;
}


Python
# Python code to implement the above approach
 
# Function to calculate the number
# of pairs of positions [i, j] (i 0):
        return 0
         
    else:
 
        # Initialising count variable to
        # store total number of valid pairs
        count = 0
 
        # Declaring a map to calculate
        # number of pairs with required sum
        mp = {}
 
        # Standard procedure to calculate
        # total number of pairs
        # of required sum
        for i in range(0, n):
            if (i > 0 and required_sum - A[i] in mp):
                count += mp[required_sum - A[i]]
             
            if arr[i] in mp:
                mp[arr[i]] += 1
            else:
                mp[arr[i]] = 1
 
        # Returning count
        return count
 
    # If no pairs with required sum
    return 0
 
# Driver code
 
N = 5
arr = [ 1, 4, 7, 3, 5 ]
numberOfPairs = countPairs(N, arr)
print(numberOfPairs)
 
# This code is contributed by Samim Hossain Mondal.


Javascript



输出
2

时间复杂度 O(N)
辅助空间 O(N)