📌  相关文章
📜  给定 Array 中三元组的计数,使得任意两个元素的总和是第三个元素

📅  最后修改于: 2021-09-08 12:45:12             🧑  作者: Mango

给定一个未排序的数组arr ,任务是找到不同三元组的计数,其中任意两个元素的总和是第三个元素。

例子:

方法:

  • 对给定数组排序
  • 为数组创建哈希映射以检查特定元素是否存在。
  • 使用两个循环遍历数组以选择不同位置的任意两个元素,并检查这两个元素的总和是否在 O(1) 时间内出现在哈希映射中。
  • 如果哈希映射中存在两个元素的总和,则增加三元组的计数。

下面是上述方法的实现:

C++
// C++ Implementation to find the
// Count the triplets in which sum
// of two elements is the third element
#include 
 
using namespace std;
 
// Function to find the count
// the triplets in which sum
// of two elements is the third element
int triplets(vectorarr)
{
 
    // Dictionary to check a element is
    // present or not in array
    map k;
    map, int> mpp;
 
    // List to check for
    // duplicates of Triplets
    vector> ssd;
 
    // Set initial count to zero
    int count = 0;
 
    // Sort the array
    sort(arr.begin(),arr.end());
 
    int i = 0;
    while (i < arr.size())
    {
 
        // Add all the values as key
        // value pairs to the dictionary
        if (k.find(arr[i]) == k.end())
            k[arr[i]] = 1;
 
        i += 1;
    }
 
    // Loop to choose two elements
    int j = 0;
    while (j < arr.size() - 1)
    {
 
        int q = j + 1;
        while (q < arr.size())
        {
 
            // Check for the sum and duplicate
            if ( k.find(arr[j] + arr[q]) != k.end() and
                mpp[{arr[j], arr[q]}] != arr[j] + arr[q])
            {
 
                count += 1;
 
                ssd.push_back({arr[j], arr[q], arr[j] + arr[q]});
                mpp[{arr[j], arr[q]}] = arr[j] + arr[q];
            }
 
            q += 1;
        }
        j += 1;
    }
    return count;
}
 
 
// Driver Code
int main()
{
    vectorarr = {7, 2, 5, 4, 3, 6, 1, 9, 10, 12};
    int count = triplets(arr);
    printf("%d",count);
    return 0;
}
 
// This code is contributed by mohit kumar 29


Java
// Java implementation to find the
// Count the triplets in which sum
// of two elements is the third element
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
 
class GFG{
     
// Function to find the count the triplets
// in which sum of two elements is the third element
public static int triplets(ArrayList arr)
{
     
      // Dictionary to check a element is
       // present or not in array
    HashSet k = new HashSet<>();
     
      // List to check for
    // duplicates of Triplets
    HashSet> ssd = new HashSet<>();
 
      // Set initial count to zero
    int count = 0;
   
    // Sort the array
    Collections.sort(arr);
 
    int i = 0;
 
      // Add all the values as key
    // value pairs to the dictionary
    while (i < arr.size())
    {
        if (!k.contains(arr.get(i)))
        {
            k.add(arr.get(i));
        }
        i += 1;
    }
    int j = 0;
     
    // Loop to choose two elements
    while (j < arr.size() - 1)
    {
        int q = j + 1;
         
          // Check for the sum and duplicate
        while (q < arr.size())
        {
            ArrayList trip = new ArrayList<>();
            trip.add(arr.get(j));
            trip.add(arr.get(q));
            trip.add(arr.get(j) + arr.get(q));
             
            if (k.contains(arr.get(j) + arr.get(q)) &&
                !ssd.contains(trip))
            {
                count += 1;
                ArrayList nums = new ArrayList<>();
                nums.add(arr.get(j));
                nums.add(arr.get(q));
                nums.add(arr.get(j) + arr.get(q));
                ssd.add(nums);
            }
            q += 1;
        }
        j += 1;
    }
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    ArrayList arr = new ArrayList<>();
    arr.add(7);
    arr.add(2);
    arr.add(5);
    arr.add(4);
    arr.add(3);
    arr.add(6);
    arr.add(1);
    arr.add(9);
    arr.add(10);
    arr.add(12);
     
    int count = triplets(arr);
     
    System.out.println(count);
}
}
 
// This code is contributed by aditya7409


Python3
# Python3 Implementation to find the
# Count the triplets in which sum
# of two elements is the third element
 
# Function to find the count
# the triplets in which sum
# of two elements is the third element
def triplets(arr):
 
    # Dictionary to check a element is
    # present or not in array
    k = set()
     
    # List to check for
    # duplicates of Triplets
    ssd = []
     
    # Set initial count to zero
    count = 0
 
    # Sort the array
    arr.sort()
 
    i = 0
    while i < len(arr):
         
        # Add all the values as key
        # value pairs to the dictionary
        if arr[i] not in k:
            k.add(arr[i])
 
        i += 1
 
    # Loop to choose two elements
    j = 0
    while j < len(arr) - 1:
 
        q = j + 1
        while q < len(arr):
 
            # Check for the sum and duplicate
            if arr[j] + arr[q] in k and\
               [arr[j], arr[q], arr[j] + arr[q]] not in ssd:
 
                count += 1
 
                ssd.append([arr[j], arr[q], arr[j] + arr[q]])
 
            q += 1
        j += 1
 
    return count
 
 
# Driver Code
if __name__ == "__main__":
    arr = [7, 2, 5, 4, 3, 6, 1, 9, 10, 12]
    count = triplets(arr)
    print(count)


C#
// C# Implementation to find the
// Count the triplets in which sum
// of two elements is the third element
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to find the count
  // the triplets in which sum
  // of two elements is the third element
  static int triplets(List arr)
  {
 
    // Dictionary to check a element is
    // present or not in array
    Dictionary k = new Dictionary();
    Dictionary, int> mpp = new Dictionary, int>();
 
    // List to check for
    // duplicates of Triplets
    List> ssd = new List>();
 
    // Set initial count to zero
    int count = 0;
 
    // Sort the array
    arr.Sort();
 
    int i = 0;
    while (i < arr.Count)
    {
 
      // Add all the values as key
      // value pairs to the dictionary
      if (!k.ContainsKey(arr[i]))
        k[arr[i]] = 1;
 
      i += 1;
    }
 
    // Loop to choose two elements
    int j = 0;
    while (j < arr.Count - 1)
    {
      int q = j + 1;
      while (q < arr.Count)
      {
 
        // Check for the sum and duplicate
        if(!k.ContainsKey(arr[j] + arr[q]))
        {
          q += 1;
          continue;
        }
        if (mpp.ContainsKey(new Tuple(arr[j], arr[q])) &&
            mpp[new Tuple(arr[j], arr[q])] != (arr[j] + arr[q]))
        {
          count += 1;   
          ssd.Add(new List(new int[]{arr[j], arr[q], arr[j] + arr[q]}));
          mpp[new Tuple(arr[j], arr[q])] = arr[j] + arr[q];
        }
        else{
          count += 1;
          ssd.Add(new List(new int[]{arr[j], arr[q], arr[j] + arr[q]}));
          mpp[new Tuple(arr[j], arr[q])] = arr[j] + arr[q];
        }    
        q += 1;
      }
      j += 1;
    }
    return count;
  }
 
  // Driver code
  static void Main()
  {
    List arr = new List(new int[]{7, 2, 5, 4, 3, 6, 1, 9, 10, 12});
    int count = triplets(arr);
    Console.Write(count);
  }
}
 
// This code is contributed by divyeshrabadiya07


Javascript


输出:
18

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