技术共享

[leetcode]circular-array-loop 环形数组是否存在循环

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

. - 力扣(LeetCode)

  1. class Solution {
  2. public:
  3. bool circularArrayLoop(vector<int>& nums) {
  4. int n = nums.size();
  5. auto next = [&](int cur) {
  6. return ((cur + nums[cur]) % n + n) % n; // 保证返回值在 [0,n) 中
  7. };
  8. for (int i = 0; i < n; i++) {
  9. if (!nums[i]) {
  10. continue;
  11. }
  12. int slow = i, fast = next(i);
  13. // 判断非零且方向相同
  14. while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(fast)] > 0) {
  15. if (slow == fast) {
  16. if (slow != next(slow)) {
  17. return true;
  18. } else {
  19. break;
  20. }
  21. }
  22. slow = next(slow);
  23. fast = next(next(fast));
  24. }
  25. int add = i;
  26. while (nums[add] * nums[next(add)] > 0) {
  27. int tmp = add;
  28. add = next(add);
  29. nums[tmp] = 0;
  30. }
  31. }
  32. return false;
  33. }
  34. };