Leetcode 457.环形数组循环

环形数组循环

给定一组含有正整数和负整数的数组。如果某个索引中的 n 是正数的,则向前移动 n 个索引。相反,如果是负数(-n),则向后移动 n 个索引。

假设数组首尾相接。判断数组中是否有环。环中至少包含 2 个元素。环中的元素一律"向前"或者一律"向后"。

示例 1:给定数组 [2, -1, 1, 2, 2], 有一个循环,从索引 0 -> 2 -> 3 -> 0。

示例 2:给定数组[-1, 2], 没有循环。

注意:给定数组保证不包含元素"0"。

你能写出时间复杂度为 O(n) 且空间复杂度为 O(1) 的算法吗?

思路

就是一个循环的判断,这道题可以使用双指针来判断,要注意的是双指针的移动要注意保持方向一致

所以在while的地方我们要求当前的和fast和fast的方向是一致的

 1 class Solution {
 2     public static boolean circularArrayLoop(int[] nums) {
 3         boolean retBoolean = false;
 4         for (int i = 0; i < nums.length; i++) {
 5             int j = i, k = getNextIndex(nums, i);
 6             while (nums[i] * nums[j] > 0 && nums[i] * nums[k] > 0 && nums[i] * nums[getNextIndex(nums, k)] > 0) {
 7                 if (j == k) {
 8                     if (j == getNextIndex(nums, j)) {
 9                         break;
10                     }
11                     return true;
12                 }
13                 j = getNextIndex(nums, j);
14                 k = getNextIndex(nums, getNextIndex(nums, k));
15             }
16         }
17         return retBoolean;
18     }
19 
20     private static int getNextIndex(int[] nums, int i) {
21         int length = nums.length;
22         int nextPosition = i + nums[i];
23         return nextPosition >= 0 ? nextPosition % length : length + (nextPosition % length);
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10273252.html