leetcode(NOWCODER)---linked-list-cycle-ii,linked-list-cycle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccnuacmhdu/article/details/85233751

linked-list-cycle

时间限制:1秒 空间限制:32768K 热度指数:18672
本题知识点: 链表 leetcode
算法知识视频讲解
题目描述

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路(集合):
这需要额外空间!开辟一个HashSet。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    public boolean hasCycle(ListNode head) {
        //笔者愚钝,表示不能不开额外空间。。。
        if(head == null || head.next == null){
            return false;
        }
        HashSet<ListNode> set = new HashSet<ListNode>();
        while(head != null){
            boolean flag = set.add(head);
            if(flag == false){
                return true;
            }
            head = head.next;
        }
        return false;
    }
}

linked-list-cycle-ii

时间限制:1秒 空间限制:32768K 热度指数:24497
本题知识点: 链表 leetcode
算法知识视频讲解
题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

思路(集合):
这需要额外空间!开辟一个HashSet。不开新空间的答案

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    public ListNode detectCycle(ListNode head) {
        HashSet<ListNode> set = new HashSet<ListNode>();
        while(head != null){
            boolean flag = set.add(head);
            if(flag == false){
                return head;
            }
            head = head.next;
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/ccnuacmhdu/article/details/85233751