📌  相关文章
📜  计算具有相同前缀和后缀和的索引对

📅  最后修改于: 2021-09-04 09:41:54             🧑  作者: Mango

给定一个长度为N的数组arr[] ,任务是找到索引对 (i, j) (基于 0 的索引)的计数,使得子数组{arr[0], … arr[i] 的前缀和}等于子数组{arr[N – 1], …, arr[j]} ( 0 ≤ i, j < N) 的后缀和。

例子:

做法:思路是用Hashing来解决这个问题。请按照以下步骤解决问题:

  1. 遍历数组arr[]并计算所有数组索引的前缀和并将它们的频率存储在 HashMap 中。
  2. 反向遍历数组并继续计算每个数组索引的后缀总和
  3. 对于获得的每个后缀和,检查它是否存在于 Map 中。如果发现为真,则将count增加1
  4. 打印获得的计数

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the count of
// index pairs having equal
// prefix and suffix sums
void countPairs(int* arr, int n)
{
    // Maps indices with prefix sums
    unordered_map mp1;
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Update prefix sum
        sum += arr[i];
 
        // Update frequency in Map
        mp1[sum] += 1;
    }
 
    sum = 0;
    int ans = 0;
 
    // Traverse the array in reverse
    for (int i = n - 1; i >= 0; i--) {
 
        // Update suffix sum
        sum += arr[i];
 
        // Check if any prefix sum of
        // equal value exists or not
        if (mp1.find(sum) != mp1.end()) {
            ans += mp1[sum];
        }
    }
 
    // Print the obtained count
    cout << ans;
}
 
// Driver code
int main()
{
 
    // Given array
    int arr[] = { 1, 2, 1, 1 };
 
    // Given size
    int n = sizeof(arr)
            / sizeof(arr[0]);
 
    // Function Call
    countPairs(arr, n);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
 
  // Function to find the count of
  // index pairs having equal
  // prefix and suffix sums
  static void countPairs(int []arr, int n)
  {
 
    // Maps indices with prefix sums
    HashMap mp1 = new HashMap();
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
      // Update prefix sum
      sum += arr[i];
 
      // Update frequency in Map
      if(mp1.containsKey(sum)){
        mp1.put(sum, mp1.get(sum)+1);
      }
      else{
        mp1.put(sum, 1);
      }
    }
 
    sum = 0;
    int ans = 0;
 
    // Traverse the array in reverse
    for (int i = n - 1; i >= 0; i--)
    {
 
      // Update suffix sum
      sum += arr[i];
 
      // Check if any prefix sum of
      // equal value exists or not
      if (mp1.containsKey(sum))
      {
        ans += mp1.get(sum);
      }
    }
 
    // Print the obtained count
    System.out.print(ans);
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given array
    int arr[] = { 1, 2, 1, 1 };
 
    // Given size
    int n = arr.length;
 
    // Function Call
    countPairs(arr, n);
  }
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function to find the count of
# index pairs having equal
# prefix and suffix sums
def countPairs(arr, n):
     
    # Maps indices with prefix sums
    mp1 = {}
    sum = 0
 
    # Traverse the array
    for i in range(n):
         
        # Update prefix sum
        sum += arr[i]
 
        # Update frequency in Map
        mp1[sum] = mp1.get(sum, 0) + 1
 
    sum = 0
    ans = 0
 
    # Traverse the array in reverse
    for i in range(n - 1, -1, -1):
 
        # Update suffix sum
        sum += arr[i]
 
        # Check if any prefix sum of
        # equal value exists or not
        if (sum in mp1):
            ans += mp1[sum]
 
    # Print the obtained count
    print (ans)
 
# Driver code
if __name__ == '__main__':
 
    # Given array
    arr = [ 1, 2, 1, 1 ]
 
    # Given size
    n = len(arr)
 
    # Function Call
    countPairs(arr, n)
 
# This code is contributed by mohit kumar 29


C#
// C# code for above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
  // Function to find the count of
  // index pairs having equal
  // prefix and suffix sums
  static void countPairs(int[] arr, int n)
  {
 
    // Maps indices with prefix sums
    Dictionary mp1 = new Dictionary();
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
      // Update prefix sum
      sum += arr[i];
 
      // Update frequency in Map
      if(mp1.ContainsKey(sum))
      {
        mp1.Add(sum, mp1[sum] + 1);
      }
      else{
        mp1.Add(sum, 1);
      }
    }
 
    sum = 0;
    int ans = 0;
 
    // Traverse the array in reverse
    for (int i = n - 1; i >= 0; i--)
    {
 
      // Update suffix sum
      sum += arr[i];
 
      // Check if any prefix sum of
      // equal value exists or not
      if (mp1.ContainsKey(sum))
      {
        ans += mp1[sum];
      }
    }
 
    // Print the obtained count
    Console.Write(ans);
  }
 
  // Driver code
  static public void Main ()
  {
 
    // Given array
    int[] arr = { 1, 2, 1, 1 };
 
    // Given size
    int n = arr.Length;
 
    // Function Call
    countPairs(arr, n);
  }
}
 
// This code is contributed by offbeat


输出:
3

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live