计算给定链表中按位与大于按位异或的节点对
给定一个单链表,任务是计算位与比位异或更大的节点对。
例子:
Input: list: 1->4->2->6->3
Output: 2
Explanation: 1st List Node Pair: (4, 6 ), Bitwise AND = 4, Bitwise XOR = 2
2nd List Node Pair: (2, 3), Bitwise AND = 2, Bitwise XOR = 1
Input: list: 17->34->62->46->30->51
Output: 7
Explanation: Valid List Node Pairs are (17, 30 ), (34, 62), (34, 46), (34, 51), (62, 46), (62, 51), (46, 51).
朴素的方法:朴素的方法是迭代链表,并为每个节点找到所有其他可能的节点形成一对,使得按位与大于按位异或。
时间复杂度: O(N 2 )
辅助空间: O(1)
有效的方法:通过使用以下观察可以有效地解决问题:
If First Set bit (Most significant bit) of two number is at same position, then the Bitwise AND or that numbers is always greater than the XOR because the XOR of two 1 is 0 and AND of two 1s is 1.
For any other cases, XOR will be always greater than the AND
请按照以下步骤解决问题:
- 遍历链表并将每个 Node 值的MSB位置存储在一个数组中。
- 初始化一个变量ans以存储所有可能的对。
- 创建一个哈希映射来存储具有相同 MSB(最高有效位)值的节点的计数。
- 遍历包含 MSB 位置的数组,并在每次迭代中:
- 获取具有相同 MSB 位置的节点数。
- 将来自这些节点的可能对的计数添加到ans中。
- 返回答案变量。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Structure of node of singly linked list
struct Node {
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
// Inserting new node
// at the beginning of the linked list
void push(struct Node** head_ref,
int new_data)
{
// Create a new node with the given data.
struct Node* new_node
= new Node(new_data);
// Make the new node point to the head.
new_node->next = (*head_ref);
// Make the new node as the head node.
(*head_ref) = new_node;
}
// Function to find the
// count of all possible pairs
int PerfectPair(Node* head, int K)
{
int ans = 0, size = 0;
unordered_map mp;
vector firstSetBit;
// Iterate Linked List and store the
// firstSetBit position
// for each Node Data
while (head != NULL) {
firstSetBit.push_back(
log2(head->data));
size++;
head = head->next;
}
// Check all previous node
// which can make
// pair with current node
for (int i = 0; i < size; i++) {
ans += mp[firstSetBit[i]];
mp[firstSetBit[i]]++;
}
return ans;
}
// Driver code
int main()
{
int K = 4;
// Create an empty singly linked list
struct Node* head = NULL;
// Insert values in Linked List
push(&head, 51);
push(&head, 30);
push(&head, 46);
push(&head, 62);
push(&head, 34);
push(&head, 17);
// Call PerfectPair function
cout << PerfectPair(head, K);
return 0;
}
7
时间复杂度: O(N * log N)
辅助空间: O(N)