📌  相关文章
📜  数组中具有相等元素的索引对的计数|套装2

📅  最后修改于: 2021-05-14 07:44:25             🧑  作者: Mango

给定N个元素的数组arr [] 。任务是计算索引(i,j)的总数,以使arr [i] = arr [j]i!= j

例子:

有关天真有效的方法,请参阅本文的上一篇文章。

更好的方法–使用两个指针:想法是对给定的数组和具有相同元素的索引差进行排序。步骤如下:

  1. 对给定的数组进行排序。
  2. 初始化两个指针分别为0和1。
  3. 现在直到right小于N ,执行以下操作:
    • 如果元素索引的左侧和右侧相同,则增加右侧指针,并将右侧指针和左侧指针添加到最终计数中。
    • 否则更新从左到右的值。
  4. 完成上述步骤后,打印计数值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function that counts the pair in
// the array arr[]
int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // Sort the array
    sort(arr, arr + n);
 
    // Initialize two pointers
    int left = 0, right = 1;
    while (right < n) {
 
        if (arr[left] == arr[right])
 
            // Add all valid pairs to answer
            ans += right - left;
        else
            left = right;
        right++;
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 2, 2, 3, 2, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << countPairs(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function that counts the pair in
// the array arr[]
static int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // Sort the array
    Arrays.sort(arr);
 
    // Initialize two pointers
    int left = 0, right = 1;
    while (right < n)
    {
        if (arr[left] == arr[right])
 
            // Add all valid pairs to answer
            ans += right - left;
        else
            left = right;
        right++;
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 2, 2, 3, 2, 3 };
 
    int N = arr.length;
 
    // Function call
    System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 program for the above approach
 
# Function that counts the pair in
# the array arr[]
def countPairs(arr, n):
 
    ans = 0
 
    # Sort the array
    arr.sort()
 
    # Initialize two pointers
    left = 0
    right = 1;
    while (right < n):
 
        if (arr[left] == arr[right]):
 
            # Add all valid pairs to answer
            ans += right - left;
        else:
            left = right;
        right += 1
    
    # Return the answer
    return ans
 
# Driver Code
if __name__ == "__main__":
   
    # Given array arr[]
    arr = [2, 2, 3, 2, 3]
 
    N = len(arr)
 
    # Function call
    print (countPairs(arr, N))
 
# This code is contributed by Chitranayal


C#
// C# program for the above approach
using System;
class GFG{
 
// Function that counts the pair in
// the array []arr
static int countPairs(int []arr, int n)
{
    int ans = 0;
 
    // Sort the array
    Array.Sort(arr);
 
    // Initialize two pointers
    int left = 0, right = 1;
    while (right < n)
    {
        if (arr[left] == arr[right])
 
            // Add all valid pairs to answer
            ans += right - left;
        else
            left = right;
        right++;
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given array []arr
    int []arr = { 2, 2, 3, 2, 3 };
 
    int N = arr.Length;
 
    // Function call
    Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by sapnasingh4991


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function that count the pairs having
// same elements in the array arr[]
int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // Hash map to keep track of
    // occurences of elements
    unordered_map count;
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Check if occurence of arr[i] > 0
        // add count[arr[i]] to answer
        if (count[arr[i]] != 0)
            ans += count[arr[i]];
 
        // Increase count of arr[i]
        count[arr[i]]++;
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 1, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << countPairs(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function that count the pairs having
// same elements in the array arr[]
static int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // Hash map to keep track of
    // occurences of elements
    HashMap count = new HashMap<>();
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++)
    {
 
        // Check if occurence of arr[i] > 0
        // add count[arr[i]] to answer
        if(count.containsKey(arr[i]))
        {
            ans += count.get(arr[i]);
            count.put(arr[i], count.get(arr[i]) + 1);
        }
        else
        {
            count.put(arr[i], 1);
        }
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 1, 2, 1, 1 };
    int N = arr.length;
 
    // Function call
    System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 program for the above approach
 
# Function that count the pairs having
# same elements in the array arr[]
def countPairs(arr, n) :
 
    ans = 0
 
    # Hash map to keep track of
    # occurences of elements
    count = {}
 
    # Traverse the array arr[]
    for i in range(n) :
 
        # Check if occurence of arr[i] > 0
        # add count[arr[i]] to answer
        if arr[i] in count :
            ans += count[arr[i]]
 
        # Increase count of arr[i]
        if arr[i] in count :
            count[arr[i]] += 1
        else :
            count[arr[i]] = 1
 
    # Return the result
    return ans
 
# Given array arr[]
arr = [ 1, 2, 1, 1 ]
N = len(arr)
 
# Function call
print(countPairs(arr, N))
 
# This code is contributed by divyesh072019


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function that count the pairs having
// same elements in the array []arr
static int countPairs(int []arr, int n)
{
    int ans = 0;
 
    // Hash map to keep track of
    // occurences of elements
    Dictionary count = new Dictionary();
 
    // Traverse the array []arr
    for (int i = 0; i < n; i++)
    {
 
        // Check if occurence of arr[i] > 0
        // add count[arr[i]] to answer
        if(count.ContainsKey(arr[i]))
        {
            ans += count[arr[i]];
            count[arr[i]] = count[arr[i]] + 1;
        }
        else
        {
            count.Add(arr[i], 1);
        }
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given array []arr
    int []arr = { 1, 2, 1, 1 };
    int N = arr.Length;
 
    // Function call
    Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by PrinciRaj1992


输出:
4

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

高效方法–使用单个遍历:想法是使用散列并更新频率大于1的每对的计数。以下是步骤:

  1. 创建一个unordered_map M来存储数组中每个元素的频率。
  2. 遍历给定的数组,并不断更新M中每个元素的频率。
  3. 在上述步骤中更新频率时,如果任何元素的频率大于0,则将该频率计数为最终计数。
  4. 完成上述步骤后,打印对数。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function that count the pairs having
// same elements in the array arr[]
int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // Hash map to keep track of
    // occurences of elements
    unordered_map count;
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Check if occurence of arr[i] > 0
        // add count[arr[i]] to answer
        if (count[arr[i]] != 0)
            ans += count[arr[i]];
 
        // Increase count of arr[i]
        count[arr[i]]++;
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 1, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << countPairs(arr, N);
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
// Function that count the pairs having
// same elements in the array arr[]
static int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // Hash map to keep track of
    // occurences of elements
    HashMap count = new HashMap<>();
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++)
    {
 
        // Check if occurence of arr[i] > 0
        // add count[arr[i]] to answer
        if(count.containsKey(arr[i]))
        {
            ans += count.get(arr[i]);
            count.put(arr[i], count.get(arr[i]) + 1);
        }
        else
        {
            count.put(arr[i], 1);
        }
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 1, 2, 1, 1 };
    int N = arr.length;
 
    // Function call
    System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by PrinciRaj1992

Python3

# Python3 program for the above approach
 
# Function that count the pairs having
# same elements in the array arr[]
def countPairs(arr, n) :
 
    ans = 0
 
    # Hash map to keep track of
    # occurences of elements
    count = {}
 
    # Traverse the array arr[]
    for i in range(n) :
 
        # Check if occurence of arr[i] > 0
        # add count[arr[i]] to answer
        if arr[i] in count :
            ans += count[arr[i]]
 
        # Increase count of arr[i]
        if arr[i] in count :
            count[arr[i]] += 1
        else :
            count[arr[i]] = 1
 
    # Return the result
    return ans
 
# Given array arr[]
arr = [ 1, 2, 1, 1 ]
N = len(arr)
 
# Function call
print(countPairs(arr, N))
 
# This code is contributed by divyesh072019

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function that count the pairs having
// same elements in the array []arr
static int countPairs(int []arr, int n)
{
    int ans = 0;
 
    // Hash map to keep track of
    // occurences of elements
    Dictionary count = new Dictionary();
 
    // Traverse the array []arr
    for (int i = 0; i < n; i++)
    {
 
        // Check if occurence of arr[i] > 0
        // add count[arr[i]] to answer
        if(count.ContainsKey(arr[i]))
        {
            ans += count[arr[i]];
            count[arr[i]] = count[arr[i]] + 1;
        }
        else
        {
            count.Add(arr[i], 1);
        }
    }
 
    // Return the result
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given array []arr
    int []arr = { 1, 2, 1, 1 };
    int N = arr.Length;
 
    // Function call
    Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by PrinciRaj1992
输出:
3

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