数组和链表中的环路问题

数组中的环路 

题目出处:https://leetcode-cn.com/problems/circular-array-loop/

思路:类似于链表中找是否存在环路,定义两个指针(一个快指针、一个慢指针),快指针初始时在慢指针的下一个位置。每次慢指针走一步、快指针走两步,两者相遇时则证明存在环。

题干中的限制条件

  1. 环的长度为1:在环的某一处结点判断(快慢指针相遇处为环的结点),如果此时慢指针的下一个位置还是它本身,则说明环的长度为1。
  2. 环中的每个元素的方向一致:判断快指针的每一个位置的方向是否与初始方向一致,且快指针下一个位置的方向也与初始位置的方向一致。
class Solution {
public:
    int next(vector<int>& nums, int now){  //下一步的位置
        int n = nums.size();
        int next_pos = ((now + nums[now]) % n +n) % n;
        return next_pos;
    }
    bool circularArrayLoop(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0; i < n; ++i){
            int slow = i;  int fast = next(nums, slow);  // 快指针多走一步
            while(nums[fast]*nums[slow] > 0 && nums[next(nums,fast)]*nums[slow] > 0){ //快指针判断方向是否一直   
                if(slow == fast){  //快慢指针相遇
                    if(slow == next(nums, slow)){  //环的长度为1,继续找环
                        break;
                    }
                    else{   //环的长度不为1,说明存在环,直接返回true
                        return true;
                    }
                }
                slow = next(nums, slow); //慢指针走一步
                fast = next(nums, next(nums,fast)); //快指针走两步
            }
        }

        return false;
    }
};

链表中的环路

题目出处:https://leetcode-cn.com/problems/linked-list-cycle/

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head || !head->next){
            return false; 
        }

        ListNode* slow = head;
        ListNode* fast = head->next;
        while(fast && fast->next){
            if(slow == fast){
                return true;
            }
            slow = slow->next;
            fast = fast->next->next;
        }

        return false;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值