Dada una array de enteros con elementos repetidos, la tarea es encontrar la suma de todos los elementos distintos en la array.
Ejemplos:
Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10}; Output : 78 Here we take 12, 10, 9, 45, 2 for sum because it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}; Output : 71
Una solución simple es usar dos bucles anidados. El bucle exterior elige un elemento uno por uno comenzando desde el elemento más a la izquierda. El bucle interno verifica si el elemento está presente en el lado izquierdo. Si está presente, ignora el elemento.
Complejidad de Tiempo : O(n 2 )
Espacio Auxiliar : O(1)
Una mejor solución a este problema es que, al usar la técnica de clasificación, primero clasificamos todos los elementos de la array en orden ascendente y encontramos elementos distintos uno por uno en la array.
Implementación:
C++
// C++ Find the sum of all non-repeated // elements in an array #include<bits/stdc++.h> using namespace std; // Find the sum of all non-repeated elements // in an array int findSum(int arr[], int n) { // sort all elements of array sort(arr, arr + n); int sum = 0; for (int i=0; i<n; i++) { if (arr[i] != arr[i+1]) sum = sum + arr[i]; } return sum; } // Driver code int main() { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = sizeof(arr)/sizeof(int); cout << findSum(arr, n); return 0; }
Java
import java.util.Arrays; // Java Find the sum of all non-repeated // elements in an array public class GFG { // Find the sum of all non-repeated elements // in an array static int findSum(int arr[], int n) { // sort all elements of array Arrays.sort(arr); int sum = arr[0]; for (int i = 0; i < n-1; i++) { if (arr[i] != arr[i + 1]) { sum = sum + arr[i+1]; } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.length; System.out.println(findSum(arr, n)); } }
Python3
# Python3 Find the sum of all non-repeated # elements in an array # Find the sum of all non-repeated elements # in an array def findSum(arr, n): # sort all elements of array arr.sort() sum = arr[0] for i in range(0,n-1): if (arr[i] != arr[i+1]): sum = sum + arr[i+1] return sum # Driver code def main(): arr= [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(findSum(arr, n)) if __name__ == '__main__': main() # This code is contributed by 29AjayKumar
C#
// C# Find the sum of all non-repeated // elements in an array using System; class GFG { // Find the sum of all non-repeated elements // in an array static int findSum(int []arr, int n) { // sort all elements of array Array.Sort(arr); int sum = arr[0]; for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) { sum = sum + arr[i + 1]; } } return sum; } // Driver code public static void Main() { int []arr = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.Length; Console.WriteLine(findSum(arr, n)); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript Program to find the sum of all non-repeated // elements in an array // Find the sum of all non-repeated elements // in an array function findSum(arr, n) { // sort all elements of array arr.sort(); let sum = 0; for (let i=0; i<n; i++) { if (arr[i] != arr[i+1]) sum = sum + arr[i]; } return sum; } // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by Surbhi Tyagi </script>
21
Complejidad de tiempo: O(n log n)
Espacio auxiliar: O(1)
Una solución eficiente de este problema es que usando unordered_set ejecutamos un solo bucle for y qué valor viene la primera vez que se agrega en la variable de suma y se almacena en la tabla hash para que la próxima vez no usemos este valor.
Implementación:
C++
// C++ Find the sum of all non- repeated // elements in an array #include<bits/stdc++.h> using namespace std; // Find the sum of all non-repeated elements // in an array int findSum(int arr[],int n) { int sum = 0; // Hash to store all element of array unordered_set< int > s; for (int i=0; i<n; i++) { if (s.find(arr[i]) == s.end()) { sum += arr[i]; s.insert(arr[i]); } } return sum; } // Driver code int main() { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = sizeof(arr)/sizeof(int); cout << findSum(arr, n); return 0; }
Java
// Java Find the sum of all non- repeated // elements in an array import java.util.*; class GFG { // Find the sum of all non-repeated elements // in an array static int findSum(int arr[], int n) { int sum = 0; // Hash to store all element of array HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { if (!s.contains(arr[i])) { sum += arr[i]; s.add(arr[i]); } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.length; System.out.println(findSum(arr, n)); } } // This code is contributed by Rajput-Ji
Python3
# Python3 Find the sum of all # non- repeated elements in an array # Find the sum of all non-repeated # elements in an array def findSum(arr, n): s = set() sum = 0 # Hash to store all element # of array for i in range(n): if arr[i] not in s: s.add(arr[i]) for i in s: sum = sum + i return sum # Driver code arr = [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(findSum(arr, n)) # This code is contributed by Shrikant13
C#
// C# Find the sum of all non- repeated // elements in an array using System; using System.Collections.Generic; class GFG { // Find the sum of all non-repeated elements // in an array static int findSum(int []arr, int n) { int sum = 0; // Hash to store all element of array HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { if (!s.Contains(arr[i])) { sum += arr[i]; s.Add(arr[i]); } } return sum; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3, 1, 1, 4, 5, 6}; int n = arr.Length; Console.WriteLine(findSum(arr, n)); } } // This code is contributed by Rajput-Ji
Javascript
<script> // Javascript program Find the sum of all non- repeated // elements in an array // Find the sum of all non-repeated elements // in an array function findSum(arr, n) { let sum = 0; // Hash to store all element of array let s = new Set(); for (let i = 0; i < n; i++) { if (!s.has(arr[i])) { sum += arr[i]; s.add(arr[i]); } } return sum; } // Driver code let arr = [1, 2, 3, 1, 1, 4, 5, 6]; let n = arr.length; document.write(findSum(arr, n)); </script>
21
Complejidad temporal: O(n)
Espacio auxiliar: O(n)
Método n.º 3: uso de las funciones integradas de python:
Acercarse:
- Calcule las frecuencias usando la función Counter()
- Convierte las claves de frecuencia a la lista.
- Calcular la suma de la lista.
A continuación se muestra la implementación del enfoque anterior.
Python3
# Python program for the above approach from collections import Counter # Function to return the sum of distinct elements def sumOfElements(arr, n): # Counter function is used to # calculate frequency of elements of array freq = Counter(arr) # Converting keys of freq dictionary to list lis = list(freq.keys()) # Return sum of list return sum(lis) # Driver code if __name__ == "__main__": arr = [1, 2, 3, 1, 1, 4, 5, 6] n = len(arr) print(sumOfElements(arr, n)) # This code is contributed by vikkycirus
21
Complejidad temporal: O(n)
Espacio auxiliar: O(n)
Este artículo es una contribución de DANISH_RAZA . 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