二分查找
mid = low + (low + high)/2;
//这样可以防止越界
链表
- 反转
1.1 迭代
ListNode pre = null, cur = head, next = null;
whilt(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
1.2 递归
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
- 复制
2.1 迭代
Map<Node, Node> cachedNode = new HashMap<Node, Node>();
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
if (!cachedNode.containsKey(head)) {
Node headNew = new Node(head.val);
cachedNode.put(head, headNew);
headNew.next = copyRandomList(head.next);
headNew.random = copyRandomList(head.random);
}
return cachedNode.get(head);
}
浙公网安备 33010602011771号