#if __GNUC__>2 #include <ext/hash_set> #include <ext/hash_map> using namespace __gnu_cxx; #else #include <hash_set> #include <hash_map> using namespace stdext; #endif #include <iostream> bool findDuplicatesWithinKDistrance(const int *arr, int arrSize, int k) { hash_set<int> set; for (int i = 0; i<arrSize; i++) { if (set.find(arr[i]) != set.end()) return true; set.insert(arr[i]); //只比较当前元素与其前面的k个元素,更前面的则删除之,因为距离已经大于k了。 if (i >= k) set.erase(arr[i - k]); } return false; } int main() { const int arrSize = 7; const int k = 3; int arr[arrSize] = { 11, 55, 22, 44, 22, 55, 77 }; if (findDuplicatesWithinKDistrance(arr, arrSize, k)) std::cout << "exist duplicates" << std::endl; else std::cout << "not exist duplicates" << std::endl; return 1; }输出:
原文地址:http://blog.csdn.net/shltsh/article/details/46485609