zoukankan      html  css  js  c++  java
  • 141. Linked List Cycle

    原题链接:https://leetcode.com/problems/linked-list-cycle/description/
    直接上代码:

    import java.util.HashSet;
    
    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        static class ListNode {
            int val;
            ListNode next;
    
            ListNode(int x) {
                val = x;
                next = null;
            }
        }
    
        public static void main(String[] args) {
            Solution s = new Solution();
    
            ListNode node1 = new ListNode(1);
            node1.next = new ListNode(2);
            node1.next.next = node1;
            System.out.println(s.hasCycle(node1));
            System.out.println(s.hasCycle2(node1));
        }
    
        /**
         * 我的方法,题目中要求不能使用额外的空间,但是我用了,所以说并不完美
         *
         * @param head
         * @return
         */
        public boolean hasCycle(ListNode head) {
            if (head == null) {
                return false;
            }
    
            HashSet<ListNode> nodes = new HashSet<>();
            nodes.add(head);
            while (head.next != null) {
                head = head.next;
                if (nodes.contains(head)) {
                    return true;
                }
                nodes.add(head);
            }
    
            return false;
        }
    
        /**
         * 别人提交的答案,不得不说很牛逼啊
         *
         * @param head
         * @return
         */
        public boolean hasCycle2(ListNode head) {
            if (head == null || head.next == null) {
                return false;
            }
    
            ListNode p1 = head, p2 = head;
            while (p2 != null && p2.next != null) {
                p1 = p1.next;
                p2 = p2.next.next;
                if (p1 == p2) {
                    return true;
                }
            }
    
            return false;
        }
    
        // 官方答案:官方答案给了两种,尼玛,就是上面的这两种了!
    }
    
  • 相关阅读:
    第十二天
    php获取变量所占内存大小的方法
    php数组倒序
    最近学习时遇到的一些函数
    php curl发送留言实例
    php性能测试
    php敏感字过滤替换
    php常用函数
    必学PHP类库/常用PHP类库大全
    thinkphp html转为字符
  • 原文地址:https://www.cnblogs.com/optor/p/8592116.html
Copyright © 2011-2022 走看看