📌  相关文章
📜  多次出现的数组元素

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

给定一个整数数组,打印数组中所有重复元素(出现多次的元素)。输出应包含根据它们第一次出现的元素。

例子:

Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}
Output: 10 45

Input: arr[] = {1, 2, 3, 4, 2, 5}
Output: 2

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1

这个想法是使用哈希在平均 O(n) 时间内解决这个问题。我们将元素及其计数存储在哈希表中。存储计数后,我们再次遍历输入数组并打印那些计数超过一次的元素。为了确保每个输出元素只打印一次,我们在打印元素后将计数设置为 0。

C++
// C++ program to print all repeating elements
#include 
using namespace std;
 
void printRepeating(int arr[], int n)
{
    // Store elements and their counts in
    // hash table
    unordered_map mp;
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Since we want elements in same order,
    // we traverse array again and print
    // those elements that appear more than
    // once.
    for (int i = 0; i < n; i++) {
        if (mp[arr[i]] > 1) {
            cout << arr[i] << " ";
 
            // This is tricky, this is done
            // to make sure that the current
            // element is not printed again
            mp[arr[i]] = 0;
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, n);
    return 0;
}


Java
// Java program to print all repeating elements
 
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.lang.*;
 
public class GFG {
 
    static void printRepeating(int arr[], int n)
    {
 
        // Store elements and their counts in
        // hash table
        Map map
            = new LinkedHashMap();
        for (int i = 0; i < n; i++) {
            try {
                map.put(arr[i], map.get(arr[i]) + 1);
            }
            catch (Exception e) {
                map.put(arr[i], 1);
            }
        }
 
        // Since we want elements in the same order,
        // we traverse array again and print
        // those elements that appear more than once.
 
        for (Entry e : map.entrySet()) {
            if (e.getValue() > 1) {
                System.out.print(e.getKey() + " ");
            }
        }
    }
 
    // Driver code
    public static void main(String[] args) throws IOException
    {
        int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
        int n = arr.length;
        printRepeating(arr, n);
    }
}
 
// This code is contributed by Wrick


Python3
# Python3 program to print
# all repeating elements
def printRepeating(arr, n):
 
    # Store elements and
    # their counts in
    # hash table
    mp = [0] * 100
    for i in range(0, n):
        mp[arr[i]] += 1
 
    # Since we want elements
    # in same order, we
    # traverse array again
    # and print those elements
    # that appear more than once.
    for i in range(0, n):
        if (mp[arr[i]] > 1):
            print(arr[i], end = " ")
             
            # This is tricky, this
            # is done to make sure
            # that the current element
            # is not printed again
            mp[arr[i]] = 0
     
# Driver code
arr = [12, 10, 9, 45,
       2, 10, 10, 45]
n = len(arr)
printRepeating(arr, n)
 
# This code is contributed
# by Smita


C#
// C# program to print all repeating elements
using System;
using System.Collections.Generic;
 
class GFG
{
static void printRepeating(int []arr, int n)
{
 
    // Store elements and their counts in
    // hash table
    Dictionary map = new Dictionary();
    for (int i = 0 ; i < n; i++)
    {
        if(map.ContainsKey(arr[i]))
        {
            var val = map[arr[i]];
            map.Remove(arr[i]);
            map.Add(arr[i], val + 1);
        }
        else
        {
            map.Add(arr[i], 1);
        }
    }
 
    // Since we want elements in the same order,
    // we traverse array again and print
    // those elements that appear more than once.
    foreach(KeyValuePair e in map)
    {
        if (e.Value > 1)
        {
            Console.Write(e.Key + " ");
        }
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 };
    int n = arr.Length;
    printRepeating(arr, n);
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


Python3
# Python3 program to print
# all repeating elements
from collections import Counter
 
def printRepeating(arr, n):
   
    # Counting frequencies
    freq = Counter(arr)
     
    # Traverse the freq dictionary and
    # print all the keys whose value
    # is greater than 1
    for i in freq:
        if(freq[i] > 1):
            print(i, end=" ")
 
 
# Driver code
arr = [12, 10, 9, 45,
       2, 10, 10, 45]
n = len(arr)
printRepeating(arr, n)
 
# This code is contributed by vikkycirus


输出:
10 45

时间复杂度: O(n) 假设哈希插入和搜索函数在 O(1) 时间内工作。

方法 #2:使用内置Python函数:

  • 使用Counter()函数计算所有元素的所有频率。
  • 在这个频率字典中遍历并打印所有值大于 1 的键。

下面是上述方法的实现:

蟒蛇3

# Python3 program to print
# all repeating elements
from collections import Counter
 
def printRepeating(arr, n):
   
    # Counting frequencies
    freq = Counter(arr)
     
    # Traverse the freq dictionary and
    # print all the keys whose value
    # is greater than 1
    for i in freq:
        if(freq[i] > 1):
            print(i, end=" ")
 
 
# Driver code
arr = [12, 10, 9, 45,
       2, 10, 10, 45]
n = len(arr)
printRepeating(arr, n)
 
# This code is contributed by vikkycirus

输出:

10 45

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