https://leetcode.com/problems/circular-array-loop/

题目蛮难的,有一些坑。

前后两个指针追赶找环的方法,基本可以归结为一种定式。可以多总结。

package com.company;

class Solution {
// 参考了这里的解法
// https://discuss.leetcode.com/topic/66894/java-slow-fast-pointer-solution
public boolean circularArrayLoop(int[] nums) {
for (int i=; i<nums.length; i++) {
if (nums[i] == ) {
continue;
}
int j = i, k = getIndex(i, nums);
// 检查同方向
while (nums[i] * nums[k] > && nums[i] * nums[getIndex(k, nums)] > ) {
if (j == k) {
// 碰到了
// 检查是否只有一个元素
if (j == getIndex(j, nums)) {
break;
}
return true;
}
// 一前一后两个指针
j = getIndex(j, nums);
k = getIndex(getIndex(k, nums), nums);
}
// 把已经走过的,置为0
j = i;
k = nums[j];
// 但要注意不同方向的不要置为0
while (nums[j]*k > ) {
int tmp = getIndex(j, nums);
nums[j] = ;
j = tmp;
}
}
return false;
} // 下面这个函数也是参考了上面Discuss里面的解法
private int getIndex(int i, int[] nums) {
int n = nums.length;
int j = (i + nums[i]) >= ? (i + nums[i]) % n : n + ((i + nums[i]) % n);
return j;
}
} public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!");
Solution solution = new Solution(); // Your Codec object will be instantiated and called as such:
int[] nums = {, -, , -, -};
boolean ret = solution.circularArrayLoop(nums);
System.out.printf("ret:%b\n", ret); System.out.println(); } }

最新文章

  1. 一个页面从输入 URL 到页面加载完的过程中都发生了什么事情?
  2. ctl 里面pdef解说
  3. HDU 1512 Monkey King
  4. cocos2d-x项目过程记录(ios和android设备的适配)
  5. AltiumDesignerSummer9Build9.3.1.19182破解图文教程
  6. orleans开篇之hello world
  7. 使用VS Code开发调试.NET Core 2.0
  8. java 二叉树
  9. 台达wplsoft2.34指令表
  10. symfony command
  11. c++模板笔记
  12. Fedora下安装deb包方法
  13. 9.线程通信wait、notify
  14. nyoj16矩形嵌套(第一道dp关于dag的题目)
  15. 转Web开发的发展史---Web开发技术的演变
  16. python_day7学习笔记
  17. 不只是内存分析工具~valgrind
  18. tomcat solr 限制ip
  19. (转)CocoaPods
  20. python爬虫基础06-常见加密算法

热门文章

  1. Wordpress 自定义文章类型添加 Categoried、Tags
  2. 如何删除本地docker images镜像
  3. Log4j官方文档翻译(七、日志格式化)
  4. windows部分快捷键及terminal命令
  5. autoprefixer小记
  6. 合理使用webpack提高开发效率
  7. canvas游戏开发系列(1):基础知识
  8. 存储过程中set什么什么的讲解
  9. android的布局-----RelativeLayout(相对布局)
  10. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---37