还未发布过话题
  • 面试官:要是不允许使用集合类来解题呢?

    那就用双指针,快的一次走两步,慢的一次走一步,总有一次会相遇

    public class Solution {
        public boolean hasCycle(ListNode head) {
            ListNode fast = head, slow = head;
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
                if (fast == slow)
                    return true;
            }
            return false;
        }
    }
    

    算是双指针比较经典的题

  • leetcode 原题,可以用集合来解决

    public class Solution {
        public boolean hasCycle(ListNode head) {
            ArrayList<ListNode> list = new ArrayList<>();
            for (int i = 0; head != null; head = head.next) {
                if (list.contains(head))
                    return true;
                else
                    list.add(head);
            }
            return false;
        }
    }