sleepyotter
LeetCode/160.Intersection of Two Linked Lists 본문
2개의 링크드 리스트가 합쳐지는 지점이 있는지 확인하라는 문제이다.
간단하게 set에다가 한 쪽의 주소들을 싹 다 집어넣고 다른 쪽을 순회하며 set에 있는지 확인하면 된다. unordered_set을 쓰면 더 빨라지긴 하는데 요새 키보드가 굉장히 무겁게 느껴져서 타이핑이 힘들어서 그냥 set 썼다.
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
set<ListNode*> set;
if(headA==nullptr || headB==nullptr)
return nullptr;
ListNode* cur = headA;
while(true)
{
set.insert(cur);
if(cur->next==nullptr)
break;
cur = cur->next;
}
cur = headB;
while(true)
{
auto it = set.find(cur);
if(it!=set.end())
return cur;
if(cur->next == nullptr)
break;
cur = cur->next;
}
return nullptr;
}
};
'프로그래밍 > 알고리즘+코딩테스트' 카테고리의 다른 글
LeetCode/67.AddBinary (0) | 2022.02.14 |
---|---|
LeetCode/169.Majority Element (0) | 2022.02.14 |
LeetCode/155.Min Stack (0) | 2022.02.14 |
LeetCode/141.Linked List Cycle (0) | 2022.02.14 |
[카카오]/추석 트래픽 (0) | 2022.02.07 |