已排序数组的绝对不同计数?
在本部分中,我们将了解如何计算绝对值不同的元素有多少个?假设数组中有几个元素,如 {5, 5, 6, -5, 8, 2, -2, 1},所以有 8 个元素。但有 5 个不同的元素 {5, 6, 8, 2, 1}。-5 和 5 不被视为不同的,因为它们的绝对值相同。
为了解决这个问题,我们将使用 Set 数据结构。在 set 中不允许有重复的元素。当我们向 set 中插入项时,我们将仅推送绝对值。
算法
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
示例
#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);
}输出
Absolute Distinct Count: 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP