mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Merge branch 'master' of github.com:youngyangyang04/leetcode-master
This commit is contained in:
@@ -81,7 +81,7 @@ public:
|
||||
|
||||
上面的代码我第一次提交执行用时8ms,打败6.5%的用户,差点吓到我了。
|
||||
|
||||
心想应该没有更好的方法了吧,也就$O(n)$的时间复杂度,重复提交几次,这样了:
|
||||
心想应该没有更好的方法了吧,也就 $O(n)$ 的时间复杂度,重复提交几次,这样了:
|
||||
|
||||

|
||||
|
||||
@@ -181,6 +181,23 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
// 将步骤 2,3 交换顺序,这样不用定义 temp 节点
|
||||
public ListNode swapPairs(ListNode head) {
|
||||
ListNode dummy = new ListNode(0, head);
|
||||
ListNode cur = dummy;
|
||||
while (cur.next != null && cur.next.next != null) {
|
||||
ListNode node1 = cur.next;// 第 1 个节点
|
||||
ListNode node2 = cur.next.next;// 第 2 个节点
|
||||
cur.next = node2; // 步骤 1
|
||||
node1.next = node2.next;// 步骤 3
|
||||
node2.next = node1;// 步骤 2
|
||||
cur = cur.next.next;
|
||||
}
|
||||
return dummy.next;
|
||||
}
|
||||
```
|
||||
|
||||
### Python:
|
||||
|
||||
```python
|
||||
@@ -285,6 +302,21 @@ var swapPairs = function (head) {
|
||||
};
|
||||
```
|
||||
|
||||
```javascript
|
||||
// 递归版本
|
||||
var swapPairs = function (head) {
|
||||
if (head == null || head.next == null) {
|
||||
return head;
|
||||
}
|
||||
|
||||
let after = head.next;
|
||||
head.next = swapPairs(after.next);
|
||||
after.next = head;
|
||||
|
||||
return after;
|
||||
};
|
||||
```
|
||||
|
||||
### TypeScript:
|
||||
|
||||
```typescript
|
||||
|
||||
Reference in New Issue
Block a user