Encuentre duplicados en una array dada cuando los elementos no están limitados a un rango

Dada una array de n enteros. La tarea es imprimir los duplicados en la array dada. Si no hay duplicados, imprima -1. 

Ejemplos: 

Input: {2, 10,10, 100, 2, 10, 11,2,11,2}
Output: 2 10 11

Input: {5, 40, 1, 40, 100000, 1, 5, 1}
Output: 5 40 1

Nota: Los elementos duplicados se pueden imprimir en cualquier orden.

Enfoque simple : la idea es usar un bucle anidado y, para cada elemento, verificar si el elemento está presente en la array más de una vez o no. Si está presente, guárdelo en un Hash-map. De lo contrario, continúe revisando otros elementos.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ implementation of the
// above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the Duplicates,
// if duplicate occurs 2 times or
// more than 2 times in array so,
// it will print duplicate value
// only once at output
void findDuplicates(int arr[], int len)
{
     
    // Initialize ifPresent as false
    bool ifPresent = false;
 
    // ArrayList to store the output
    vector<int> al;
 
    for(int i = 0; i < len - 1; i++)
    {
        for(int j = i + 1; j < len; j++)
        {
            if (arr[i] == arr[j])
            {
                 
                // Checking if element is
                // present in the ArrayList
                // or not if present then break
                auto it = std::find(al.begin(),
                                    al.end(), arr[i]);
                                     
                if (it != al.end())
                {
                    break;
                }
 
                // If element is not present in the
                // ArrayList then add it to ArrayList
                // and make ifPresent at true
                else
                {
                    al.push_back(arr[i]);
                    ifPresent = true;
                }
            }
        }
    }
 
    // If duplicates is present
    // then print ArrayList
    if (ifPresent == true)
    {
        cout << "[" << al[0] << ", ";
        for(int i = 1; i < al.size() - 1; i++)
        {
            cout << al[i] << ", ";
        }
         
        cout << al[al.size() - 1] << "]";
    }
    else
    {
        cout << "No duplicates present in arrays";
    }
}
 
// Driver code
int main()
{
    int arr[] = { 12, 11, 40, 12,
                  5, 6, 5, 12, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findDuplicates(arr, n);
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07

Java

// Java implementation of the
// above approach
 
import java.util.ArrayList;
 
public class GFG {
 
    // Function to find the Duplicates,
    // if duplicate occurs 2 times or
    // more than 2 times in
    // array so, it will print duplicate
    // value only once at output
    static void findDuplicates(
      int arr[], int len)
    {
 
        // initialize ifPresent as false
        boolean ifPresent = false;
 
        // ArrayList to store the output
        ArrayList<Integer> al = new ArrayList<Integer>();
 
        for (int i = 0; i < len - 1; i++) {
            for (int j = i + 1; j < len; j++) {
                if (arr[i] == arr[j]) {
                    // checking if element is
                    // present in the ArrayList
                    // or not if present then break
                    if (al.contains(arr[i])) {
                        break;
                    }
 
                    // if element is not present in the
                    // ArrayList then add it to ArrayList
                    // and make ifPresent at true
                    else {
                        al.add(arr[i]);
                        ifPresent = true;
                    }
                }
            }
        }
 
        // if duplicates is present
        // then print ArrayList
        if (ifPresent == true) {
 
            System.out.print(al + " ");
        }
        else {
            System.out.print(
                "No duplicates present in arrays");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int arr[] = { 12, 11, 40, 12, 5, 6, 5, 12, 11 };
        int n = arr.length;
 
        findDuplicates(arr, n);
    }
}

Python3

# Python3 implementation of the
# above approach
 
# Function to find the Duplicates,
# if duplicate occurs 2 times or
# more than 2 times in array so,
# it will print duplicate value
# only once at output
def findDuplicates(arr, Len):
     
    # Initialize ifPresent as false
    ifPresent = False
 
    # ArrayList to store the output
    a1 = []
    for i in range(Len - 1):
        for j in range(i + 1, Len):
 
            # Checking if element is
            # present in the ArrayList
            # or not if present then break
            if (arr[i] == arr[j]):
                if arr[i] in a1:
                    break
                 
                # If element is not present in the
                # ArrayList then add it to ArrayList
                # and make ifPresent at true
                else:
                    a1.append(arr[i])
                    ifPresent = True
 
    # If duplicates is present
    # then print ArrayList
    if (ifPresent):
        print(a1, end = " ")
    else:
        print("No duplicates present in arrays")
 
# Driver Code
arr = [ 12, 11, 40, 12, 5, 6, 5, 12, 11 ]
n = len(arr)
 
findDuplicates(arr, n)
 
# This code is contributed by rag2127

C#

// C# implementation of the
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the Duplicates,
// if duplicate occurs 2 times or
// more than 2 times in array so,
// it will print duplicate value
// only once at output
static void findDuplicates(int[] arr, int len)
{
     
    // Initialize ifPresent as false
    bool ifPresent = false;
 
    // ArrayList to store the output
    List<int> al = new List<int>();
 
    for(int i = 0; i < len - 1; i++)
    {
        for(int j = i + 1; j < len; j++)
        {
            if (arr[i] == arr[j])
            {
                 
                // Checking if element is
                // present in the ArrayList
                // or not if present then break
                if (al.Contains(arr[i]))
                {
                    break;
                }
 
                // If element is not present in the
                // ArrayList then add it to ArrayList
                // and make ifPresent at true
                else
                {
                    al.Add(arr[i]);
                    ifPresent = true;
                }
            }
        }
    }
 
    // If duplicates is present
    // then print ArrayList
    if (ifPresent == true)
    {
        Console.Write("[" + al[0] + ", ");
        for(int i = 1; i < al.Count - 1; i++)
        {
            Console.Write(al[i] + ", ");
        }
        Console.Write(al[al.Count - 1] + "]");
    }
    else
    {
        Console.Write("No duplicates present in arrays");
    }
}
 
// Driver code   
static void Main()
{
    int[] arr = { 12, 11, 40, 12,
                  5, 6, 5, 12, 11 };
    int n = arr.Length;
 
    findDuplicates(arr, n);
}
}
 
// This code is contributed by divyesh072019

Javascript

<script>
 
// JavaScript implementation of the
// above approach
 
// Function to find the Duplicates,
// if duplicate occurs 2 times or
// more than 2 times in
// array so, it will print duplicate
// value only once at output
function findDuplicates(arr, len) {
 
    // initialize ifPresent as false
    let ifPresent = false;
 
    // ArrayList to store the output
    let al = new Array();
 
    for (let i = 0; i < len - 1; i++) {
        for (let j = i + 1; j < len; j++) {
            if (arr[i] == arr[j]) {
                // checking if element is
                // present in the ArrayList
                // or not if present then break
                if (al.includes(arr[i])) {
                    break;
                }
 
                // if element is not present in the
                // ArrayList then add it to ArrayList
                // and make ifPresent at true
                else {
                    al.push(arr[i]);
                    ifPresent = true;
                }
            }
        }
    }
 
    // if duplicates is present
    // then print ArrayList
    if (ifPresent == true) {
 
        document.write(`[${al}]`);
    }
    else {
        document.write("No duplicates present in arrays");
    }
}
 
// Driver Code
 
let arr = [12, 11, 40, 12, 5, 6, 5, 12, 11];
let n = arr.length;
 
findDuplicates(arr, n);
 
</script>
Producción

[12, 11, 5]

Tiempo Complejidad: O(N 2
Espacio Auxiliar: O(N)

Enfoque eficiente : use unordered_map para hash. Cuente la frecuencia de aparición de cada elemento y se imprimen los elementos con una frecuencia superior a 1. se utiliza unordered_map ya que no se conoce el rango de enteros. Para Python, use el diccionario para almacenar el número como clave y su frecuencia como valor. Se puede usar el diccionario ya que no se conoce el rango de números enteros.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program to find
// duplicates in the given array
#include <bits/stdc++.h>
using namespace std;
 
// function to find and print duplicates
void printDuplicates(int arr[], int n)
{
    // unordered_map to store frequencies
    unordered_map<int, int> freq;
    for (int i=0; i<n; i++)
        freq[arr[i]]++;
 
    bool dup = false;
    unordered_map<int, int>:: iterator itr;
    for (itr=freq.begin(); itr!=freq.end(); itr++)
    {
        // if frequency is more than 1
        // print the element
        if (itr->second > 1)
        {
            cout << itr->first << " ";
            dup = true;
        }
    }
 
    // no duplicates present
    if (dup == false)
        cout << "-1";
}
 
// Driver program to test above
int main()
{
    int arr[] = {12, 11, 40, 12, 5, 6, 5, 12, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
    printDuplicates(arr, n);
    return 0;
}

Java

// Java program to find
// duplicates in the given array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
 
public class FindDuplicatedInArray
{
    // Driver program
    public static void main(String[] args)
    {
        int arr[] = {12, 11, 40, 12, 5, 6, 5, 12, 11};
        int n = arr.length;
        printDuplicates(arr, n);
    }
    // function to find and print duplicates
    private static void printDuplicates(int[] arr, int n)
    {
        Map<Integer,Integer> map = new HashMap<>();
        int count = 0;
        boolean dup = false;
        for(int i = 0; i < n; i++){
            if(map.containsKey(arr[i])){
                count = map.get(arr[i]);
                map.put(arr[i], count + 1);
            }
            else{
                map.put(arr[i], 1);
            }
        }
         
        for(Entry<Integer,Integer> entry : map.entrySet())
        {
            // if frequency is more than 1
            // print the element
            if(entry.getValue() > 1){
                System.out.print(entry.getKey()+ " ");
                dup = true;
            }
        }
        // no duplicates present
        if(!dup){
            System.out.println("-1");
        }
    }
}

Python3

# Python3 program to find duplicates
# using dictionary approach.
def printDuplicates(arr):
    dict = {}
 
    for ele in arr:
        try:
            dict[ele] += 1
        except:
            dict[ele] = 1
             
    for item in dict:
         
         # if frequency is more than 1
         # print the element
        if(dict[item] > 1):
            print(item, end=" ")
 
    print("\n")
 
# Driver Code
if __name__ == "__main__":
    list = [12, 11, 40, 12,
            5, 6, 5, 12, 11]
    printDuplicates(list)
 
# This code is contributed
# by Sushil Bhile

C#

// C# program to find
// duplicates in the given array
using System;
using System.Collections.Generic;
 
class GFG
{
    // function to find and print duplicates
    static void printDuplicates(int[] arr, int n)
    {
        Dictionary<int,
                   int> map = new Dictionary<int,
                                             int>();
        int count = 0;
        bool dup = false;
        for (int i = 0; i < n; i++)
        {
            if (map.ContainsKey(arr[i]))
            {
                count = map[arr[i]];
                map[arr[i]]++;
            }
            else
                map.Add(arr[i], 1);
        }
 
        foreach (KeyValuePair<int,
                              int> entry in map)
        {
            // if frequency is more than 1
            // print the element
            if (entry.Value > 1)
                Console.Write(entry.Key + " ");
            dup = true;
        }
 
        // no duplicates present
        if (!dup)
            Console.WriteLine("-1");
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 12, 11, 40, 12,
                     5, 6, 5, 12, 11 };
        int n = arr.Length;
        printDuplicates(arr, n);
    }
}
 
// This code is contributed by
// sanjeev2552

Javascript

<script>
 
// JavaScript program to find
// duplicates in the given array
 
// Function to find and print duplicates
function printDuplicates(arr, n)
{
     
    // unordered_map to store frequencies
    var freq = new Map();
    for(let i = 0; i < n; i++)
    {
        if (freq.has(arr[i]))
        {
            freq.set(arr[i], freq.get(arr[i]) + 1);
        }
        else
        {
            freq.set(arr[i], 1);
        }
    }
     
    var dup = false;
    for(let [key, value] of freq)
    {
         
        // If frequency is more than 1
        // print the element
        if (value > 1)
        {
            document.write(key + " ");
            dup = true;
        }
    }
     
    // No duplicates present
    if (dup == false)
        document.write("-1");
}
 
// Driver code
var arr = [ 12, 11, 40, 12,
            5, 6, 5, 12, 11 ];
var n = arr.length;
 
printDuplicates(arr, n);
 
// This code is contributed by lokeshpotta20
 
</script>
Producción

5 12 11

Complejidad temporal: O(N)
Espacio auxiliar: O(N)

Publicación relacionada: 
Imprima todos los elementos distintos de una array de enteros dada  
Encuentre duplicados en O (n) tiempo y O (1) espacio adicional | Establezca 1  
Duplicados en una array en O (n) y usando O (1) espacio adicional | Set-2  
Imprimir todos los duplicados en la string de entrada

Este artículo es una contribución de Ayush Jauhari . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *