今天看了一下校招算法题,没想到比社招算法题离谱的不止一点点,基于此,我们开始熟练掌握一部分有可能必出的代码,背一背八股,马爸爸求你中一回吧
1、昨日写过的堆排,把int[]转成堆排
public static void main(String[] args) {
int[] arr = {1, 4, 7, 8, 9, 6, 5, 2, 3};
heapSort(arr);
System.out.println(arr);
}
public static void heapSort(int[] arr) {
buildHeap(arr, arr.length);
for (int i = 0; i < arr.length; i++) {
swap(arr, 0, arr.length - i - 1);
maxHeap(arr, 0, arr.length - i - 1);
}
}
public static void buildHeap(int[] arr, int heapSize) {
for (int i = (heapSize - 2) >> 1; i >= 0; i--) {
maxHeap(arr, i, heapSize);
}
}
public static void maxHeap(int[] arr, int index, int heapSize) {
int left = 2 * index + 1;
int right = 2 * index + 2;
int largest = index;
//我总在这写错,每次递归都要用largest递归,不能用index递归
if (left < heapSize && arr[left] > arr[largest]) {
largest = left;
}
if (right < heapSize && arr[right] > arr[largest]) {
largest = right;
}
if (index != largest) {
swap(arr, largest, index);
maxHeap(arr, largest, heapSize);
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
2、臭名昭著快排
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void fastSort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int i = left;
int j = right;
int temp = arr[left];
//注意两层while的思路
while (i < j) {
while (j > i && arr[j] >= temp) {
j--;
}
while (i < j && arr[i] <= temp) {
i++;
}
if (i < j) {
swap(arr, i, j);
}
}
swap(arr, left, i);
quickSort(arr, left, i - 1);
quickSort(arr, i + 1, right);
}
LRU
上次写的复杂的,这次先写简单的,再写复杂的
class LRUCache extends LinkedHashMap<Integer, Integer>{
private int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75F, true);
this.capacity = capacity;
}
public int get(int key) {
return super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
其余:
rand5()实现rand3()
public static int rand3(){
int i = rand5();
while(i>3){
i = rand5();
}
return i;
}
rand5()实现rand7()
思路产生【1,2,3,4,5】,我需要一个更大的数据区域去分片,能映射到1-7上,那么至少要大于7,且每个数字出现的概率相等,做法:rand5-1范围【0,1,2,3,4】,结果乘以5,得到【0,5,10,15,20】,(rand5-1)*5+rand5得到【0-24】 等概率数,之后分组即可
public static int rand7() {
int i;
do {
i = (rand5() - 1) * 5 + rand5();
} while (i > 21);
return i % 7 + 1;
}
当然这样写也行:
public static int rand7q() {
while (true) {
int i = (rand5() - 1) * 5 + rand5();
if (i > 22) {
continue;
} else {
return i % 7 + 1;
}
}
}