zoukankan      html  css  js  c++  java
  • 刷题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.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    SQLiteDatabase 源码
    SQLiteOpenHelper 源码
    Java同步机制总结--synchronized
    [Swift A]
    [Swift A]-问号&感叹号
    [Swift A]
    [Swift A]
    android 屏幕适配
    2014年度加班时间
    nodejs初学-----helloworld
  • 原文地址:https://www.cnblogs.com/siweihz/p/12272892.html
Copyright © 2011-2022 走看看