/* 在n个元素的数组中,找到差值为k的数字对去重后的个数 思路: 双重循环枚举对,然后把一对数放在set容器去重,最后输出set的大小 缺点: 当数据很大时,时间复杂度会很高 */ #include <iostream> #include <set> using namespace std; set <pair<int, int>> mypairs; int n, k,a[10000]; int main() { cin >> n >> k; for (int i = 0; i < n;i++) { cin >> a[i]; } for (int i = 0; i < n;i++) { for (int j = 0; j < n;j++) { if ((a[i]+k)==a[j]) { mypairs.insert(make_pair(a[i],a[j])); } } } cout << mypairs.size() << endl; return 0; } /* 优化: 光枚举a[i];减少for循环 */ #include <iostream> #include <set> using namespace std; int n, k, a[10000],ans=0; set <int> myset; int main() { cin >> n >> k; for (int i = 0; i < n;i++) { cin >> a[i]; myset.insert(a[i]); } for (int x : myset) { if (myset.find(x+k)!=myset.end()) { ans++; } } cout << ans << endl; return 0; }
在n个元素的数组中,找到差值为k的数字对去重后的个数
猜你喜欢
转载自blog.csdn.net/m0_37806112/article/details/80600921
今日推荐
周排行