熟练度
https://docs.qq.com/sheet/DUGZ6cEtrUFJsSGxP
快速排序
插入排序好处:在线算法
92 区间反转链表
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
头插法
start = 2 翻转m-n条边
1 | 1->2->3->4->5->NULL |
25 k个一组反转链表
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
1 | public ListNode reverseKGroup(ListNode head, int k) { |
24 两个一组反转链表
Given 1->2->3->4, you should return the list as 2->1->4->3.
1 | public ListNode swapPairs(ListNode head) { |
11 选两点容纳的水面积最大
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
1 | public int maxArea(int[] height) { |
146 LRU cache HashMap<Integer,DoubleLinkedList>
Cache replacement policies
least recently used cache最近最少使用缓存
java:LinkedHashMap:
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#removeEldestEntry-java.util.Map.Entry-
双向链表+hashmap
1 | public class LRUCache { |
946 栈顺序
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
1 | public boolean validateStackSequences(int[] pushed, int[] popped) { |
206反转链表
空间是n1
2
3
4
5
6
7
8public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode second = reverseList(head.next);
// 1->(second:7->6->5..->2) (second:7->6->5..->2) ->1->null
head.next.next = head;
head.next = null;
return second;
}
迭代空间是1:
三个指针pre(注意初始为null),cur,next(只用于cur跳跃),用cur控制结束,一个暂存三个赋值。1
2
3
4
5
6
7
8
9
10
11
12public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode prev = null;
ListNode curr = head;
while(curr != null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
少一个指针 正确做法1
2
3
4
5
6
7
8
9
10
11public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode cur = null;
while(head!=null){
ListNode next = head.next;
head.next = cur;
cur = head;
head = next;
}
return cur;
}
python1
2
3
4
5def reverseList(self, head):
cur,prev = head,None
while cur:
cur.next,prev,cur = prev,cur,cur.next
return prev
转成栈浪费空间并且代码复杂
141链表环检测
空间O(1) 快慢指针:快指针走2步,慢指针走一步,当快指针遇到慢指针
最坏情况,快指针和慢指针相差环长q -1步
1 | class Solution{ |
142 环起始于哪个node
1->2->3->4->5->6->7->3 meet:6
a: 从head到环
b:快指针走了两次的环内距离(慢指针到环起点的距离)
c: 慢指针没走完的环内距离
已知快指针走的距离是slow的两倍
慢=a+b 快=a+2b+c
则a=c
从len(head - 环起点) == 慢指针没走完的环距离
head与慢指针能在环起点相遇。1
2
3
4
5
6
7if(slow==fast){
while(head!=slow){
head=head.next;
slow=slow.next;
}
return slow;
}