检查给定数组中是否存在 C++ 中彼此 k 距离内的重复元素


我们将学习如何检查未排序数组中是否存在彼此 k 距离内的重复元素。假设元素列表为 {1, 2, 3, 1, 4, 5},如果 k = 3,则程序将返回 true,因为两个 1 之间的距离为 3。

我们将使用哈希表来解决这个问题。步骤如下:

  • 创建一个空的哈希表
  • 对于每个索引 i,令列表中的元素 e = arr[i],执行以下操作:
    • 如果 e 存在于哈希表中,则返回 true
    • 否则,将 e 添加到哈希表中,并在 i >= K 时,如果存在,则从哈希表中删除第 (i-k) 个元素。

示例

 在线演示

#include<iostream>
#include<set>
using namespace std;
bool hasDuplicateWithDistK(int arr[], int n, int k) {
   set<int> element_set;
   for (int i = 0; i < n; i++) {
      if (element_set.find(arr[i]) != element_set.end())
         return true;
      element_set.insert(arr[i]);
      if (i >= k)
         element_set.erase(arr[i-k]);
   }
   return false;
}
int main () {
   int arr[] = {10, 5, 3, 4, 3, 5, 6};
   int n = sizeof(arr) / sizeof(arr[0]);
   if (hasDuplicateWithDistK(arr, n, 3))
      cout << "Duplicate element has found";
   else
      cout << "Duplicate element has not found";
}

输出

Duplicate element has found

更新于:2019年10月22日

371 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.