下面所记录的是我在刷 LeetCode Array 相关的题目自己的解法。
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
JavaScript Solution
递归方法
1 | /** |
Java Solution
迭代方法
1 | /** |
83. Remove Duplicates from Sorted List
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
JavaScript Solution
1 | /** |
Java Solution
递归方法
1 | public ListNode deleteDuplicates(ListNode head) { |
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
JavaScript Solution
1 | /** |
Best Solution
Best Solution 的做法是一个 fast runner 和一个 slow runner,如果有环路,fast 最终一定可以和 slow 遇上。
1 | /** |
160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
1 | A: a1 → a2 |
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null
.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Best Solution
这个解法妙在将两个链表合为一个链表,比如:
1 | 0 -> 1 -> 2 //第一个链表 |
合成后的链表为:
1 | 0 1 2 3 4 5 1 2 //第一个链表 |
经过比较就可以找到相同的点
1 | /** |
203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
JavaScript Solution
如果链表的第一个值不方便处理的时候,可以再创建一个节点指向第一个值。
1 | /** |
Best Solution
递归方法,这个方法的思想就是,如果本节点不满足要求,就返回下一个节点。
1 | /** |
206. Reverse Linked List
Reverse a singly linked list.