📌  相关文章
📜  查找数组中非重复(不同)元素的总和

📅  最后修改于: 2021-10-27 07:22:37             🧑  作者: Mango

给定一个具有重复元素的整数数组,任务是找到数组中所有不同元素的总和。
例子:

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

一个简单的解决方案是使用两个嵌套循环。外循环从最左边的元素开始一个一个地选取一个元素。内循环检查元素是否存在于它的左侧。如果存在,则忽略该元素。
时间复杂度: O(n 2 )
辅助空间: O(1)
这个问题的一个更好的解决方案是使用排序技术我们首先按升序对数组的所有元素进行排序,然后在数组中找到一个一个不同的元素。

C++
// C++ Find the sum of all non-repeated
// elements in an array
#include
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


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


C++
// C++ Find the sum of all non- repeated
// elements in an array
#include
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


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 s = new HashSet();
        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 s = new HashSet();
        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


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

时间复杂度: O(n log n)
空间复杂度: O(1)
这个问题的一个有效解决方案是使用 unordered_set 我们运行单个 for 循环,哪个值第一次出现在 sum 变量中并存储在哈希表中,下次我们不使用这个值。

C++

// C++ Find the sum of all non- repeated
// elements in an array
#include
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

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 s = new HashSet();
        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

蟒蛇3

# 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 s = new HashSet();
        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


输出:

21

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

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

方法:

  • 使用Counter()函数计算频率
  • 将频率键转换为列表。
  • 计算列表的总和。

下面是上述方法的实现

蟒蛇3

# 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

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