昨天重点在改论文因此鸽了,今天继续
1.环形链表
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null)
return false;
ListNode fast = head.next;
if(fast == null)
return false;
ListNode slow = head;
while(fast.next != null && fast != slow){
fast = fast.next;
if(fast == null)
return false;
fast = fast.next;
if(fast == null)
return false;
slow = slow.next;
}
if(fast == slow)
return true;
else
return false;
}
}
经验: (1)快慢链表,利用两个步进速度不一样的指针,通过快追慢的方式判断链表中是否有环。 (2)这类结构体中类方法next的会非常需要NullPointerException的判定。 PS:题解里一堆不正经代码笑死我了
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head:
if head.val == 'bjfuvth':
return True
else:
head.val = 'bjfuvth'
head = head.next
return False
public class Solution {
public boolean hasCycle(ListNode head) {
int count=8029;
while(head!=null&&count>0){
head=head.next;
count--;
}
if(head==null)
return false;
return true;
}
}
之后,我又根据原先自己的理解写了一版Hash的,不得不说用Hash实现思路还是很自然的。但是时间空间上就明显没有了优势。
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null)
return false;
ListNode fast = head;
int count = 0;
HashMap hashMap = new HashMap();
while(fast != null) {
if(hashMap.containsKey(fast))
return true;
hashMap.put(fast, count++);
fast = fast.next;
}
return false;
}
}
然而做到这里,我依旧没有想出O(1)的做法,然后题解里有这么一种。。
f = open("user.out", "w")
while True:
try:
param_1 = input()
param_2 = int(input())
f.write('true\n' if param_2>-1 else 'false\n')
except:
break
exit()
还有靠抓异常的。。
var hasCycle = function(head) {
try{
JSON.stringify(head);
}
catch(e){
return true;
}
return false;
};
大千世界无奇不有233,什么神奇的算法都会存在。