• 刷题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.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    android面试之怎么把图片变成圆形
    android面试之contentProvider获取联系人
    Android面试之assets和aw文件的使用
    Android设计模式之面试
    Activity、Window、View的关系
    ViewPager的简单用法
    补间动画
    帧动画
    android系统的样式和主题
    C++的三种继承方式简述
  • 原文地址:https://www.cnblogs.com/siweihz/p/12272892.html
Copyright © 2020-2023  润新知