题目主要来源:LeetCode。主要选自剑指offer、程序员面试宝典。
每日尽可能保持 N+1 道题,N 取 0 到 9。部分解法是从LeetCode上大佬们的解法中拿过来的,如有侵权,告知立删
文章目录
0x01 剑指 Offer 35. 复杂链表的复制
/**
* JZ35 构建一个map,存储原链表和新链表的映射
*
* @author Anjude
* @date 2021/7/16 22:26
*/
public class JZ35 {
public Node copyRandomList(Node head) {
if(head == null)return null;
Node cur = head;
Map<Node, Node> map = new HashMap<>();
while (cur != null){
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur!= null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
0x02 剑指 Offer 40. 最小的k个数
/**
* JZ40 可用方法很多:快排/堆/二叉搜索树/计数排序,此处只写了快排全部排序的
*
* @author Anjude
* @date 2021/7/17 21:05
*/
public class JZ40 {
public int[] getLeastNumbers(int[] arr, int k) {
if (arr == null || arr.length <= k) return arr;
quickSort(arr, 0, arr.length - 1);
return Arrays.copyOfRange(arr, 0, k);
}
private void quickSort(int[] arr, int l, int r) {
if (l >= r) return;
int standard = arr[l];
int i = l, j = r;
while (i < j) {
// 找到第一个小于基准值的数的下标d(从右往左)
while (i < j && arr[j] > standard) {
j--;
}
if (i < j) {
arr[i] = arr[j];
arr[j] = standard;
i++;
}
// 找到第一个大于基准值的数的下标(从左往右)
while (i < j && arr[i] < standard) {
i++;
}
if (i < j) {
arr[j] = arr[i];
arr[i] = standard;
j--;
}
}
quickSort(arr, l, i - 1);
quickSort(arr, i + 1, r);
}
}
0x03 剑指 Offer 30. 包含min函数的栈
/**
* JZ30 构造一个数组,存储当前最小值,缺少 throws 的代码
*
* @author Anjude
* @date 2021/7/17 23:37
*/
public class JZ30 {
private List<StackNode> myStack;
private StackNode top;
private int size;
public JZ30() {
myStack = new ArrayList<>();
}
public void push(int x) {
StackNode stackNode = new StackNode();
if (top == null || top.min > x) {
stackNode.min = x;
} else {
stackNode.min = top.min;
}
stackNode.val = x;
top = stackNode;
size++;
myStack.add(stackNode);
}
public void pop() {
if (size == 0) {
return;
} else if (size == 1) {
myStack = new ArrayList<>();
top = null;
size = 0;
} else {
top = myStack.get(size - 2);
myStack.remove(size - 1);
size--;
}
}
public int top() {
if (top == null) {
return -1;
}
return top.val;
}
public int min() {
if (top == null) {
return -1;
}
return top.min;
}
static class StackNode {
int val;
int min;
}
public static void main(String[] args) throws Exception {
JZ30 jz30 = new JZ30();
jz30.push(-2);
jz30.push(0);
jz30.push(-3);
System.out.println(jz30.min());
jz30.pop();
System.out.println(jz30.top());
System.out.println(jz30.min());
}
}