public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<Integer> nums = new HashSet<Integer>();
ListNode count = headA;
int lengthA = 0;
int lengthB = 0;
int lastA = 0;
int lastB = 0;
while (count.next != null) {
lengthA++;
lastA = count.val;
}
count = headB;
while (count.next != null) {
lengthB++;
lastB = count.val;
}
if (lastA != lastB) {
return null;
}
ListNode potential = null;
int start = Math.abs(lengthA - lengthB);
ListNode sA = headA;
ListNode sB = headB;
for (int i = 0; i < start; i++) {
if (lengthA < lengthB) {
sB = sB.next;
} else {
sA = sA.next;
}
}
while (sA.next != null && sA.val != sB.val) {
if (sA.val == sB.val) {
potential = sA;
} else {
potential = null;
}
sA = sA.next;
sB = sB.next;
}
return potential;
}
}
Timeout 처음봤다....ㅎㅎ
Approach 2. Array 만들어서 값 다 넣고
마지막이 다르면 return null
마지막이 같으면 2배수로 해서 계속 같은 값 찾기
.next로 listNode return 하기
이렇게 하면 쉬울 것 같은데...
space complexity가 1인지 모르겠다
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode a = headA;
ListNode b = headB;
while( a != b){
a = a == null? headB : a.next;
b = b == null? headA : b.next;
}
return a;
}
Edge case: 하나만 같고 바로 손절하는... 그런 시나리오를 생각 안하나?
이것도 전씨와 함께 탐구해 나가고 싶네요^^
Runtime: 1 ms, faster than 97.59% of Java online submissions for Intersection of Two Linked Lists.
Memory Usage: 41.7 MB, less than 77.74% of Java online submissions for Intersection of Two Linked Lists.