- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find sum of non-repeating (distinct) elements in an arrays in C++
Consider we have an array A with few elements. We have to find sum of all distinct elements in the array. So if the A = [5, 12, 63, 5, 33, 47, 12, 63], then sum of distinct elements is 160. Duplicate elements are simply ignored once it has considered.
We can use the unordered set to solve this problem efficiently. We will run one single for loop and which value comes first time, its add in sum variable and store in hash table that for next time, we will not use this value.
Example
#include<iostream> #include<unordered_set> using namespace std; int getNonRepeatSum(int arr[],int n) { int sum = 0; unordered_set< int > u_set; for (int i=0; i<n; i++) { if (u_set.find(arr[i]) == u_set.end()) { sum += arr[i]; u_set.insert(arr[i]); } } return sum; } int main() { int arr[] = {5, 12, 63, 5, 33, 47, 12, 63}; int n = sizeof(arr)/sizeof(int); cout << "Sum is: " << getNonRepeatSum(arr, n); }
Output
Sum is: 160
Advertisements
To Continue Learning Please Login
Login with Google