
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Absolute Distinct Count in a Sorted Array
In this section we will see how to count how many of elements whose absolute values are distinct? Suppose in an array there are few elements like {5, 5, 6, -5, 8, 2, -2, 1}, so there are 8 elements. But there are 5 elements {5, 6, 8, 2, 1} which are distinct. The -5 and 5 are not considered as different, they are same as their absolute value is same.
To solve this problem, we will use the Set data-structure. In set duplicate elements are not allowed. And when we are inserting item into the set, we will push only the absolute value.
Algorithm
absoluteDistinctCount(arr)
begin define set s; for each element e in arr, do insert |e| into s done return the number of elements of s end
Example
#include<iostream> #include<set> #include<cmath> using namespace std; int absoluteDistinctCount(int arr[], int n){ set<int> s; for(int i = 0; i<n; i++){ s.insert(abs(arr[i])); //insert the absolute value } return s.size(); } main() { int arr[] = {5, 5, 6, -5, 8, 2, -2, 1}; int n = (sizeof(arr))/(sizeof(arr[0])); cout << "Absolute Distinct Count: " << absoluteDistinctCount(arr, n); }
Output
Absolute Distinct Count: 5
Advertisements