• leetcode 141 Linked List Cycle Hash fast and slow pointer


    Problem describe:https://leetcode.com/problems/linked-list-cycle/

    Given a linked list, determine if it has a cycle in it.
    
    To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
    
    Example 1:
    
    Input: head = [3,2,0,-4], pos = 1
    Output: true
    Explanation: There is a cycle in the linked list, where tail connects to the second node.
    
    
    Example 2:
    
    Input: head = [1,2], pos = 0
    Output: true
    Explanation: There is a cycle in the linked list, where tail connects to the first node.
    
    
    Example 3:
    
    Input: head = [1], pos = -1
    Output: false
    Explanation: There is no cycle in the linked list.
    
    Follow up:
    
    Can you solve it using O(1) (i.e. constant) memory?


    Ac Code: (Hash)

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     bool hasCycle(ListNode *head) {
    12         unordered_set<ListNode*> visit;
    13         while(head)
    14         {
    15             if(visit.count(head)!=0) return true;
    16             visit.insert(head);
    17             head = head->next;
    18         }
    19         return false;
    20     }
    21 };

     Fast and Slow Pointer

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     bool hasCycle(ListNode *head) {
    12         ListNode *slow = head;
    13         ListNode *fast = head;
    14         while(fast){
    15             if(!fast->next) return false;
    16             fast = fast->next->next;
    17             slow = slow->next;
    18             if(slow == fast) return true;
    19         }
    20         return false;
    21     }
    22 };
  • 相关阅读:
    爬虫相关知识(二 )xpath
    爬虫相关知识(一)
    html基础知识
    接口和异常
    继承与多态
    方法与方法重载,方法重写
    面向对象预习随笔
    《深入浅出MFC》第三章 MFC六大关键技术之仿真
    《深入浅出MFC》第二章 C++的重要性质
    《深入浅出MFC》第一章 Win32基本程序概念
  • 原文地址:https://www.cnblogs.com/CS-WLJ/p/11181770.html
Copyright © 2020-2023  润新知