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;
}
}