添加py,js和cpp(上半部分)

pull/33/head
jaredliw 2021-07-14 23:32:30 +08:00
parent b043dc0786
commit 98bf6ded78
1 changed files with 77 additions and 13 deletions

View File

@ -46,6 +46,8 @@ public class Solution {
}
```
[](https://github.com/chefyuan/algorithm-base/blob/main/animation-simulation/%E9%93%BE%E8%A1%A8%E7%AF%87/leetcode141%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8.md)。
绿
绿2
@ -62,23 +64,22 @@ public class Solution {
![image-20201027182649669](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/image-20201027182649669.2g8gq4ik6xs0.png)
Java Code:
```java
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return head;
}
if (head.next == null) {
return head.next;
}
//创建新的HashSet,用于保存节点
//创建新的HashSet用于保存节点
HashSet<ListNode> hash = new HashSet<ListNode>();
//遍历链表
while (head != null) {
//判断哈希表中是否含有某节点,没有则保存,含有则返回该节点
//判断哈希表中是否含有某节点,没有则保存,含有则返回该节点
if (hash.contains(head)) {
return head;
}
@ -91,6 +92,70 @@ public class Solution {
}
```
C++ Code:
```cpp
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == nullptr) return head;
if (head->next == nullptr) return head->next;
set<ListNode *> hash;
while (head != nullptr) {
if (hash.count(head)) {
return head;
}
hash.insert(head);
head = head->next;
}
return head;
}
};
```
JS Code:
```javascript
var detectCycle = function(head) {
if (head === null) return head;
if (head.next === null) return head.next;
//创建新的HashSet用于保存节点
let hash = new Set();
//遍历链表
while (head !== null) {
//判断哈希表中是否含有某节点,没有则保存,含有则返回该节点
if (hash.has(head)) {
return head;
}
//不含有,则进行保存,并移动指针
hash.add(head);
head = head.next;
}
return head;
};
```
Python Code:
```py
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head is None:
return head
if head.next is None:
return head.next
# HashSet
hash = set()
while head is not None:
#
if head in hash:
return head
#
hash.add(head)
head = head.next
return head
```
###
@ -101,25 +166,25 @@ public class Solution {
**a+(b+c)n+b**
**a+(b+c)n+b**n
b+ca线bna+(b+c)n+ba+(n+1)b+nc
**a+(b+c)m+b**,m
**a+(b+c)m+b**m
2,2
22
**a+(n+1)b+nc=2[a+(m+1)b+mc]****a+b=(n-2m)(b+c)****b+c**
**a+(n+1)b+nc=2[a+(m+1)b+mc]****a+b=(n-2m)(b+c)**
a+bn-2m便n-2m1a+b=b+ca=cheada=c
**b+c**a+bn-2m便n-2m1a+b=b+ca=cheada=c
1.2
1.2
2.
2.
3.head1
3.head1
![2](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/环形链表2.elwu1pw2lw0.gif)
@ -150,7 +215,6 @@ public class Solution {
}
}
return null;
}
}
```