Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
humingk committed Jun 3, 2024
1 parent 22fec5a commit eb55980
Showing 1 changed file with 54 additions and 1 deletion.
55 changes: 54 additions & 1 deletion _posts/2019-03-18-alg-note.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,10 @@ categories : alg
二分遍历:
归并排序:递归拆分两个数组,直到只有一个元素,通过辅助数组的比较归并两个有序数组
快速排序(三切分):三指针前后遍历,切分小于、等于和大于第一个值,然后递归排序小于和大于部分
堆排序:先通过下沉构造一个最大堆,依次将堆顶的最大值和末尾值交换,并继续下沉构造新的最大堆
```



#### 实现原理

- 插入排序
Expand Down Expand Up @@ -729,6 +729,8 @@ public class Heap {
}
```

oj:https://leetcode.cn/problems/sort-an-array/submissions/536995680/
```java
class Solution {
public int[] sortArray(int[] nums) {
if (nums == null || nums.length <= 1) {
Expand Down Expand Up @@ -6129,6 +6131,57 @@ public class Solution {
}
```

OJ:https://leetcode.cn/problems/smallest-k-lcci/

构建最小堆

```java
class Solution {
public int[] smallestK(int[] arr, int k) {
if (arr == null || k < 0) {
return null;
}
// 先构造最小堆
for (int i = arr.length / 2; i >= 0; i--) {
sink(arr, i, arr.length - 1);
}

// 最小的k个数
int[] result = new int[k];
for (int i = arr.length - 1; k > 0; k--) {
result[k - 1] = arr[0];
arr[0] = arr[i];
i--;
sink(arr, 0, i);
}
return result;
}

private void sink(int[] arr, int root, int max) {
while (root * 2 + 1 <= max) {
// 左子节点
int son = root * 2 + 1;
// 右子节点
if (son + 1 <= max && arr[son] > arr[son + 1]) {
son++;
}
if (arr[son] < arr[root]) {
exchange(arr, root, son);
} else {
break;
}
root = son;
}
}

private void exchange(int[] arr, int left, int right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
```



---
Expand Down

0 comments on commit eb55980

Please sign in to comment.