📌  相关文章
📜  从排序数组中计算三元组,相邻元素之间的差异等于 D

📅  最后修改于: 2021-09-06 06:21:16             🧑  作者: Mango

给定一个由N 个正整数和一个整数D组成的排序数组arr[] ,任务是找到三元组(i, j, k) 的数量,使得arr[j] – arr[i] = Darr[k ] – arr[j] = D并且0 ≤ i < j < k < N

例子:

朴素的方法:解决这个问题的最简单的方法是生成给定数组的所有三元组,并计算相邻元素之间差异为 D(= 3) 的那些三元组。

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

有效的方法:上述方法也可以通过将数组的每个元素视为三元组的最后一个元素并检查前两个元素即(arr[i] – D)(arr[i] – 2 * D) 是否存在于数组中。请按照以下步骤解决问题。

  • 初始化一个 HashMap,比如存储数组元素频率的M。
  • 初始化一个变量,比如ans0
  • 遍历给定的数组arr[]并执行以下步骤:
    • arr[i]在 HashMap M 中的频率增加1
    • 现在,检查元素(arr[i] – D)(arr[i] – 2 * D)是否存在于 HashMap 中。如果发现为true ,则将ans的值增加freq[arr[i] – D] * freq[arr[i] – 2 * D]
  • 完成上述步骤后,打印ans的值作为数组中三元组的结果计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
int countTriplets(int D, vector& arr)
{
    // Stores the frequency
    // of array elements
    unordered_map freq;
 
    // Stores the count of
    // resultant triplets
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < arr.size(); i++) {
 
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.find(arr[i] - D)
                != freq.end()
            && freq.find(arr[i] - 2 * D)
                   != freq.end()) {
 
            // Update the value of ans
            ans += freq[arr[i] - D]
                   * freq[arr[i] - 2 * D];
        }
 
        // Increase the frequency
        // of the current element
        freq[arr[i]]++;
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
int main()
{
    vector arr{ 1, 2, 4, 5, 7, 8, 10 };
    int D = 1;
    cout << countTriplets(D, arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
static int countTriplets(int D, int []arr)
{
     
    // Stores the frequency
    // of array elements
    HashMap freq = new HashMap();
 
    // Stores the count of
    // resultant triplets
    int ans = 0;
 
    // Traverse the array
    for(int i = 0; i < arr.length; i++)
    {
         
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.containsKey(arr[i] - D) &&
            freq.containsKey(arr[i] - 2 * D))
        {
             
            // Update the value of ans
            ans += freq.get(arr[i] - D) *
                   freq.get(arr[i] - 2 * D);
        }
 
        // Increase the frequency
        // of the current element
        if (freq.containsKey(arr[i]))
        {
            freq.put(arr[i], freq.get(arr[i]) + 1);
        }
        else
        {
            freq.put(arr[i], 1);
        }
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int []arr = { 1, 2, 4, 5, 7, 8, 10 };
    int D = 1;
     
    System.out.print(countTriplets(D, arr));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to count the number of
# triplets having difference
# between adjacent  elements equal to D
def countTriplets(D, arr):
     
    # Stores the frequency
    # of array elements
    freq = {}
 
    # Stores the count of
    # resultant triplets
    ans = 0
  
    # Traverse the array
    for i in range(len(arr)):
         
        # Check if arr[i] - D and
        # arr[i] - 2 * D  exists
        # in the Hashmap or not
        if (((arr[i] - D) in freq) and
             (arr[i] - 2 * D) in freq):
                  
            # Update the value of ans
            ans += (freq[arr[i] - D] *
                    freq[arr[i] - 2 * D])
 
        # Increase the frequency
        # of the current element
        freq[arr[i]] = freq.get(arr[i], 0) + 1
 
    # Return the resultant count
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 4, 5, 7, 8, 10 ]
    D = 1
     
    print (countTriplets(D, arr))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
static int countTriplets(int D, int[] arr)
{
     
    // Stores the frequency
    // of array elements
    Dictionary freq = new Dictionary();
 
    // Stores the count of
    // resultant triplets
    int ans = 0;
 
    // Traverse the array
    for(int i = 0; i < arr.Length; i++)
    {
         
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.ContainsKey(arr[i] - D) &&
            freq.ContainsKey(arr[i] - 2 * D))
        {
             
            // Update the value of ans
            ans += freq[arr[i] - D] *
                   freq[arr[i] - 2 * D];
        }
 
        // Increase the frequency
        // of the current element
        if (!freq.ContainsKey(arr[i]))
            freq[arr[i]] = 0;
             
        freq[arr[i]]++;
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 4, 5, 7, 8, 10 };
    int D = 1;
     
    Console.WriteLine(countTriplets(D, arr));
}
}
 
// This code is contributed by ukasp


Javascript


输出:
0

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

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