排序数组中的绝对唯一计数?
在本节中,我们将看到如何计算绝对值不同的元素数量?假设数组中的元素很少,例如{5,5,6,-5,8,2,2,-2,1},因此有8个元素。但是有5个元素{5,6,8,2,1}是截然不同的。-5和5不会被视为不同,它们的绝对值相同是相同的。
为了解决这个问题,我们将使用Set数据结构。在设置中,不允许重复元素。当我们将item插入集合时,我们将仅推送绝对值。
算法
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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短