Skip to content

Commit

Permalink
update algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
rbmonster committed Feb 5, 2023
1 parent 367cdef commit ac82e7d
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/main/java/com/learning/algorithm/ALGORITHM.md
Original file line number Diff line number Diff line change
Expand Up @@ -1233,6 +1233,28 @@ BFS与DFS相关的问题,经常都可以用两种方式求解,因此把相
- [可能的二分法](https://leetcode.cn/problems/possible-bipartition/)

## 递归
编写递归代码时最重要的有以下三点:
1. 递归总有一个最简单的情况 — 方法的第一条语句总是一个包含return的条件语句。
2. 递归调用总是去**尝试解决一个规模更小的子问题**,这样递归才能收敛到最简单的情况。如下代码第三、四参数的差值一直在缩小。
3. 递归调用的父问题和尝试解决的子问题之间不应该有交集。

```java
class Solution {
public static int rank(int key, int[] a) {
return rank(key, a, 0, a.length - 1);
}

public static int rank(int key, int[] a ,int lo, int hi){
// 如果key存在于数组中,它的索引不会小于lo且不会大于hi
if(lo>hi) return -1;
int mid = lo + (hi -lo)/2;
if (key<a[mid]) return rank(key, a, lo, mid -1);
else if(key>a[mid]) return rank(key, a, mid+1, hi);
else return mid;
}
}
```


### 递归三要素

Expand Down Expand Up @@ -2211,4 +2233,13 @@ public class Solution{

}
}
```
```

# 算法4原书


```java


```

65 changes: 65 additions & 0 deletions src/main/java/com/learning/algorithm/Algorithm4.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.learning.algorithm;

public class Algorithm4 {

private double forMaxElement(double[] num) {
double max = num[0];
for (int i = 1; i < num.length; i++) {
if (num[i] > max) {
max = num[i];
}
}
return max;
}

public static boolean isPrime(int N) {
if (N < 2) {
return false;
}
for (int i = 2; i * i <= N; i++) {
if (N % i == 0) {
return false;
}
}
return true;
}

/**
* 计算平方根
* 牛顿迭代法
*
* @param c
* @return
*/
public static double sqrt(double c) {
if (c < 0) {
return Double.NaN;
}
double err = 1e-15;
double t = c;

while (Math.abs(t - c / t) > err * t) {
t = (c / t + t) / 2.0;
}
return t;
}

/**
* 计算调和级数
*
* @param N
* @return
*/
public static double H(int N) {
double sum = 0.0;
for (int i = 0; i <= N; i++) {
sum += 1.0 / i;
}
return sum;
}

public static void main(String[] args) {
double sum = 0.0;
int cnt = 0;
}
}

0 comments on commit ac82e7d

Please sign in to comment.