-
Notifications
You must be signed in to change notification settings - Fork 634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
有赞&leetcode141:判断一个单链表是否有环 #13
Comments
当然是让引擎帮你判断啦 function hasLoop(node){
try{
JSON.stringify(node)
}catch(e){
return e.toString().includes('Converting circular')
}
return false
} 哈哈哈开玩笑的,其实可以用 Map 或者快慢指针解 |
解法一:标志法给每个已遍历过的节点加标志位,遍历链表,当出现下一个节点已被标志时,则证明单链表有环 let hasCycle = function(head) {
while(head) {
if(head.flag) return true
head.flag = true
head = head.next
}
return false
}; 时间复杂度:O(n) 空间复杂度:O(n) 解法二:利用
|
哈希map var hasCycle = function(head) {
let map = new WeakMap()
if (!head && !head.next) {
return false
}
while (head) {
if (map.get(head)) {
return true
} else {
map.set(head, false)
head = head.next
}
}
return false
}; |
function Node(data) {
this.data = data
this.next = null
}
const node1 = new Node(1)
const node2 = new Node(2)
const node4 = new Node(4)
const node6 = new Node(6)
const node3 = new Node(3)
const node5 = new Node(5)
const node9 = new Node(9)
node1.next = node2
node2.next = node4
node4.next = node6
node6.next = node5
node5.next = node9
node9.next = node6
let hasCycle = function (head) {
if (!head || !head.next) {
return false
}
let fast = head.next.next,
slow = head.next
let i = 0
while (fast !== slow) {
if (!fast || !fast.next) {
return false
}
fast = fast.next.next
slow = slow.next
i++
}
return true
}
const hasCycle2 = (head) => {
try {
JSON.stringify(head)
return false
} catch (error) {
console.log(error)
return true
}
}
const hasCycle3 = (head) => {
let link = head
while (link) {
if (link.flag) return true
link.flag = true
link = link.next
}
return false
}
var a = hasCycle3(node1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数
pos
来表示链表尾连接到链表中的位置(索引从0
开始)。 如果pos
是-1
,则在该链表中没有环。示例 1:
示例 2:
示例 3:
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
附leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: