📌  相关文章
📜  计算数组中包含 i+j= arr[i]+arr[j] 的对

📅  最后修改于: 2021-10-27 08:38:07             🧑  作者: Mango

给定一个整数数组arr[] ,任务是计算所有对(arr[i], arr[j])使得i + j = arr[i] + arr[j]对于所有0 ≤ i < j < .
注意:对 (x, y) 和 (y, x) 被视为一对。

例子:

天真的方法:运行两个嵌套循环并检查每个可能的对,以找到i + j = arr[i] + arr[j] 的条件。如果满足条件,则更新count = count + 1 。最后打印计数
下面是上述方法的实现:

C++
// C++ program to count all the pairs that
// hold the condition i + j = arr[i] + arr[j]
#include 
using namespace std;
 
// Function to return the count of pairs that
// satisfy the given condition
int CountPairs(int arr[], int n)
{
    int count = 0;
 
    // Generate all possible pairs and increment
    // the count if the condition is satisfied
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if ((i + j) == (arr[i] + arr[j]))
                count++;
        }
    }
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 0, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << CountPairs(arr, n);
    return 0;
}


Java
// Java program to count all the pairs that
// hold the condition i + j = arr[i] + arr[j]
 
public class GFG {
     
    // Function to return the count of pairs that
    // satisfy the given condition
    static int CountPairs(int arr[], int n)
    {
        int count = 0;
     
        // Generate all possible pairs and increment
        // the count if the condition is satisfied
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((i + j) == (arr[i] + arr[j]))
                    count++;
            }
        }
        return count;
    }
     
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 0, 3, 2 };
        int n = arr.length ;
        System.out.print(CountPairs(arr, n));
    }
 
    // This code is contributed by Ryuga.
}


Python3
# Python 3 program to count all the pairs that
# hold the condition i + j = arr[i] + arr[j]
 
# Function to return the count of pairs
# that satisfy the given condition
def CountPairs(arr, n):
 
    count = 0;
 
    # Generate all possible pairs and increment
    # the count if the condition is satisfied
    for i in range(n - 1):
        for j in range(i + 1, n):
            if ((i + j) == (arr[i] + arr[j])):
                count += 1;
    return count;
 
# Driver code
arr = [ 1, 0, 3, 2 ];
n = len(arr);
print(CountPairs(arr, n));
 
# This code is contributed
# by Akanksha Rai


C#
using System;
 
// C# program to count all the pairs that
// hold the condition i + j = arr[i] + arr[j]
  
public class GFG {
      
    // Function to return the count of pairs that
    // satisfy the given condition
    static int CountPairs(int[] arr, int n)
    {
        int count = 0;
      
        // Generate all possible pairs and increment
        // the count if the condition is satisfied
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((i + j) == (arr[i] + arr[j]))
                    count++;
            }
        }
        return count;
    }
      
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 0, 3, 2 };
        int n = arr.Length ;
        Console.Write(CountPairs(arr, n));
    }
  
}


PHP


Javascript


C++
#include 
#include 
using namespace std;
 
// Function to return the count of pairs that
// satisfy the given condition
int countValidPairs(int arr[], int n)
{
 
    int i;
 
    // Update all the elements as describde
    // in the approach
    for (i = 0; i < n; i++)
        arr[i] -= i;
 
    // HashMap for storing the frequency of
    // negative elements
    map negMap;
 
    // HashMap for storing the frequency of
    // positive elements (including 0)
    map posMap;
    for (i = 0; i < n; i++)
    {
 
        // For negative elements
        if (arr[i] < 0)
        {
 
            // If HashMap already contains the integer
            // then increment its frequency by 1
            if (negMap.count(arr[i]))
                negMap.insert({arr[i], negMap.find(arr[i])->second + 1});
            else
 
                // Else set the frequency to 1
                negMap.insert({arr[i], 1});
        }
 
        // For positive elements (including 0)
        else
        {
 
            // If HashMap already contains the integer
            // then increment its frequency by 1
            if (posMap.count(arr[i]))
                posMap.insert({arr[i], posMap.find(arr[i])->second + 1});
            else
 
                // Else set the frequency to 1
                posMap.insert({arr[i], 1});
        }
    }
 
    // To store the count of valid pairs
    int count = 0;
 
    for (auto itr = posMap.begin(); itr != posMap.end(); ++itr)
    {
        int posVal = itr->second;
 
        // If an equivalent -ve element is found for
        // the current +ve element
        if (negMap.count(-itr->first))
        {
            int negVal = negMap.find(-itr->first)->second;
 
            // Add all possible pairs to the count
            count += (negVal * posVal);
        }
    }
 
    // Return the count
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countValidPairs(arr, n);
     
}
 
// This code is contributed by ApurvaRaj


Java
import java.util.HashMap;
import java.util.Map;
public class GFG {
 
    // Function to return the count of pairs that
    // satisfy the given condition
    static int countValidPairs(int arr[], int n)
    {
 
        int i;
 
        // Update all the elements as describde
        // in the approach
        for (i = 0; i < n; i++)
            arr[i] -= i;
 
        // HashMap for storing the frequency of
        // negative elements
        Map negMap = new HashMap<>();
 
        // HashMap for storing the frequency of
        // positive elements (including 0)
        Map posMap = new HashMap<>();
        for (i = 0; i < n; i++) {
 
            // For negative elements
            if (arr[i] < 0) {
 
                // If HashMap already contains the integer
                // then increment its frequency by 1
                if (negMap.containsKey(arr[i]))
                    negMap.put(arr[i], negMap.get(arr[i]) + 1);
                else
 
                    // Else set the frequency to 1
                    negMap.put(arr[i], 1);
            }
 
            // For positive elements (including 0)
            else {
 
                // If HashMap already contains the integer
                // then increment its frequency by 1
                if (posMap.containsKey(arr[i]))
                    posMap.put(arr[i], posMap.get(arr[i]) + 1);
                else
 
                    // Else set the frequency to 1
                    posMap.put(arr[i], 1);
            }
        }
 
        // To store the count of valid pairs
        int count = 0;
 
        for (int posKey : posMap.keySet()) {
            int posVal = posMap.get(posKey);
 
            // If an equivalent -ve element is found for
            // the current +ve element
            if (negMap.containsKey(-posKey)) {
                int negVal = negMap.get(-posKey);
 
                // Add all possible pairs to the count
                count += (negVal * posVal);
            }
        }
 
        // Return the count
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 };
        int n = arr.length;
        System.out.println(countValidPairs(arr, n));
    }
}


Python3
# Function to return the count of pairs that
# satisfy the given condition
def countValidPairs(arr, n):
    i = 0
 
    # Update all the elements as described
    # in the approach
    for i in range(n):
        arr[i] -= i
 
    # HashMap for storing the frequency
    # of negative elements
    negMap = dict()
 
    # HashMap for storing the frequency of
    # positive elements (including 0)
    posMap = dict()
    for i in range(n):
 
        # For negative elements
        if (arr[i] < 0):
             
            # If HashMap already contains the integer
            # then increment its frequency by 1
            negMap[arr[i]] = negMap.get(arr[i], 0) + 1
         
        # For positive elements (including 0)
        else:
 
            # If HashMap already contains the integer
            # then increment its frequency by 1
            posMap[arr[i]] = posMap.get(arr[i], 0) + 1
 
    # To store the count of valid pairs
    count = 0
 
    for posKey in posMap:
        posVal = posMap[posKey]
 
        negVal = 0
 
        if -posKey in negMap:
            negVal = negMap[-posKey]
 
        # Add all possible pairs to the count
        count += (negVal * posVal)
 
    # Return the count
    return count
 
# Driver code
arr = [8, 4, 2, 1, 5, 4, 2, 1, 2, 3]
n = len(arr)
print(countValidPairs(arr, n))
 
# This code is contributed
# by mohit kumar


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to return the count
// of pairs that satisfy the given
// condition
static int countValidPairs(int []arr,
                           int n)
{
  int i;
 
  // Update all the elements
  // as described in the approach
  for (i = 0; i < n; i++)
    arr[i] -= i;
 
  // Dictionary for storing the
  // frequency of negative elements
  Dictionary negMap =
             new Dictionary();
 
  // Dictionary for storing the
  // frequency of positive elements
  // (including 0)
  Dictionary posMap =
             new Dictionary();
  for (i = 0; i < n; i++)
  {
    // For negative elements
    if (arr[i] < 0)
    {
      // If Dictionary already
      // contains the integer then
      // increment its frequency by 1
      if (negMap.ContainsKey(arr[i]))
        negMap[arr[i]] = negMap[arr[i]] + 1;
      else
 
        // Else set the frequency to 1
        negMap.Add(arr[i], 1);
    }
 
    // For positive elements (including 0)
    else
    {
      // If Dictionary already contains
      // the integer then increment its
      // frequency by 1
      if (posMap.ContainsKey(arr[i]))
        posMap.Add(arr[i], posMap[arr[i]] + 1);
      else
 
        // Else set the frequency to 1
        posMap.Add(arr[i], 1);
    }
  }
 
  // To store the count of valid pairs
  int count = 0;
 
  foreach (int posKey in posMap.Keys)
  {
    int posVal = posMap[posKey];
 
    // If an equivalent -ve element
    // is found for the current +ve element
    if (negMap.ContainsKey(-posKey))
    {
      int negVal = negMap[-posKey];
 
      // Add all possible pairs to
      // the count
      count += (negVal * posVal);
    }
  }
 
  // Return the count
  return count;
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {8, 4, 2, 1, 5,
               4, 2, 1, 2, 3};
  int n = arr.Length;
  Console.WriteLine(countValidPairs(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
4

有效的方法:

  1. i + j = arr[i] + arr[j] 减少(arr[i] – i) = -(arr[j] – j) 。现在,问题简化为查找(x, -x)形式的所有对。
  2. 因此,根据步骤 1 的缩减,将数组的所有元素更新为arr[i] = arr[i] – i
  3. 为了统计(x, -x)形式的所有对,将所有负元素的频率保存到名为negMap的 HashMap 中,将所有正元素(包括 0)的频率保存到posMap 中
  4. 现在,在posMap每个频率例如x,找到-xnegMap频率。因此, x-x之间的所有可能对都将是count = count + (frequency(x) * frequency(-x))
  5. 最后打印计数

下面是上述方法的实现:

C++

#include 
#include 
using namespace std;
 
// Function to return the count of pairs that
// satisfy the given condition
int countValidPairs(int arr[], int n)
{
 
    int i;
 
    // Update all the elements as describde
    // in the approach
    for (i = 0; i < n; i++)
        arr[i] -= i;
 
    // HashMap for storing the frequency of
    // negative elements
    map negMap;
 
    // HashMap for storing the frequency of
    // positive elements (including 0)
    map posMap;
    for (i = 0; i < n; i++)
    {
 
        // For negative elements
        if (arr[i] < 0)
        {
 
            // If HashMap already contains the integer
            // then increment its frequency by 1
            if (negMap.count(arr[i]))
                negMap.insert({arr[i], negMap.find(arr[i])->second + 1});
            else
 
                // Else set the frequency to 1
                negMap.insert({arr[i], 1});
        }
 
        // For positive elements (including 0)
        else
        {
 
            // If HashMap already contains the integer
            // then increment its frequency by 1
            if (posMap.count(arr[i]))
                posMap.insert({arr[i], posMap.find(arr[i])->second + 1});
            else
 
                // Else set the frequency to 1
                posMap.insert({arr[i], 1});
        }
    }
 
    // To store the count of valid pairs
    int count = 0;
 
    for (auto itr = posMap.begin(); itr != posMap.end(); ++itr)
    {
        int posVal = itr->second;
 
        // If an equivalent -ve element is found for
        // the current +ve element
        if (negMap.count(-itr->first))
        {
            int negVal = negMap.find(-itr->first)->second;
 
            // Add all possible pairs to the count
            count += (negVal * posVal);
        }
    }
 
    // Return the count
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countValidPairs(arr, n);
     
}
 
// This code is contributed by ApurvaRaj

Java

import java.util.HashMap;
import java.util.Map;
public class GFG {
 
    // Function to return the count of pairs that
    // satisfy the given condition
    static int countValidPairs(int arr[], int n)
    {
 
        int i;
 
        // Update all the elements as describde
        // in the approach
        for (i = 0; i < n; i++)
            arr[i] -= i;
 
        // HashMap for storing the frequency of
        // negative elements
        Map negMap = new HashMap<>();
 
        // HashMap for storing the frequency of
        // positive elements (including 0)
        Map posMap = new HashMap<>();
        for (i = 0; i < n; i++) {
 
            // For negative elements
            if (arr[i] < 0) {
 
                // If HashMap already contains the integer
                // then increment its frequency by 1
                if (negMap.containsKey(arr[i]))
                    negMap.put(arr[i], negMap.get(arr[i]) + 1);
                else
 
                    // Else set the frequency to 1
                    negMap.put(arr[i], 1);
            }
 
            // For positive elements (including 0)
            else {
 
                // If HashMap already contains the integer
                // then increment its frequency by 1
                if (posMap.containsKey(arr[i]))
                    posMap.put(arr[i], posMap.get(arr[i]) + 1);
                else
 
                    // Else set the frequency to 1
                    posMap.put(arr[i], 1);
            }
        }
 
        // To store the count of valid pairs
        int count = 0;
 
        for (int posKey : posMap.keySet()) {
            int posVal = posMap.get(posKey);
 
            // If an equivalent -ve element is found for
            // the current +ve element
            if (negMap.containsKey(-posKey)) {
                int negVal = negMap.get(-posKey);
 
                // Add all possible pairs to the count
                count += (negVal * posVal);
            }
        }
 
        // Return the count
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 };
        int n = arr.length;
        System.out.println(countValidPairs(arr, n));
    }
}

蟒蛇3

# Function to return the count of pairs that
# satisfy the given condition
def countValidPairs(arr, n):
    i = 0
 
    # Update all the elements as described
    # in the approach
    for i in range(n):
        arr[i] -= i
 
    # HashMap for storing the frequency
    # of negative elements
    negMap = dict()
 
    # HashMap for storing the frequency of
    # positive elements (including 0)
    posMap = dict()
    for i in range(n):
 
        # For negative elements
        if (arr[i] < 0):
             
            # If HashMap already contains the integer
            # then increment its frequency by 1
            negMap[arr[i]] = negMap.get(arr[i], 0) + 1
         
        # For positive elements (including 0)
        else:
 
            # If HashMap already contains the integer
            # then increment its frequency by 1
            posMap[arr[i]] = posMap.get(arr[i], 0) + 1
 
    # To store the count of valid pairs
    count = 0
 
    for posKey in posMap:
        posVal = posMap[posKey]
 
        negVal = 0
 
        if -posKey in negMap:
            negVal = negMap[-posKey]
 
        # Add all possible pairs to the count
        count += (negVal * posVal)
 
    # Return the count
    return count
 
# Driver code
arr = [8, 4, 2, 1, 5, 4, 2, 1, 2, 3]
n = len(arr)
print(countValidPairs(arr, n))
 
# This code is contributed
# by mohit kumar

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to return the count
// of pairs that satisfy the given
// condition
static int countValidPairs(int []arr,
                           int n)
{
  int i;
 
  // Update all the elements
  // as described in the approach
  for (i = 0; i < n; i++)
    arr[i] -= i;
 
  // Dictionary for storing the
  // frequency of negative elements
  Dictionary negMap =
             new Dictionary();
 
  // Dictionary for storing the
  // frequency of positive elements
  // (including 0)
  Dictionary posMap =
             new Dictionary();
  for (i = 0; i < n; i++)
  {
    // For negative elements
    if (arr[i] < 0)
    {
      // If Dictionary already
      // contains the integer then
      // increment its frequency by 1
      if (negMap.ContainsKey(arr[i]))
        negMap[arr[i]] = negMap[arr[i]] + 1;
      else
 
        // Else set the frequency to 1
        negMap.Add(arr[i], 1);
    }
 
    // For positive elements (including 0)
    else
    {
      // If Dictionary already contains
      // the integer then increment its
      // frequency by 1
      if (posMap.ContainsKey(arr[i]))
        posMap.Add(arr[i], posMap[arr[i]] + 1);
      else
 
        // Else set the frequency to 1
        posMap.Add(arr[i], 1);
    }
  }
 
  // To store the count of valid pairs
  int count = 0;
 
  foreach (int posKey in posMap.Keys)
  {
    int posVal = posMap[posKey];
 
    // If an equivalent -ve element
    // is found for the current +ve element
    if (negMap.ContainsKey(-posKey))
    {
      int negVal = negMap[-posKey];
 
      // Add all possible pairs to
      // the count
      count += (negVal * posVal);
    }
  }
 
  // Return the count
  return count;
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {8, 4, 2, 1, 5,
               4, 2, 1, 2, 3};
  int n = arr.Length;
  Console.WriteLine(countValidPairs(arr, n));
}
}
 
// This code is contributed by Rajput-Ji

Javascript


输出:
1

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程