检查在C ++的链接列表中是否存在与给定产品的对

我们有一组元素。还有一个乘积K。任务是检查链表中是否存在两个数字,乘积与K相同。如果有两个数字,则打印它们;如果有两个以上的数字,则打印任何一个。假设链接列表是这样的{2,4,8,8,12,15},并且k值为16。则它将返回(2,8)

我们将使用哈希技术解决此问题。取一个哈希表,并将所有元素标记为0。现在,如果链表中存在哈希表,则将所有元素迭代标记为1。现在开始遍历链表,并检查给定产品是否可被当前元素整除。如果是,则检查哈希表中是否存在链接列表的(K /当前元素)。

示例

#include <unordered_set>
#define MAX 100000
using namespace std;
class Node {
   public:
   int data;
   Node* next;
};
void append(struct Node** start, int key) {
   Node* new_node = new Node;
   new_node->data = key;
   new_node->next = (*start);
   (*start) = new_node;
}
bool isPairPresent(Node* start, int K) {
   unordered_set<int> s;
   Node* p = start;
   while (p != NULL) {
      int current = p->data;
      if ((K % current == 0) && (s.find(K / current) != s.end())) {
         cout << current << " " << K / current;
         return true;
      }
      s.insert(p->data);
      p = p->next;
   }
   return false;
}
int main() {
   Node* start = NULL;
   int arr[] = {2, 4, 8, 12, 15};
   int n = sizeof(arr)/sizeof(arr[0]);
   for(int i = 0; i<n; i++){
      append(&start, arr[i]);
   }
   if (isPairPresent(start, 16) == false)
   cout << "NO PAIR EXIST";
}

输出结果

2 8