141. Linked List Cycle

JJ·2020년 12월 6일
0

저번에 배웠던 circle detection 알고리즘을 써먹을때

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode f = head, b = head;
        while (f.next != null && b.next.next != null) {
            int v1 = f.next.val;
            int v2 = b.next.next.val;
            if (v1 == v2) {
                return true;
            }
            f = f.next;
            b = b.next.next;
        }
        return false; 
    }
}

한번 뵙고 싶은 알고리즘 썼는데 안풀린당...

그나저나 pass 못한 테스트 케이스 실환가요...^^
스크롤 꼬라지 봐라

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        ListNode f = head, b = head.next;
        while (f != b) {
            if (b == null || b.next == null) {
                return false; 
            }
            f = f.next;
            b = b.next.next;
        }
        return true; 
    }
}

그 알고리즘이 조금 틀린걸 깨닫고 바꿨읍니다.
head == null이면 false인게 더 포괄적임

f = head, h = head.next로 바꿈 (전에는 둘다 head)
이유) 둘이 같으면 냅다 true 던지잖어 바부야..

while문을 f.next == null || b.next.next == null로 잡았었는데 그러면 영원히 가는데 circle하는 것들을 잡을 수 없음 ==> f != b로 가는 것이 맞음

그렇게 하면 false 문이 b = null, b.next == null이 됨 ==> b로 하는게 f 보다 빠름

테스트 다 통과하면 true

Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.

Memory Usage: 39.1 MB, less than 48.11% of Java online submissions for Linked List Cycle.

0개의 댓글

관련 채용 정보