Solution.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package _457;
  2. class Solution {
  3. public boolean circularArrayLoop(int[] nums) {
  4. int n = nums.length;
  5. // Start from every element
  6. for (int i = 0; i < n; i++) {
  7. // Mark all visited points as 0 (after loop no found),
  8. // continue to next loop if curr loop starts with 0
  9. if (nums[i] == 0) {
  10. continue;
  11. }
  12. int slow = i;
  13. int fast = nextIndex(i, nums);
  14. int fastNext = nextIndex(fast, nums); // The next element of fast
  15. // Break if the direction of fast and fastNext do change
  16. // or if the fast or fastNext reach 0
  17. while (nums[fast] * nums[i] > 0 && nums[fastNext] * nums[i] > 0) {
  18. slow = nextIndex(slow, nums);
  19. fast = nextIndex(fastNext, nums);
  20. fastNext = nextIndex(fast, nums);
  21. // If fast catch up slow
  22. if (slow == fast) {
  23. // Single element in loop
  24. if (fast == fastNext) {
  25. break;
  26. }
  27. return true;
  28. }
  29. }
  30. // Set the path to 0
  31. slow = i;
  32. while (nums[slow] * nums[i] > 0) {
  33. nums[slow] = 0;
  34. slow = nextIndex(slow, nums);
  35. }
  36. }
  37. return false;
  38. }
  39. public static void main(String[] args) {
  40. Solution s = new Solution();
  41. int[] n1 = { 2, -1, 1, 2, 2 };
  42. System.out.println(s.circularArrayLoop(n1));
  43. int[] n2 = { -1, 2 };
  44. System.out.println(s.circularArrayLoop(n2));
  45. int[] n3 = { -2, 1, -1, -2, -2 };
  46. System.out.println(s.circularArrayLoop(n3));
  47. }
  48. private int nextIndex(int i, int[] nums) {
  49. int n = nums.length;
  50. int index = i + nums[i];
  51. return index >= 0 ? index % n : n + (index % n);
  52. }
  53. }