[英]Can't pass all test cases for LeetCode question to find intersection of two linked lists using Hash map
我通過了初始測試用例,但它顯示了一個測試用例的錯誤答案。(測試用例中給出的鏈接列表:[0,9,1,2,4] 和 [3,2,4]。預期的答案是節點值為 2,但我得到 4。)任何人都可以發現代碼中的錯誤嗎?
歡迎使用其他方法來解決這個問題,但我想用哈希映射來做我自己的練習。
class Solution{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_map<int, ListNode*> map;
int i=0;
while(headA!=NULL){ //inserting all nodes of LL A in hash map
map[i]=headA;
headA=headA->next;
i++;
}
while(1){
for (auto it = map.begin(); it != map.end(); it++) {
if (it->second == headB){
return it->second;
}
else{
if(headB->next!=NULL) {
headB=headB->next;
}
else{
break;
}
}
}
}
return NULL;
}
};
我想先說unordered_map
不保證存儲順序。 這意味着項目不一定按照插入的順序存儲。
我們來看一下相關的代碼。
while(1){
for (auto it = map.begin(); it != map.end(); it++) {
if (it->second == headB){
return it->second;
}
else{
if(headB->next!=NULL) {
headB=headB->next;
}
else{
break;
}
}
}
迭代器將以您基本上無法預測的順序遍歷地圖的存儲順序。 粗略瀏覽一下您的代碼,我可以看到您的程序將在以下兩種情況之一中返回:
headB
值headB
值。headB
在沒有找到匹配的情況下到達它的最后一個值, while(1)
將重新啟動內部 for 循環並將迭代器指向的第一個值與headB
鏈表中的最后一個值進行headB
。 如果比較成功,則程序將返回。 否則,循環將永遠持續下去。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.