当前位置: 首页 > article >正文

Java | Leetcode Java题解之第457题环形数组是否存在循环

题目:

题解:

class Solution {
    public boolean circularArrayLoop(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if (nums[i] == 0) {
                continue;
            }
            int slow = i, fast = next(nums, i);
            // 判断非零且方向相同
            while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(nums, fast)] > 0) {
                if (slow == fast) {
                    if (slow != next(nums, slow)) {
                        return true;
                    } else {
                        break;
                    }
                }
                slow = next(nums, slow);
                fast = next(nums, next(nums, fast));
            }
            int add = i;
            while (nums[add] * nums[next(nums, add)] > 0) {
                int tmp = add;
                add = next(nums, add);
                nums[tmp] = 0;
            }
        }
        return false;
    }

    public int next(int[] nums, int cur) {
        int n = nums.length;
        return ((cur + nums[cur]) % n + n) % n; // 保证返回值在 [0,n) 中
    }
}

http://www.kler.cn/news/335508.html

相关文章:

  • Golang | Leetcode Golang题解之第455题分发饼干
  • L1415 【哈工大_操作系统】CPU调度策略一个实际的schedule函数
  • [Offsec Lab] ICMP Monitorr-RCE+hping3权限提升
  • Kotlin真·全平台——Kotlin Compose Multiplatform Mobile(kotlin跨平台方案、KMP、KMM)
  • 4款专业电脑数据恢复软件,帮你保障数据安全。
  • CUDA与TensorRT学习四:模型部署基础知识、模型部署的几大误区、模型量化、模型剪枝、层融合
  • Oracle RAC中停止has、crs、cluster的区别
  • WooCommerce与wordpress是什么关系
  • 遥感影像-实例分割数据集:iSAID 从切图到YOLO格式数据集制作详细介绍
  • 字段临时缓存包装器
  • Qt/C++开源控件 自定义雷达控件
  • 计算机取证
  • win用户数据保存路径更改
  • 银河麒麟桌面操作系统修改默认Shell为Bash
  • linux下sudo执行的程序会有一个额外的进程的问题
  • 螺蛳壳里做道场:老破机搭建的私人数据中心---Centos下Docker学习01(环境准备)
  • 【笔记】数据结构
  • 基于单片机的宠物喂食(ESP8266、红外、电机)
  • 第 19 场 强者挑战赛
  • 尝试从 http://pypi.doubanio.com/simple 这个索引源安装 webdriver 时出现了问题