From 866032c16d5977a0e55d44b8086c60712032275a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=97=A8=E5=97=A8=E5=97=A8?= <111850394+QinWeijia111@users.noreply.github.com> Date: Wed, 11 Sep 2024 15:26:40 +0800 Subject: [PATCH 01/26] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加Python语言版本的双指针去除空格算法的非调包算法 --- problems/0151.翻转字符串里的单词.md | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index a0005198..bf486bdc 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -475,7 +475,45 @@ class Solution: words = words[::-1] # 反转单词 return ' '.join(words) #列表转换成字符串 ``` +(版本四) 将字符串转换为列表后,使用双指针去除空格 +```python +class Solution: + def single_reverse(self, s, start: int, end: int): + while start < end: + s[start], s[end] = s[end], s[start] + start += 1 + end -= 1 + def reverseWords(self, s: str) -> str: + result = "" + fast = 0 + # 1. 首先将原字符串反转并且除掉空格, 并且加入到新的字符串当中 + # 由于Python字符串的不可变性,因此只能转换为列表进行处理 + s = list(s) + s.reverse() + while fast < len(s): + if s[fast] != " ": + if len(result) != 0: + result += " " + while s[fast] != " " and fast < len(s): + result += s[fast] + fast += 1 + else: + fast += 1 + # 2.其次将每个单词进行翻转操作 + slow = 0 + fast = 0 + result = list(result) + while fast <= len(result): + if fast == len(result) or result[fast] == " ": + self.single_reverse(result, slow, fast - 1) + slow = fast + 1 + fast += 1 + else: + fast += 1 + + return "".join(result) +``` ### Go: 版本一: From 4f9d9491ae07d68cdd671a28b1b33c294569e00d Mon Sep 17 00:00:00 2001 From: markwang Date: Wed, 11 Sep 2024 17:30:52 +0800 Subject: [PATCH 02/26] =?UTF-8?q?494.=E7=9B=AE=E6=A0=87=E5=92=8C=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0Go=E4=BA=8C=E7=BB=B4dp=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0494.目标和.md | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 82d330b7..dc8d6c0f 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -675,6 +675,57 @@ class Solution: ``` ### Go +二维dp +```go +func findTargetSumWays(nums []int, target int) int { + sum := 0 + for _, v := range nums { + sum += v + } + if math.Abs(float64(target)) > float64(sum) { + return 0 // 此时没有方案 + } + if (target + sum) % 2 == 1 { + return 0 // 此时没有方案 + } + bagSize := (target + sum) / 2 + + dp := make([][]int, len(nums)) + for i := range dp { + dp[i] = make([]int, bagSize + 1) + } + + // 初始化最上行 + if nums[0] <= bagSize { + dp[0][nums[0]] = 1 + } + + // 初始化最左列,最左列其他数值在递推公式中就完成了赋值 + dp[0][0] = 1 + + var numZero float64 + for i := range nums { + if nums[i] == 0 { + numZero++ + } + dp[i][0] = int(math.Pow(2, numZero)) + } + + // 以下遍历顺序行列可以颠倒 + for i := 1; i < len(nums); i++ { // 行,遍历物品 + for j := 0; j <= bagSize; j++ { // 列,遍历背包 + if nums[i] > j { + dp[i][j] = dp[i-1][j] + } else { + dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i]] + } + } + } + return dp[len(nums)-1][bagSize] +} +``` + +一维dp ```go func findTargetSumWays(nums []int, target int) int { sum := 0 From b5e3b801d37b290b48d03cdca1ef3a81d680e95b Mon Sep 17 00:00:00 2001 From: Elio Zhou <30508272+eliozh@users.noreply.github.com> Date: Wed, 11 Sep 2024 18:56:36 +0800 Subject: [PATCH 03/26] =?UTF-8?q?Update=200236.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化Rust版本0236.二叉树的最近公共祖先代码 --- problems/0236.二叉树的最近公共祖先.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 5e80e702..2e94f7a7 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -454,7 +454,11 @@ impl Solution { p: Option>>, q: Option>>, ) -> Option>> { - if root == p || root == q || root.is_none() { + if root.is_none() { + return root; + } + if Rc::ptr_eq(root.as_ref().unwrap(), p.as_ref().unwrap()) + || Rc::ptr_eq(root.as_ref().unwrap(), q.as_ref().unwrap()) { return root; } let left = Self::lowest_common_ancestor( From b7ddc4a4abdb8cde5e020d47d7ed37e18a9df91b Mon Sep 17 00:00:00 2001 From: markwang Date: Thu, 12 Sep 2024 16:07:01 +0800 Subject: [PATCH 04/26] =?UTF-8?q?518.=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2I?= =?UTF-8?q?I=E5=A2=9E=E5=8A=A0Go=E4=BA=8C=E7=BB=B4dp=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0518.零钱兑换II.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index 255912d6..bef62b30 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -268,6 +268,7 @@ class Solution: ### Go: +一维dp ```go func change(amount int, coins []int) int { // 定义dp数组 @@ -286,6 +287,29 @@ func change(amount int, coins []int) int { return dp[amount] } ``` +二维dp +```go +func change(amount int, coins []int) int { + dp := make([][]int, len(coins)) + for i := range dp { + dp[i] = make([]int, amount + 1) + dp[i][0] = 1 + } + for j := coins[0]; j <= amount; j++ { + dp[0][j] += dp[0][j-coins[0]] + } + for i := 1; i < len(coins); i++ { + for j := 1; j <= amount; j++ { + if j < coins[i] { + dp[i][j] = dp[i-1][j] + } else { + dp[i][j] = dp[i][j-coins[i]] + dp[i-1][j] + } + } + } + return dp[len(coins)-1][amount] +} +``` ### Rust: From b5161e725dc25e2994a903935858d557707cef18 Mon Sep 17 00:00:00 2001 From: markwang Date: Fri, 13 Sep 2024 09:49:36 +0800 Subject: [PATCH 05/26] =?UTF-8?q?kama57.=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?=E8=A1=A5=E5=85=85Go=E8=A7=A3=E6=B3=95package=E5=92=8Cimport?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯完全背包版本.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index 07e0261e..c51a590b 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -184,6 +184,16 @@ if __name__ == '__main__': ### Go: ```go +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + func climbStairs(n int, m int) int { dp := make([]int, n+1) dp[0] = 1 From 8be83e8138532b03aa7b114a7bd84dae325b213c Mon Sep 17 00:00:00 2001 From: cyxiwai Date: Fri, 13 Sep 2024 10:02:13 +0800 Subject: [PATCH 06/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=B9=B6=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E4=BA=86kama0109.=E5=86=97=E4=BD=99=E9=93=BE=E6=8E=A5?= =?UTF-8?q?II=E7=9A=84Java=E7=89=88=E6=9C=AC=EF=BC=8C=E9=99=84=E6=9C=89?= =?UTF-8?q?=E8=AF=A6=E7=BB=86=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0109.冗余连接II.md | 98 +++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/problems/kamacoder/0109.冗余连接II.md b/problems/kamacoder/0109.冗余连接II.md index fd834357..bd707bf6 100644 --- a/problems/kamacoder/0109.冗余连接II.md +++ b/problems/kamacoder/0109.冗余连接II.md @@ -250,7 +250,105 @@ int main() { ## 其他语言版本 ### Java +```java +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +public class Main { + static int n; + static int[] father = new int[1001]; // 并查集数组 + + // 并查集初始化 + public static void init() { + for (int i = 1; i <= n; ++i) { + father[i] = i; + } + } + + // 并查集里寻根的过程 + public static int find(int u) { + if (u == father[u]) return u; + return father[u] = find(father[u]); // 路径压缩 + } + + // 将 v->u 这条边加入并查集 + public static void join(int u, int v) { + u = find(u); + v = find(v); + if (u != v) { + father[v] = u; // 合并两棵树 + } + } + + // 判断 u 和 v 是否有同一个根 + public static boolean same(int u, int v) { + return find(u) == find(v); + } + + // 在有向图里找到删除的那条边,使其变成树 + public static void getRemoveEdge(List edges) { + init(); // 初始化并查集 + for (int i = 0; i < n; i++) { // 遍历所有的边 + if (same(edges.get(i)[0], edges.get(i)[1])) { // 如果构成有向环了,就是要删除的边 + System.out.println(edges.get(i)[0] + " " + edges.get(i)[1]); + return; + } else { + join(edges.get(i)[0], edges.get(i)[1]); + } + } + } + + // 删一条边之后判断是不是树 + public static boolean isTreeAfterRemoveEdge(List edges, int deleteEdge) { + init(); // 初始化并查集 + for (int i = 0; i < n; i++) { + if (i == deleteEdge) continue; + if (same(edges.get(i)[0], edges.get(i)[1])) { // 如果构成有向环了,一定不是树 + return false; + } + join(edges.get(i)[0], edges.get(i)[1]); + } + return true; + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + List edges = new ArrayList<>(); // 存储所有的边 + + n = sc.nextInt(); // 顶点数 + int[] inDegree = new int[n + 1]; // 记录每个节点的入度 + for (int i = 0; i < n; i++) { + int s = sc.nextInt(); // 边的起点 + int t = sc.nextInt(); // 边的终点 + inDegree[t]++; + edges.add(new int[]{s, t}); // 将边加入列表 + } + + List vec = new ArrayList<>(); // 记录入度为2的边(如果有的话就两条边) + // 找入度为2的节点所对应的边,注意要倒序,因为优先删除最后出现的一条边 + for (int i = n - 1; i >= 0; i--) { + if (inDegree[edges.get(i)[1]] == 2) { + vec.add(i); + } + } + + // 情况一、情况二 + if (vec.size() > 0) { + // vec里的边已经按照倒叙放的,所以优先删 vec.get(0) 这条边 + if (isTreeAfterRemoveEdge(edges, vec.get(0))) { + System.out.println(edges.get(vec.get(0))[0] + " " + edges.get(vec.get(0))[1]); + } else { + System.out.println(edges.get(vec.get(1))[0] + " " + edges.get(vec.get(1))[1]); + } + return; + } + + // 处理情况三:明确没有入度为2的情况,一定有有向环,找到构成环的边返回即可 + getRemoveEdge(edges); + } +} +``` ### Python ### Go From d6cd5e0ceff6c26dde8083b81b9316b832721bfc Mon Sep 17 00:00:00 2001 From: Yufan SHENG Date: Fri, 13 Sep 2024 14:28:49 +1000 Subject: [PATCH 07/26] =?UTF-8?q?=E6=9B=B4=E6=96=B00110=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91Python3=E8=BF=AD=E4=BB=A3=E6=B3=95?= =?UTF-8?q?=E7=B2=BE=E7=AE=80=E7=89=88=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index f8071333..ec120bcc 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -609,10 +609,13 @@ class Solution: while stack: node = stack.pop() if node: - stack.append(node) + stack.append(node) # 中 stack.append(None) - if node.left: stack.append(node.left) - if node.right: stack.append(node.right) + # 采用数组进行迭代,先将右子树加入,保证左节点能够先出栈 + if node.right: # 右 + stack.append(node.right) + if node.left: # 左 + stack.append(node.left) else: real_node = stack.pop() left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0) From 507d9e04308e1859558912a3797e6f9f59106303 Mon Sep 17 00:00:00 2001 From: Yufan Sheng <18829237653@163.com> Date: Fri, 13 Sep 2024 14:40:58 +1000 Subject: [PATCH 08/26] =?UTF-8?q?=E6=9B=B4=E6=96=B00110.=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E4=B8=AD=E7=9A=84=E4=B8=8A=E6=AC=A1?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=9A=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index ec120bcc..a4339ac3 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -611,7 +611,7 @@ class Solution: if node: stack.append(node) # 中 stack.append(None) - # 采用数组进行迭代,先将右子树加入,保证左节点能够先出栈 + # 采用数组进行迭代,先将右节点加入,保证左节点能够先出栈 if node.right: # 右 stack.append(node.right) if node.left: # 左 From 513440ad8f22c6d9a14ceb23a78e0dfde7649c67 Mon Sep 17 00:00:00 2001 From: Chemxy Date: Fri, 13 Sep 2024 19:34:17 +0800 Subject: [PATCH 09/26] =?UTF-8?q?new=20=EF=BC=9A=E6=96=B0=E5=A2=9ECangjie?= =?UTF-8?q?=E8=A7=A3=E9=A2=98=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0300.最长上升子序列.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index 9ee7bef3..f1a146b7 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -337,6 +337,29 @@ pub fn length_of_lis(nums: Vec) -> i32 { } ``` +### Cangjie: + +```cangjie +func lengthOfLIS(nums: Array): Int64 { + let n = nums.size + if (n <= 1) { + return n + } + + let dp = Array(n, item: 1) + var res = 0 + for (i in 1..n) { + for (j in 0..i) { + if (nums[i] > nums[j]) { + dp[i] = max(dp[i], dp[j] + 1) + } + } + res = max(dp[i], res) + } + return res +} +``` +

From 8127baf3fe23d735a4135900605ad9ebc3ebee63 Mon Sep 17 00:00:00 2001 From: Chemxy Date: Fri, 13 Sep 2024 20:40:37 +0800 Subject: [PATCH 10/26] =?UTF-8?q?new=EF=BC=9A=E6=96=B0=E5=A2=9ECangjie?= =?UTF-8?q?=E9=A2=98=E8=A7=A3=EF=BC=9A=E6=9C=80=E9=95=BF=E8=BF=9E=E7=BB=AD?= =?UTF-8?q?=E9=80=92=E5=A2=9E=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0674.最长连续递增序列.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index cebb552b..fe882e05 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -491,7 +491,24 @@ int findLengthOfLCIS(int* nums, int numsSize) { return result; } ``` - +### Cangjie +```cangjie +func findLengthOfLCIS(nums: Array): Int64 { + let n = nums.size + if (n <= 1) { + return n + } + let dp = Array(n, repeat: 1) + var res = 0 + for (i in 1..n) { + if (nums[i] > nums[i - 1]) { + dp[i] = dp[i - 1] + 1 + } + res = max(res, dp[i]) + } + return res +} +``` From 60f34628ebadd556d639ae3792af98df65c3476a Mon Sep 17 00:00:00 2001 From: Chemxy Date: Fri, 13 Sep 2024 20:42:36 +0800 Subject: [PATCH 11/26] =?UTF-8?q?new=EF=BC=9A=E6=96=B0=E5=A2=9ECangjie?= =?UTF-8?q?=E9=A2=98=E8=A7=A3=EF=BC=9A=E6=9C=80=E9=95=BF=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E5=AD=90=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0718.最长重复子数组.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index 6c8e7101..19520d13 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -581,6 +581,24 @@ int findLength(int* nums1, int nums1Size, int* nums2, int nums2Size) { } ``` +### Cangjie +```cangjie +func findLength(nums1: Array, nums2: Array): Int64 { + let n = nums1.size + let m = nums2.size + let dp = Array(n + 1, {_ => Array(m + 1, item: 0)}) + var res = 0 + for (i in 1..=n) { + for (j in 1..=m) { + if (nums1[i - 1] == nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1 + } + res = max(res, dp[i][j]) + } + } + return res +} +```

From d742497b528e028cff4f756524ed1d9ddc24c8da Mon Sep 17 00:00:00 2001 From: Chemxy Date: Fri, 13 Sep 2024 23:05:37 +0800 Subject: [PATCH 12/26] =?UTF-8?q?new=EF=BC=9A=E6=96=B0=E5=A2=9ECangjie?= =?UTF-8?q?=E9=A2=98=E8=A7=A3=EF=BC=9A=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1143.最长公共子序列.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index 7fa7bb68..93df987e 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -399,6 +399,24 @@ int longestCommonSubsequence(char* text1, char* text2) { } ``` +### Cangjie +```cangjie +func longestCommonSubsequence(text1: String, text2: String): Int64 { + let n = text1.size + let m = text2.size + let dp = Array(n + 1, {_ => Array(m + 1, repeat: 0)}) + for (i in 1..=n) { + for (j in 1..=m) { + if (text1[i - 1] == text2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1 + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + } + } + } + return dp[n][m] +} +```

From 8b90ac06bf65ccfa036baa6629a37eb948008108 Mon Sep 17 00:00:00 2001 From: Chemxy Date: Fri, 13 Sep 2024 23:08:46 +0800 Subject: [PATCH 13/26] =?UTF-8?q?fix=EF=BC=9A=E8=B0=83=E6=95=B4=E9=97=B4?= =?UTF-8?q?=E8=B7=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0674.最长连续递增序列.md | 2 ++ problems/0718.最长重复子数组.md | 1 + problems/1143.最长公共子序列.md | 1 + 3 files changed, 4 insertions(+) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index fe882e05..57a38404 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -491,7 +491,9 @@ int findLengthOfLCIS(int* nums, int numsSize) { return result; } ``` + ### Cangjie + ```cangjie func findLengthOfLCIS(nums: Array): Int64 { let n = nums.size diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index 19520d13..1391926a 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -582,6 +582,7 @@ int findLength(int* nums1, int nums1Size, int* nums2, int nums2Size) { ``` ### Cangjie + ```cangjie func findLength(nums1: Array, nums2: Array): Int64 { let n = nums1.size diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index 93df987e..25f32838 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -400,6 +400,7 @@ int longestCommonSubsequence(char* text1, char* text2) { ``` ### Cangjie + ```cangjie func longestCommonSubsequence(text1: String, text2: String): Int64 { let n = text1.size From 51f6ab5a54f7e6c3ee0518e2b1fd093b784d434a Mon Sep 17 00:00:00 2001 From: poivre Date: Wed, 18 Sep 2024 00:19:21 +0800 Subject: [PATCH 14/26] =?UTF-8?q?docs:=20=E6=9B=B4=E6=AD=A30459=E7=9A=84?= =?UTF-8?q?=E6=96=87=E6=9C=AC=E7=9A=84=E8=AF=AD=E5=8F=A5=E9=99=88=E8=BF=B0?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 254d921d..41c2ea2d 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -163,7 +163,7 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一 如果一个字符串s是由重复子串组成,那么 最长相等前后缀不包含的子串一定是字符串s的最小重复子串。 -证明: 如果s 是有是有最小重复子串p组成。 +证明: 如果s 是由最小重复子串p组成。 即 s = n * p @@ -884,3 +884,4 @@ public int[] GetNext(string s) + From ee41f4df2203884a884a108bc9cc2662f4fdc823 Mon Sep 17 00:00:00 2001 From: poivre Date: Wed, 18 Sep 2024 00:27:25 +0800 Subject: [PATCH 15/26] =?UTF-8?q?Revert=20"docs:=20=E6=9B=B4=E6=AD=A30459?= =?UTF-8?q?=E7=9A=84=E6=96=87=E6=9C=AC=E7=9A=84=E8=AF=AD=E5=8F=A5=E9=99=88?= =?UTF-8?q?=E8=BF=B0=E3=80=82"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 51f6ab5a54f7e6c3ee0518e2b1fd093b784d434a. --- problems/0459.重复的子字符串.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 41c2ea2d..254d921d 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -163,7 +163,7 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一 如果一个字符串s是由重复子串组成,那么 最长相等前后缀不包含的子串一定是字符串s的最小重复子串。 -证明: 如果s 是由最小重复子串p组成。 +证明: 如果s 是有是有最小重复子串p组成。 即 s = n * p @@ -884,4 +884,3 @@ public int[] GetNext(string s) - From 69a413c3e65ce07144bfdb8199ee0b2d47080e33 Mon Sep 17 00:00:00 2001 From: poivre Date: Wed, 18 Sep 2024 00:28:17 +0800 Subject: [PATCH 16/26] =?UTF-8?q?docs:=20=E6=9B=B4=E6=AD=A30459=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E4=B8=AD=E6=96=87=E6=9C=AC=E7=9A=84=E9=99=88=E8=BF=B0?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 254d921d..dbf32e64 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -163,7 +163,7 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一 如果一个字符串s是由重复子串组成,那么 最长相等前后缀不包含的子串一定是字符串s的最小重复子串。 -证明: 如果s 是有是有最小重复子串p组成。 +证明: 如果s 是由最小重复子串p组成。 即 s = n * p @@ -179,7 +179,7 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240913110841.png) -这里有录友就想:如果字符串s 是有是有最小重复子串p组成,最长相等前后缀就不能更长一些? 例如这样: +这里有录友就想:如果字符串s 是由最小重复子串p组成,最长相等前后缀就不能更长一些? 例如这样: ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240913114348.png) @@ -884,3 +884,4 @@ public int[] GetNext(string s) + From 75f587507dea0f21ec667a38c049b9324b982f9d Mon Sep 17 00:00:00 2001 From: DraculaJay <113758447+DraculaJay@users.noreply.github.com> Date: Sat, 21 Sep 2024 04:52:40 +0800 Subject: [PATCH 17/26] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86python?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E5=89=AA=E6=9E=9D=E6=93=8D=E4=BD=9C=EF=BC=8C?= =?UTF-8?q?=E9=80=9A=E8=BF=87=E5=AF=B9=E5=89=A9=E4=BD=99=E5=85=83=E7=B4=A0?= =?UTF-8?q?=E9=95=BF=E5=BA=A6=E7=9A=84=E5=88=A4=E6=96=AD=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E5=89=AA=E6=9E=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index d1300a39..eb81f4b6 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -467,9 +467,37 @@ class Solution: num = int(s[start:end+1]) return 0 <= num <= 255 +回溯(版本三) - - +```python +class Solution: + def restoreIpAddresses(self, s: str) -> List[str]: + result = [] + self.backtracking(s, 0, [], result) + return result + + def backtracking(self, s, startIndex, path, result): + if startIndex == len(s): + result.append('.'.join(path[:])) + return + + for i in range(startIndex, min(startIndex+3, len(s))): + # 如果 i 往后遍历了,并且当前地址的第一个元素是 0 ,就直接退出 + if i > startIndex and s[startIndex] == '0': + break + # 比如 s 长度为 5,当前遍历到 i = 3 这个元素 + # 因为还没有执行任何操作,所以此时剩下的元素数量就是 5 - 3 = 2 ,即包括当前的 i 本身 + # path 里面是当前包含的子串,所以有几个元素就表示储存了几个地址 + # 所以 (4 - len(path)) * 3 表示当前路径至多能存放的元素个数 + # 4 - len(path) 表示至少要存放的元素个数 + if (4 - len(path)) * 3 < len(s) - i or 4 - len(path) > len(s) - i: + break + if i - startIndex == 2: + if not int(s[startIndex:i+1]) <= 255: + break + path.append(s[startIndex:i+1]) + self.backtracking(s, i+1, path, result) + path.pop() ``` ### Go From b3c0d03885496324d5cea3427ccd6cd633368e0a Mon Sep 17 00:00:00 2001 From: Runze Liao <72693579+tony8888lrz@users.noreply.github.com> Date: Fri, 20 Sep 2024 16:56:31 -0700 Subject: [PATCH 18/26] =?UTF-8?q?Update=200343.=E6=95=B4=E6=95=B0=E6=8B=86?= =?UTF-8?q?=E5=88=86.md=20Java=E7=89=88=E6=9C=AC=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E8=B4=AA=E5=BF=83=E7=AE=97=E6=B3=95=EF=BC=8C=E6=B8=85=E6=99=B0?= =?UTF-8?q?=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0343.整数拆分.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 7295627f..3ba23e52 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -243,6 +243,29 @@ class Solution { } } ``` +贪心 +```Java +class Solution { + public int integerBreak(int n) { + // with 贪心 + // 通过数学原理拆出更多的3乘积越大,则 + /** + @Param: an int, the integer we need to break. + @Return: an int, the maximum integer after breaking + @Method: Using math principle to solve this problem + @Time complexity: O(1) + **/ + if(n == 2) return 1; + if(n == 3) return 2; + int result = 1; + while(n > 4) { + n-=3; + result *=3; + } + return result*n; + } +} +``` ### Python 动态规划(版本一) From fed25bf0125118e4b985fb58d122430b3141b919 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Sat, 21 Sep 2024 14:36:45 +0800 Subject: [PATCH 19/26] =?UTF-8?q?feat:=20=E5=9C=96=E8=AB=96100=E5=B2=9B?= =?UTF-8?q?=E5=B1=BF=E7=9A=84=E6=9C=80=E5=A4=A7=E9=9D=A2=E7=A7=AF=EF=BC=8C?= =?UTF-8?q?=E6=96=B0=E5=A2=9Ejs=E6=B7=B1=E6=90=9C=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kamacoder/0100.岛屿的最大面积.md | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/problems/kamacoder/0100.岛屿的最大面积.md b/problems/kamacoder/0100.岛屿的最大面积.md index ea62edc2..51bfc57f 100644 --- a/problems/kamacoder/0100.岛屿的最大面积.md +++ b/problems/kamacoder/0100.岛屿的最大面积.md @@ -480,7 +480,84 @@ const bfs = (graph, visited, x, y) => { })() ``` +```javascript +// 深搜版 + +const r1 = require('readline').createInterface({ input: process.stdin }); +// 创建readline接口 +let iter = r1[Symbol.asyncIterator](); +// 创建异步迭代器 +const readline = async () => (await iter.next()).value; + +let graph // 地图 +let N, M // 地图大小 +let visited // 访问过的节点 +let result = 0 // 最大岛屿面积 +let count = 0 // 岛屿内节点数 +const dir = [[0, 1], [1, 0], [0, -1], [-1, 0]] //方向 + +// 读取输入,初始化地图 +const initGraph = async () => { + let line = await readline(); + [N, M] = line.split(' ').map(Number); + graph = new Array(N).fill(0).map(() => new Array(M).fill(0)) + visited = new Array(N).fill(false).map(() => new Array(M).fill(false)) + + for (let i = 0; i < N; i++) { + line = await readline() + line = line.split(' ').map(Number) + for (let j = 0; j < M; j++) { + graph[i][j] = line[j] + } + } +} + +/** + * @description: 从(x, y)开始深度优先遍历 + * @param {*} graph 地图 + * @param {*} visited 访问过的节点 + * @param {*} x 开始搜索节点的下标 + * @param {*} y 开始搜索节点的下标 + * @return {*} + */ +const dfs = (graph, visited, x, y) => { + for (let i = 0; i < 4; i++) { + let nextx = x + dir[i][0] + let nexty = y + dir[i][1] + if(nextx < 0 || nextx >= N || nexty < 0 || nexty >= M) continue + if(!visited[nextx][nexty] && graph[nextx][nexty] === 1){ + count++ + visited[nextx][nexty] = true + dfs(graph, visited, nextx, nexty) + } + } +} + +(async function () { + + // 读取输入,初始化地图 + await initGraph() + + // 统计最大岛屿面积 + for (let i = 0; i < N; i++) { + for (let j = 0; j < M; j++) { + if (!visited[i][j] && graph[i][j] === 1) { //遇到没有访问过的陆地 + // 重新计算面积 + count = 1 + visited[i][j] = true + + // 深度优先遍历,统计岛屿内节点数,并将岛屿标记为已访问 + dfs(graph, visited, i, j) + + // 更新最大岛屿面积 + result = Math.max(result, count) + } + } + } + console.log(result); +})() +``` ### TypeScript From 99e85bfea1804fcc87458d858fed44d76c7996f2 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Sat, 21 Sep 2024 16:05:46 +0800 Subject: [PATCH 20/26] =?UTF-8?q?feat:=20=E5=9C=96=E8=AB=96101=E5=AD=A4?= =?UTF-8?q?=E5=B3=B6=E6=80=BB=E9=9D=A2=E7=A7=AF=20=EF=BC=8C=E6=96=B0?= =?UTF-8?q?=E5=A2=9Epython=E6=B7=B1=E6=90=9C=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0101.孤岛的总面积.md | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/kamacoder/0101.孤岛的总面积.md b/problems/kamacoder/0101.孤岛的总面积.md index 006484de..26c92c07 100644 --- a/problems/kamacoder/0101.孤岛的总面积.md +++ b/problems/kamacoder/0101.孤岛的总面积.md @@ -307,6 +307,71 @@ for i in range(n): print(count) ``` + +```python +direction = [[1, 0], [-1, 0], [0, 1], [0, -1]] +result = 0 + +# 深度搜尋 +def dfs(grid, y, x): + grid[y][x] = 0 + global result + result += 1 + + for i, j in direction: + next_x = x + j + next_y = y + i + if (next_x < 0 or next_y < 0 or + next_x >= len(grid[0]) or next_y >= len(grid) + ): + continue + if grid[next_y][next_x] == 1 and not visited[next_y][next_x]: + visited[next_y][next_x] = True + dfs(grid, next_y, next_x) + + +# 讀取輸入值 +n, m = map(int, input().split()) +grid = [] +visited = [[False] * m for _ in range(n)] + +for i in range(n): + grid.append(list(map(int, input().split()))) + +# 處理邊界 +for j in range(m): + # 上邊界 + if grid[0][j] == 1 and not visited[0][j]: + visited[0][j] = True + dfs(grid, 0, j) + # 下邊界 + if grid[n - 1][j] == 1 and not visited[n - 1][j]: + visited[n - 1][j] = True + dfs(grid, n - 1, j) + +for i in range(n): + # 左邊界 + if grid[i][0] == 1 and not visited[i][0]: + visited[i][0] = True + dfs(grid, i, 0) + # 右邊界 + if grid[i][m - 1] == 1 and not visited[i][m - 1]: + visited[i][m - 1] = True + dfs(grid, i, m - 1) + +# 計算孤島總面積 +result = 0 # 初始化,避免使用到處理邊界時所產生的累加值 + +for i in range(n): + for j in range(m): + if grid[i][j] == 1 and not visited[i][j]: + visited[i][j] = True + dfs(grid, i, j) + +# 輸出孤島的總面積 +print(result) +``` + ### Go ``` go From 848fbd4cd5c868839c75c637ef5ea9057ab301d7 Mon Sep 17 00:00:00 2001 From: Zhihan Li <54661071+zhihali@users.noreply.github.com> Date: Sun, 22 Sep 2024 16:22:04 +0100 Subject: [PATCH 21/26] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 551c39bf..1c7ff0cd 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -214,6 +214,7 @@ class Solution: return result ``` +贪心法 ```python class Solution: def maxSubArray(self, nums): @@ -226,8 +227,18 @@ class Solution: if count <= 0: # 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和 count = 0 return result - - +``` +动态规划 +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + dp = [0] * len(nums) + dp[0] = nums[0] + res = nums[0] + for i in range(1, len(nums)): + dp[i] = max(dp[i-1] + nums[i], nums[i]) + res = max(res, dp[i]) + return res ``` ### Go 贪心法 From 2841f59212a4f8399d53007eb01130172ce59814 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Tue, 24 Sep 2024 14:41:38 +0800 Subject: [PATCH 22/26] =?UTF-8?q?feat:=20108.=20=E5=86=97=E4=BD=99?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=96=B0=E5=A2=9Epython=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0108.冗余连接.md | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/kamacoder/0108.冗余连接.md b/problems/kamacoder/0108.冗余连接.md index 2c133782..18a86ad6 100644 --- a/problems/kamacoder/0108.冗余连接.md +++ b/problems/kamacoder/0108.冗余连接.md @@ -178,6 +178,45 @@ int main() { ### Python +```python +father = list() + +def find(u): + if u == father[u]: + return u + else: + father[u] = find(father[u]) + return father[u] + +def is_same(u, v): + u = find(u) + v = find(v) + return u == v + +def join(u, v): + u = find(u) + v = find(v) + if u != v: + father[u] = v + +if __name__ == "__main__": + # 輸入 + n = int(input()) + for i in range(n + 1): + father.append(i) + # 尋找冗余邊 + result = None + for i in range(n): + s, t = map(int, input().split()) + if is_same(s, t): + result = str(s) + ' ' + str(t) + else: + join(s, t) + + # 輸出 + print(result) +``` + ### Go ### Rust From 5c67ef4acd04b228b2f24f32a89917d9abc478b0 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Tue, 24 Sep 2024 16:13:28 +0800 Subject: [PATCH 23/26] =?UTF-8?q?feat:=20109.=20=E5=86=97=E4=BD=99?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5II=E6=96=B0=E5=A2=9Epython=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0109.冗余连接II.md | 86 +++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/problems/kamacoder/0109.冗余连接II.md b/problems/kamacoder/0109.冗余连接II.md index bd707bf6..2bd4eac6 100644 --- a/problems/kamacoder/0109.冗余连接II.md +++ b/problems/kamacoder/0109.冗余连接II.md @@ -351,6 +351,92 @@ public class Main { ``` ### Python +```python +from collections import defaultdict + +father = list() + + +def find(u): + if u == father[u]: + return u + else: + father[u] = find(father[u]) + return father[u] + + +def is_same(u, v): + u = find(u) + v = find(v) + return u == v + + +def join(u, v): + u = find(u) + v = find(v) + if u != v: + father[u] = v + + +def is_tree_after_remove_edge(edges, edge, n): + # 初始化并查集 + global father + father = [i for i in range(n + 1)] + + for i in range(len(edges)): + if i == edge: + continue + s, t = edges[i] + if is_same(s, t): # 成環,即不是有向樹 + return False + else: # 將s,t放入集合中 + join(s, t) + return True + + +def get_remove_edge(edges): + # 初始化并查集 + global father + father = [i for i in range(n + 1)] + + for s, t in edges: + if is_same(s, t): + print(s, t) + return + else: + join(s, t) + + +if __name__ == "__main__": + # 輸入 + n = int(input()) + edges = list() + in_degree = defaultdict(int) + + for i in range(n): + s, t = map(int, input().split()) + in_degree[t] += 1 + edges.append([s, t]) + + # 尋找入度為2的邊,並紀錄其下標(index) + vec = list() + for i in range(n - 1, -1, -1): + if in_degree[edges[i][1]] == 2: + vec.append(i) + + # 輸出 + if len(vec) > 0: + # 情況一:刪除輸出順序靠後的邊 + if is_tree_after_remove_edge(edges, vec[0], n): + print(edges[vec[0]][0], edges[vec[0]][1]) + # 情況二:只能刪除特定的邊 + else: + print(edges[vec[1]][0], edges[vec[1]][1]) + else: + # 情況三: 原圖有環 + get_remove_edge(edges) +``` + ### Go ### Rust From 183fe44ae0d0569f39ab525b57877d844e9d3823 Mon Sep 17 00:00:00 2001 From: Zhihan Li <54661071+zhihali@users.noreply.github.com> Date: Tue, 24 Sep 2024 16:09:20 +0100 Subject: [PATCH 24/26] =?UTF-8?q?Update=200134.=E5=8A=A0=E6=B2=B9=E7=AB=99?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index 7ac9f0f9..5cf50b3e 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -158,7 +158,7 @@ i从0开始累加rest[i],和记为curSum,一旦curSum小于零,说明[0, i 如果 curSum<0 说明 区间和1 + 区间和2 < 0, 那么 假设从上图中的位置开始计数curSum不会小于0的话,就是 区间和2>0。 -区间和1 + 区间和2 < 0 同时 区间和2>0,只能说明区间和1 < 0, 那么就会从假设的箭头初就开始从新选择其实位置了。 +区间和1 + 区间和2 < 0 同时 区间和2>0,只能说明区间和1 < 0, 那么就会从假设的箭头初就开始从新选择起始位置了。 **那么局部最优:当前累加rest[i]的和curSum一旦小于0,起始位置至少要是i+1,因为从i之前开始一定不行。全局最优:找到可以跑一圈的起始位置**。 From 779ff9dd08a4b18d0aa8e077fcdab5e821662c08 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Wed, 25 Sep 2024 12:35:34 +0800 Subject: [PATCH 25/26] =?UTF-8?q?feat:=2053.=20=E5=AF=BB=E5=AE=9D=E6=96=B0?= =?UTF-8?q?=E5=A2=9Ejs=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0053.寻宝-prim.md | 49 ++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/kamacoder/0053.寻宝-prim.md b/problems/kamacoder/0053.寻宝-prim.md index c71624b5..a8dad4cb 100644 --- a/problems/kamacoder/0053.寻宝-prim.md +++ b/problems/kamacoder/0053.寻宝-prim.md @@ -693,6 +693,55 @@ if __name__ == "__main__": ### Rust ### Javascript +```js +function prim(v, edges) { + const grid = Array.from({ length: v + 1 }, () => new Array(v + 1).fill(10001)); // Fixed grid initialization + const minDist = new Array(v + 1).fill(10001) + const isInTree = new Array(v + 1).fill(false) + // 建構鄰接矩陣 + for(const [v1, v2, w] of edges) { + grid[v1][v2] = w + grid[v2][v1] = w + } + // prim 演算法 + for (let i = 1 ; i < v ; i++) { + let cur = -1 + let tempMinDist = Number.MAX_VALUE + // 1. 尋找距離生成樹最近的節點 + for (let j = 1 ; j < v + 1 ; j++) { + if (!isInTree[j] && minDist[j] < tempMinDist) { + tempMinDist = minDist[j] + cur = j + } + } + // 2. 將節點放入生成樹 + isInTree[cur] = true + // 3. 更新非生成樹節點與生成樹的最短距離 + for (let j = 1 ; j < v + 1 ; j++) { + if (!isInTree[j] && grid[cur][j] < minDist[j]) { + minDist[j] = grid[cur][j] + } + } + } + console.log(minDist.slice(2).reduce((acc, cur) => acc + cur, 0)) +} + + +async function main() { + const rl = require('readline').createInterface({ input: process.stdin }) + const iter = rl[Symbol.asyncIterator]() + const readline = async () => (await iter.next()).value + const [v, e] = (await readline()).split(" ").map(Number) + const edges = [] + for (let i = 0 ; i < e ; i++) { + edges.push((await readline()).split(" ").map(Number)) + } + prim(v, edges) +} + + +main() +``` ### TypeScript From 9e66f2232363c66f1c466329b518fc2d8c6525c5 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Wed, 25 Sep 2024 14:57:21 +0800 Subject: [PATCH 26/26] =?UTF-8?q?feat:=2053.=20=E5=AF=BB=E5=AE=9D=E6=96=B0?= =?UTF-8?q?=E5=A2=9Ekruskal=20js=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0053.寻宝-Kruskal.md | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/problems/kamacoder/0053.寻宝-Kruskal.md b/problems/kamacoder/0053.寻宝-Kruskal.md index cb24fd17..6a227985 100644 --- a/problems/kamacoder/0053.寻宝-Kruskal.md +++ b/problems/kamacoder/0053.寻宝-Kruskal.md @@ -549,6 +549,62 @@ if __name__ == "__main__": ### Javascript +```js +function kruskal(v, edges) { + const father = Array.from({ length: v + 1 }, (_, i) => i) + + function find(u){ + if (u === father[u]) { + return u + } else { + father[u] = find(father[u]) + return father[u] + } + + } + + function isSame(u, v) { + let s = find(u) + let t = find(v) + return s === t + } + + function join(u, v) { + let s = find(u) + let t = find(v) + if (s !== t) { + father[s] = t + } + } + + edges.sort((a, b) => a[2] - b[2]) + let result = 0 + for (const [v1, v2, w] of edges) { + if (!isSame(v1, v2)) { + result += w + join(v1 ,v2) + } + } + console.log(result) +} + + +async function main() { + const rl = require('readline').createInterface({ input: process.stdin }) + const iter = rl[Symbol.asyncIterator]() + const readline = async () => (await iter.next()).value + const [v, e] = (await readline()).split(" ").map(Number) + const edges = [] + for (let i = 0 ; i < e ; i++) { + edges.push((await readline()).split(" ").map(Number)) + } + kruskal(v, edges) +} + + +main() +``` + ### TypeScript ### PhP