Leetcode # 141: ring list [Easy]

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_42191317/article/details/102760230

Title Description

Given a list, the list is determined whether a ring.

To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.

Examples of topics

Example 1:

Input: head = [3,2,0, -4], = POS. 1
 Output: to true
 explanation: the list has a ring tail portion connected to a second node.

Example 2:

Input: head = [1,2], POS = 0
 Output: to true
 explanation: the list has a ring, which is connected to the tail of the first node.

Example 3:

Input: head = [. 1], POS = -1
 Output: to false
 interpretation: the list does not ring.

Problem-solving ideas

1> iterative solution

Conventional thinking, to determine whether the list loop has been traversed to, if there has been next pointer ring there, or else acyclic, the code is difficult to achieve

2> hash table Solution

Traversing the list, the elements are still encountered into the hash table, first determine whether or not there before traversing the hash table (i.e., if placed before), if its size is repeated elements, cyclic, or acyclic.

Time complexity of O (n), the spatial complexity of O (n)

3> speed pointer

The list of conventional thinking to solve problems, set the speed of two pointers, each pointer fast take two steps slow pointer go one step further, if no ring, then quickly went to the end of the pointer at the end, if there is a ring, the faster the pointer must be entered in the rings encounter with slow pointer.

The time complexity of O (logn), the spatial complexity is O (1)

Code

Pointer speed

public class HasCycle {

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }

    public boolean hasCycle(ListNode head) {
        //非空检验
        if(head == null || head.next == null){
            return false;
        }
        //快慢指针
        ListNode fast = head.next;
        ListNode slow = head;
        boolean flag = false;
        while(fast != null){
            if(fast == slow){
                flag = true;
                break;
            }
            //防止空指针
            if(fast.next == null){
                break;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return flag;
    }


}

 

Guess you like

Origin blog.csdn.net/qq_42191317/article/details/102760230