• 刷题141. Linked List Cycle


    一、题目说明

    题目141. Linked List Cycle,给一个链表,判断是否有环。难度是Easy!

    二、我的解答

    遍历链表,访问过的打上标记即可。

    class Solution{
    	public:
    		bool hasCycle(ListNode* head){
    			while(head!=NULL){
    				if(head->val == INT_MAX) {
    					return true;
    				}
    				head->val = INT_MAX;
    				head = head->next;
    			}
    			if(head==NULL)return false;
    			else return true;
    		}
    };
    
    Runtime: 4 ms, faster than 99.89% of C++ online submissions for Linked List Cycle.
    Memory Usage: 9.9 MB, less than 50.00% of C++ online submissions for Linked List Cycle.
    

    三、优化措施

    快慢指针法,这个不破坏原链表。

    class Solution{
    	public:
    		bool hasCycle(ListNode* head){
    			if(head==NULL || head->next==NULL){
    				return false;
    			}
    			ListNode* fast = head->next,*slow = head;
    			while(fast != slow){
    				if(fast==NULL || slow==NULL){
    					return false;
    				}
    				slow = slow->next;
    				fast= fast->next;
                    if(fast!=NULL) {
                        fast=fast->next;
                    }else{
                        return false;
                    }
    			}
    			return true;
    		}
    };
    
    Runtime: 12 ms, faster than 77.13% of C++ online submissions for Linked List Cycle.
    Memory Usage: 9.8 MB, less than 75.00% of C++ online submissions for Linked List Cycle.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    优化问题中什么形式有闭式解
    选择排序
    超算私房菜之集群搭建
    Scramble String
    Insert Interval
    Implement strStr()
    Permutation Sequence
    Insertion Sort List
    Restore IP Addresses
    Recover Binary Search Tree
  • 原文地址:https://www.cnblogs.com/siweihz/p/12272892.html
Copyright © 2020-2023  润新知