From ac82e7d7f550f51cb76324d3910436ec4c649c75 Mon Sep 17 00:00:00 2001 From: sanwuhong Date: Mon, 6 Feb 2023 00:36:37 +0800 Subject: [PATCH] update algorithm --- .../java/com/learning/algorithm/ALGORITHM.md | 33 +++++++++- .../com/learning/algorithm/Algorithm4.java | 65 +++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/learning/algorithm/Algorithm4.java diff --git a/src/main/java/com/learning/algorithm/ALGORITHM.md b/src/main/java/com/learning/algorithm/ALGORITHM.md index ebbf8fa..679507c 100644 --- a/src/main/java/com/learning/algorithm/ALGORITHM.md +++ b/src/main/java/com/learning/algorithm/ALGORITHM.md @@ -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 (keya[mid]) return rank(key, a, mid+1, hi); + else return mid; + } +} +``` + ### 递归三要素 @@ -2211,4 +2233,13 @@ public class Solution{ } } -``` \ No newline at end of file +``` + +# 算法4原书 + + +```java + + +``` + diff --git a/src/main/java/com/learning/algorithm/Algorithm4.java b/src/main/java/com/learning/algorithm/Algorithm4.java new file mode 100644 index 0000000..31faf8b --- /dev/null +++ b/src/main/java/com/learning/algorithm/Algorithm4.java @@ -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; + } +}