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

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

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

例子:

对于朴素和高效的方法,请参阅本文的前一篇文章。

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

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

下面是上述方法的实现:

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


Javascript


输出:
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

蟒蛇3

# 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

Javascript


输出:
3

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

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