LintCode:Circular Array Loop

本文介绍了一种用于检测循环数组中是否存在特定循环路径的算法。该算法通过遍历数组元素并跟踪路径来确定是否存在一个从某点开始且最终返回该点的循环路径。文章提供了两种实现方式,一种严格遵循题目要求,另一种则提供了一个更为灵活的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first element. Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be "forward" or "backward'.

样例
Example 1:
Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0.
Example 2:

Given the array [-1, 2], there is no loop.

题目意思是判断数组是否有循环,而且注意题目中最后加粗的那一句,其表示这个循环只能是一直向后走或者一直向前走的,我之前就没注意这条,导致测试通不过。其实这句话就表示,在这个循环路径上要么全是正数要么全是负数。

实现:

public class Solution {
    
    public boolean circularArrayLoop(int[] nums) {
        for(int i=0; i<nums.length; i++){
        	int k=i;
        	int j=(k+nums[k]+nums.length)%nums.length;
        	int flag=nums[k]/Math.abs(nums[k]);
        	while(nums[j]*flag>0 && k!=j){
        		if(j==i) {
        			return true;
        		}
        		k=j;
        		j=(k+nums[k]+nums.length)%nums.length;
        	}
        }
        return false;
    }
    
}

其实忽略题目最后一个条件也是可以做的,而且可以取巧,下面贴出循环可以向前走也可以向后走的代码:

public class CircularArrayLoop {//时间复杂度是O(n)
	public boolean circularArrayLoop(int[] nums) {
        if(nums==null || nums.length<2) return false;
        int len=nums.length;
        int i=0;
        int j=0;
        while(true){
        	if(nums[i]==0) return true;
        	j=i+nums[i];        	
        	if(j>=len) j=j%len;
        	if(j<0){
        		while(j<0) j+=len;
        	}
        	if(j==i) break;
        	nums[i]=0;
        	i=j;        	
        }        
        return false;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值