java - java中的循环检测
问题描述
我正在研究一个hackerrank问题,似乎无论我尝试的解决方案有什么变化,我都无法让循环检测工作。
这是我正在使用的代码
static boolean hasCycle(SinglyLinkedListNode head) {
if (head == null) return false;
SinglyLinkedListNode slow, fast;
slow = head;
fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
我可以调整解决方案以使其他测试通过,但不能同时通过。在这种情况下,永远不会返回 true,即使它应该返回。我该如何解决这个问题,我做错了什么?
解决方案
这与Hackerrank本身有关。我尝试了自己的解决方案,该解决方案前段时间通过了所有测试,但在存在循环的情况下也失败了。所以,我看了一下Hackerrank insertNode
用于在测试用例中创建列表的方法:
public void insertNode(int nodeData) {
// here a new node object is created each time a method is called
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
然后它是如何在他们的main
:
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int tests = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int testsItr = 0; testsItr < tests; testsItr++) {
int index = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
SinglyLinkedList llist = new SinglyLinkedList();
int llistCount = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < llistCount; i++) {
int llistItem = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
// a new node is inserted each time so no cycle can be created whatsoever.
llist.insertNode(llistItem);
}
boolean result = hasCycle(llist.head);
bufferedWriter.write(String.valueOf(result ? 1 : 0));
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
正如您所看到的,每个llistItem
值llist.insertNode(llistItem)
都被调用以将项目添加到列表中。但是,此方法无法创建循环,因为它每次都会创建一个新循环。 SinglyLinkedListNode
因此,即使某些llistItem
值相同,包含它们的节点也总是不同的。
更新
截至 2020 年 1 月 5 日,Hackerrank测试已修复,并且 OP 提供的解决方案通过了所有测试。
推荐阅读
- laravel - 从作业中发送 Guzzle http 请求后没有响应
- reactjs - redux-persist 和 AsyncStorage 有什么区别?
- java - Java,将相同的对象映射到不同的对象
- android - 类似 Snapchat 的 Viewpager 动画
- php - Laravel 在模型中定义多个外键并出现错误
- swift - 类型开关模式
- python - 如何从包含分页的网站中提取链接?(使用硒)
- php - Laravel 5.6 - 验证后表单未重新填充以前的值
- javascript - 在nl2br中使用table标签时如何避免不必要的br标签?
- swift - 在 swift 4.0 中使用枚举下标数组