From 0d0465d54b80044ec1aadc1fe612dd9474231675 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 19:40:55 +0800 Subject: [PATCH 01/16] feat: update solutions to lc problem: No.1034 No.1034.Coloring A Border --- .../1034.Coloring A Border/README.md | 120 ++++++++++-------- .../1034.Coloring A Border/README_EN.md | 114 +++++++++-------- .../1034.Coloring A Border/Solution.cpp | 48 +++---- .../1034.Coloring A Border/Solution.go | 20 ++- .../1034.Coloring A Border/Solution.java | 28 ++-- .../1034.Coloring A Border/Solution.py | 18 ++- 6 files changed, 182 insertions(+), 166 deletions(-) diff --git a/solution/1000-1099/1034.Coloring A Border/README.md b/solution/1000-1099/1034.Coloring A Border/README.md index cbd0d850653fe..25cb30bb0a7f6 100644 --- a/solution/1000-1099/1034.Coloring A Border/README.md +++ b/solution/1000-1099/1034.Coloring A Border/README.md @@ -63,7 +63,11 @@ -深度优先搜索,利用 vis 记录访问过的位置。 +**方法一:DFS** + +我们从位置 $(row, col)$ 出发,利用 DFS 搜索所有颜色为 $grid[row][col]$ 的网格块,如果该网格块的某个相邻位置的颜色不为 $grid[row][col]$,或者该网格块在网格的边界上,则将该网格块的颜色改为 $color$。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是网格的行数和列数。 @@ -76,24 +80,22 @@ class Solution: def colorBorder( self, grid: List[List[int]], row: int, col: int, color: int ) -> List[List[int]]: - m, n = len(grid), len(grid[0]) - vis = [[False] * n for _ in range(m)] - - def dfs(i, j, color): + def dfs(i: int, j: int, c: int) -> None: vis[i][j] = True - old_color = grid[i][j] - for a, b in [[-1, 0], [1, 0], [0, -1], [0, 1]]: - x, y = a + i, b + j + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = i + a, j + b if 0 <= x < m and 0 <= y < n: if not vis[x][y]: - if grid[x][y] == old_color: - dfs(x, y, color) + if grid[x][y] == c: + dfs(x, y, c) else: grid[i][j] = color else: grid[i][j] = color - dfs(row, col, color) + m, n = len(grid), len(grid[0]) + vis = [[False] * n for _ in range(m)] + dfs(row, col, grid[row][col]) return grid ``` @@ -103,23 +105,31 @@ class Solution: ```java class Solution { - private int[] dirs = new int[] {-1, 0, 1, 0, -1}; - - public int[][] colorBorder(int[][] grid, int r0, int c0, int color) { - boolean[][] vis = new boolean[grid.length][grid[0].length]; - dfs(grid, r0, c0, color, vis); + private int[][] grid; + private int color; + private int m; + private int n; + private boolean[][] vis; + + public int[][] colorBorder(int[][] grid, int row, int col, int color) { + this.grid = grid; + this.color = color; + m = grid.length; + n = grid[0].length; + vis = new boolean[m][n]; + dfs(row, col, grid[row][col]); return grid; } - private void dfs(int[][] grid, int i, int j, int color, boolean[][] vis) { + private void dfs(int i, int j, int c) { vis[i][j] = true; - int oldColor = grid[i][j]; + int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length) { + if (x >= 0 && x < m && y >= 0 && y < n) { if (!vis[x][y]) { - if (grid[x][y] == oldColor) { - dfs(grid, x, y, color, vis); + if (grid[x][y] == c) { + dfs(x, y, c); } else { grid[i][j] = color; } @@ -137,32 +147,32 @@ class Solution { ```cpp class Solution { public: - int m, n; - vector> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - vector> colorBorder(vector>& grid, int row, int col, int color) { - m = grid.size(); - n = grid[0].size(); - vector> vis(m, vector(n, false)); - dfs(row, col, color, grid, vis); - return grid; - } - - void dfs(int i, int j, int color, vector>& grid, vector>& vis) { - vis[i][j] = true; - int oldColor = grid[i][j]; - for (auto& dir : dirs) { - int x = i + dir[0], y = j + dir[1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - if (!vis[x][y]) { - if (grid[x][y] == oldColor) - dfs(x, y, color, grid, vis); - else - grid[i][j] = color; + int m = grid.size(); + int n = grid[0].size(); + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j, int c) { + vis[i][j] = true; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + if (!vis[x][y]) { + if (grid[x][y] == c) { + dfs(x, y, c); + } else { + grid[i][j] = color; + } + } + } else { + grid[i][j] = color; } - } else - grid[i][j] = color; - } + } + }; + dfs(row, col, grid[row][col]); + return grid; } }; ``` @@ -173,21 +183,19 @@ public: func colorBorder(grid [][]int, row int, col int, color int) [][]int { m, n := len(grid), len(grid[0]) vis := make([][]bool, m) - for i := 0; i < m; i++ { + for i := range vis { vis[i] = make([]bool, n) } - dirs := [4][2]int{{0, -1}, {0, 1}, {1, 0}, {-1, 0}} - - var dfs func(i, j, color int) - dfs = func(i, j, color int) { + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(int, int, int) + dfs = func(i, j, c int) { vis[i][j] = true - oldColor := grid[i][j] - for _, dir := range dirs { - x, y := i+dir[0], j+dir[1] + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n { if !vis[x][y] { - if grid[x][y] == oldColor { - dfs(x, y, color) + if grid[x][y] == c { + dfs(x, y, c) } else { grid[i][j] = color } @@ -197,7 +205,7 @@ func colorBorder(grid [][]int, row int, col int, color int) [][]int { } } } - dfs(row, col, color) + dfs(row, col, grid[row][col]) return grid } ``` diff --git a/solution/1000-1099/1034.Coloring A Border/README_EN.md b/solution/1000-1099/1034.Coloring A Border/README_EN.md index c71502bb10c4f..a1edb629d8f3e 100644 --- a/solution/1000-1099/1034.Coloring A Border/README_EN.md +++ b/solution/1000-1099/1034.Coloring A Border/README_EN.md @@ -48,24 +48,22 @@ class Solution: def colorBorder( self, grid: List[List[int]], row: int, col: int, color: int ) -> List[List[int]]: - m, n = len(grid), len(grid[0]) - vis = [[False] * n for _ in range(m)] - - def dfs(i, j, color): + def dfs(i: int, j: int, c: int) -> None: vis[i][j] = True - old_color = grid[i][j] - for a, b in [[-1, 0], [1, 0], [0, -1], [0, 1]]: - x, y = a + i, b + j + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = i + a, j + b if 0 <= x < m and 0 <= y < n: if not vis[x][y]: - if grid[x][y] == old_color: - dfs(x, y, color) + if grid[x][y] == c: + dfs(x, y, c) else: grid[i][j] = color else: grid[i][j] = color - dfs(row, col, color) + m, n = len(grid), len(grid[0]) + vis = [[False] * n for _ in range(m)] + dfs(row, col, grid[row][col]) return grid ``` @@ -73,23 +71,31 @@ class Solution: ```java class Solution { - private int[] dirs = new int[] {-1, 0, 1, 0, -1}; - - public int[][] colorBorder(int[][] grid, int r0, int c0, int color) { - boolean[][] vis = new boolean[grid.length][grid[0].length]; - dfs(grid, r0, c0, color, vis); + private int[][] grid; + private int color; + private int m; + private int n; + private boolean[][] vis; + + public int[][] colorBorder(int[][] grid, int row, int col, int color) { + this.grid = grid; + this.color = color; + m = grid.length; + n = grid[0].length; + vis = new boolean[m][n]; + dfs(row, col, grid[row][col]); return grid; } - private void dfs(int[][] grid, int i, int j, int color, boolean[][] vis) { + private void dfs(int i, int j, int c) { vis[i][j] = true; - int oldColor = grid[i][j]; + int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length) { + if (x >= 0 && x < m && y >= 0 && y < n) { if (!vis[x][y]) { - if (grid[x][y] == oldColor) { - dfs(grid, x, y, color, vis); + if (grid[x][y] == c) { + dfs(x, y, c); } else { grid[i][j] = color; } @@ -107,32 +113,32 @@ class Solution { ```cpp class Solution { public: - int m, n; - vector> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - vector> colorBorder(vector>& grid, int row, int col, int color) { - m = grid.size(); - n = grid[0].size(); - vector> vis(m, vector(n, false)); - dfs(row, col, color, grid, vis); - return grid; - } - - void dfs(int i, int j, int color, vector>& grid, vector>& vis) { - vis[i][j] = true; - int oldColor = grid[i][j]; - for (auto& dir : dirs) { - int x = i + dir[0], y = j + dir[1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - if (!vis[x][y]) { - if (grid[x][y] == oldColor) - dfs(x, y, color, grid, vis); - else - grid[i][j] = color; + int m = grid.size(); + int n = grid[0].size(); + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j, int c) { + vis[i][j] = true; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + if (!vis[x][y]) { + if (grid[x][y] == c) { + dfs(x, y, c); + } else { + grid[i][j] = color; + } + } + } else { + grid[i][j] = color; } - } else - grid[i][j] = color; - } + } + }; + dfs(row, col, grid[row][col]); + return grid; } }; ``` @@ -143,21 +149,19 @@ public: func colorBorder(grid [][]int, row int, col int, color int) [][]int { m, n := len(grid), len(grid[0]) vis := make([][]bool, m) - for i := 0; i < m; i++ { + for i := range vis { vis[i] = make([]bool, n) } - dirs := [4][2]int{{0, -1}, {0, 1}, {1, 0}, {-1, 0}} - - var dfs func(i, j, color int) - dfs = func(i, j, color int) { + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(int, int, int) + dfs = func(i, j, c int) { vis[i][j] = true - oldColor := grid[i][j] - for _, dir := range dirs { - x, y := i+dir[0], j+dir[1] + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n { if !vis[x][y] { - if grid[x][y] == oldColor { - dfs(x, y, color) + if grid[x][y] == c { + dfs(x, y, c) } else { grid[i][j] = color } @@ -167,7 +171,7 @@ func colorBorder(grid [][]int, row int, col int, color int) [][]int { } } } - dfs(row, col, color) + dfs(row, col, grid[row][col]) return grid } ``` diff --git a/solution/1000-1099/1034.Coloring A Border/Solution.cpp b/solution/1000-1099/1034.Coloring A Border/Solution.cpp index b0c97af31ff92..c00caa1200646 100644 --- a/solution/1000-1099/1034.Coloring A Border/Solution.cpp +++ b/solution/1000-1099/1034.Coloring A Border/Solution.cpp @@ -1,30 +1,30 @@ class Solution { public: - int m, n; - vector> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - vector> colorBorder(vector>& grid, int row, int col, int color) { - m = grid.size(); - n = grid[0].size(); - vector> vis(m, vector(n, false)); - dfs(row, col, color, grid, vis); - return grid; - } - - void dfs(int i, int j, int color, vector>& grid, vector>& vis) { - vis[i][j] = true; - int oldColor = grid[i][j]; - for (auto& dir : dirs) { - int x = i + dir[0], y = j + dir[1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - if (!vis[x][y]) { - if (grid[x][y] == oldColor) - dfs(x, y, color, grid, vis); - else - grid[i][j] = color; + int m = grid.size(); + int n = grid[0].size(); + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j, int c) { + vis[i][j] = true; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + if (!vis[x][y]) { + if (grid[x][y] == c) { + dfs(x, y, c); + } else { + grid[i][j] = color; + } + } + } else { + grid[i][j] = color; } - } else - grid[i][j] = color; - } + } + }; + dfs(row, col, grid[row][col]); + return grid; } }; \ No newline at end of file diff --git a/solution/1000-1099/1034.Coloring A Border/Solution.go b/solution/1000-1099/1034.Coloring A Border/Solution.go index d9a0e05707db6..d67c5be5eda99 100644 --- a/solution/1000-1099/1034.Coloring A Border/Solution.go +++ b/solution/1000-1099/1034.Coloring A Border/Solution.go @@ -1,21 +1,19 @@ func colorBorder(grid [][]int, row int, col int, color int) [][]int { m, n := len(grid), len(grid[0]) vis := make([][]bool, m) - for i := 0; i < m; i++ { + for i := range vis { vis[i] = make([]bool, n) } - dirs := [4][2]int{{0, -1}, {0, 1}, {1, 0}, {-1, 0}} - - var dfs func(i, j, color int) - dfs = func(i, j, color int) { + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(int, int, int) + dfs = func(i, j, c int) { vis[i][j] = true - oldColor := grid[i][j] - for _, dir := range dirs { - x, y := i+dir[0], j+dir[1] + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n { if !vis[x][y] { - if grid[x][y] == oldColor { - dfs(x, y, color) + if grid[x][y] == c { + dfs(x, y, c) } else { grid[i][j] = color } @@ -25,6 +23,6 @@ func colorBorder(grid [][]int, row int, col int, color int) [][]int { } } } - dfs(row, col, color) + dfs(row, col, grid[row][col]) return grid } \ No newline at end of file diff --git a/solution/1000-1099/1034.Coloring A Border/Solution.java b/solution/1000-1099/1034.Coloring A Border/Solution.java index 9c757e75eb132..d4e68abb0df66 100644 --- a/solution/1000-1099/1034.Coloring A Border/Solution.java +++ b/solution/1000-1099/1034.Coloring A Border/Solution.java @@ -1,21 +1,29 @@ class Solution { - private int[] dirs = new int[] {-1, 0, 1, 0, -1}; + private int[][] grid; + private int color; + private int m; + private int n; + private boolean[][] vis; - public int[][] colorBorder(int[][] grid, int r0, int c0, int color) { - boolean[][] vis = new boolean[grid.length][grid[0].length]; - dfs(grid, r0, c0, color, vis); + public int[][] colorBorder(int[][] grid, int row, int col, int color) { + this.grid = grid; + this.color = color; + m = grid.length; + n = grid[0].length; + vis = new boolean[m][n]; + dfs(row, col, grid[row][col]); return grid; } - private void dfs(int[][] grid, int i, int j, int color, boolean[][] vis) { + private void dfs(int i, int j, int c) { vis[i][j] = true; - int oldColor = grid[i][j]; + int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length) { + if (x >= 0 && x < m && y >= 0 && y < n) { if (!vis[x][y]) { - if (grid[x][y] == oldColor) { - dfs(grid, x, y, color, vis); + if (grid[x][y] == c) { + dfs(x, y, c); } else { grid[i][j] = color; } @@ -25,4 +33,4 @@ private void dfs(int[][] grid, int i, int j, int color, boolean[][] vis) { } } } -} +} \ No newline at end of file diff --git a/solution/1000-1099/1034.Coloring A Border/Solution.py b/solution/1000-1099/1034.Coloring A Border/Solution.py index 17251cc610719..575aaea638258 100644 --- a/solution/1000-1099/1034.Coloring A Border/Solution.py +++ b/solution/1000-1099/1034.Coloring A Border/Solution.py @@ -2,22 +2,20 @@ class Solution: def colorBorder( self, grid: List[List[int]], row: int, col: int, color: int ) -> List[List[int]]: - m, n = len(grid), len(grid[0]) - vis = [[False] * n for _ in range(m)] - - def dfs(i, j, color): + def dfs(i: int, j: int, c: int) -> None: vis[i][j] = True - old_color = grid[i][j] - for a, b in [[-1, 0], [1, 0], [0, -1], [0, 1]]: - x, y = a + i, b + j + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = i + a, j + b if 0 <= x < m and 0 <= y < n: if not vis[x][y]: - if grid[x][y] == old_color: - dfs(x, y, color) + if grid[x][y] == c: + dfs(x, y, c) else: grid[i][j] = color else: grid[i][j] = color - dfs(row, col, color) + m, n = len(grid), len(grid[0]) + vis = [[False] * n for _ in range(m)] + dfs(row, col, grid[row][col]) return grid From 8d2a07b934c57015296f9a42526f3b7c438cb7a2 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 20:10:08 +0800 Subject: [PATCH 02/16] feat: update solutions to lc problem: No.1033 No.1033.Moving Stones Until Consecutive --- .../README.md | 71 ++++++++++--------- .../README_EN.md | 56 ++++++++------- .../Solution.cpp | 12 ++-- .../Solution.go | 18 ++--- .../Solution.java | 11 +-- .../Solution.py | 17 ++--- 6 files changed, 98 insertions(+), 87 deletions(-) diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md index 39c76a5a08ac2..61fb825847249 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md @@ -47,12 +47,17 @@ -**方法一:脑筋急转弯** +**方法一:分类讨论** -- 若 $3$ 个数已经相邻,则不用移动,直接返回结果 $[0,0]$; -- 若 $3$ 个数中存在两数之差小于 $3$,最小只需移动 $1$ 次; -- 其他情况最小只需移动 $2$ 次; -- 两边逐个往中间靠,就是最大移动次数 $c - a - 2$。 +我们先将 $a, b, c$ 排序,记为 $x, y, z$,即 $x \lt y \lt z$。 + +接下来分情况讨论: + +1. 如果 $z - x \leq 2$,说明 $3$ 个数已经相邻,不用移动,结果为 $[0, 0]$; +1. 否则,如果 $y - x \lt 3$,或者 $z - y \lt 3$,说明有两个数只间隔一个位置,我们只需要把另一个数移动到这两个数的中间,最小移动次数为 $1$;其他情况,最小移动次数为 $2$; +1. 最大移动次数就是两边的数字逐个往中间靠,最多移动 $z - x - 2$ 次。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 @@ -63,16 +68,13 @@ ```python class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: - a, b, c = sorted([a, b, c]) - ans = [0] * 2 - if c - a == 2: - return ans - if b - a < 3 or c - b < 3: - ans[0] = 1 - else: - ans[0] = 2 - ans[1] = c - a - 2 - return ans + x, z = min(a, b, c), max(a, b, c) + y = a + b + c - x - z + mi = mx = 0 + if z - x > 2: + mi = 1 if y - x < 3 or z - y < 3 else 2 + mx = z - x - 2 + return [mi, mx] ``` ### **Java** @@ -85,9 +87,12 @@ class Solution { int x = Math.min(a, Math.min(b, c)); int z = Math.max(a, Math.max(b, c)); int y = a + b + c - x - z; - int max = z - x - 2; - int min = y - x == 1 && z - y == 1 ? 0 : y - x <= 2 || z - y <= 2 ? 1 : 2; - return new int[] {min, max}; + int mi = 0, mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } + return new int[]{mi, mx}; } } ``` @@ -98,12 +103,14 @@ class Solution { class Solution { public: vector numMovesStones(int a, int b, int c) { - int x = min(min(a, b), c); - int z = max(max(a, b), c); + int x = min({a, b, c}); + int z = max({a, b, c}); int y = a + b + c - x - z; - if (z - x == 2) return {0, 0}; - int mx = z - x - 2; - int mi = y - x < 3 || z - y < 3 ? 1 : 2; + int mi = 0, mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } return {mi, mx}; } }; @@ -113,16 +120,16 @@ public: ```go func numMovesStones(a int, b int, c int) []int { - x := min(min(a, b), c) - z := max(max(a, b), c) + x := min(a, min(b, c)) + z := max(a, max(b, c)) y := a + b + c - x - z - if z-x == 2 { - return []int{0, 0} - } - mx := z - x - 2 - mi := 2 - if y-x < 3 || z-y < 3 { - mi = 1 + mi, mx := 0, 0 + if z-x > 2 { + mi = 2 + if y-x < 3 || z-y < 3 { + mi = 1 + } + mx = z - x - 2 } return []int{mi, mx} } diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md index 6da72c7974d82..020d2b2c04e48 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md @@ -59,16 +59,13 @@ ```python class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: - a, b, c = sorted([a, b, c]) - ans = [0] * 2 - if c - a == 2: - return ans - if b - a < 3 or c - b < 3: - ans[0] = 1 - else: - ans[0] = 2 - ans[1] = c - a - 2 - return ans + x, z = min(a, b, c), max(a, b, c) + y = a + b + c - x - z + mi = mx = 0 + if z - x > 2: + mi = 1 if y - x < 3 or z - y < 3 else 2 + mx = z - x - 2 + return [mi, mx] ``` ### **Java** @@ -79,9 +76,12 @@ class Solution { int x = Math.min(a, Math.min(b, c)); int z = Math.max(a, Math.max(b, c)); int y = a + b + c - x - z; - int max = z - x - 2; - int min = y - x == 1 && z - y == 1 ? 0 : y - x <= 2 || z - y <= 2 ? 1 : 2; - return new int[] {min, max}; + int mi = 0, mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } + return new int[]{mi, mx}; } } ``` @@ -92,12 +92,14 @@ class Solution { class Solution { public: vector numMovesStones(int a, int b, int c) { - int x = min(min(a, b), c); - int z = max(max(a, b), c); + int x = min({a, b, c}); + int z = max({a, b, c}); int y = a + b + c - x - z; - if (z - x == 2) return {0, 0}; - int mx = z - x - 2; - int mi = y - x < 3 || z - y < 3 ? 1 : 2; + int mi = 0, mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } return {mi, mx}; } }; @@ -107,16 +109,16 @@ public: ```go func numMovesStones(a int, b int, c int) []int { - x := min(min(a, b), c) - z := max(max(a, b), c) + x := min(a, min(b, c)) + z := max(a, max(b, c)) y := a + b + c - x - z - if z-x == 2 { - return []int{0, 0} - } - mx := z - x - 2 - mi := 2 - if y-x < 3 || z-y < 3 { - mi = 1 + mi, mx := 0, 0 + if z-x > 2 { + mi = 2 + if y-x < 3 || z-y < 3 { + mi = 1 + } + mx = z - x - 2 } return []int{mi, mx} } diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.cpp b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.cpp index cf9af0d9ffc3b..31feb01084a01 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.cpp +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.cpp @@ -1,12 +1,14 @@ class Solution { public: vector numMovesStones(int a, int b, int c) { - int x = min(min(a, b), c); - int z = max(max(a, b), c); + int x = min({a, b, c}); + int z = max({a, b, c}); int y = a + b + c - x - z; - if (z - x == 2) return {0, 0}; - int mx = z - x - 2; - int mi = y - x < 3 || z - y < 3 ? 1 : 2; + int mi = 0, mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } return {mi, mx}; } }; \ No newline at end of file diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.go b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.go index 8976dc70a955b..4ef2845c143d4 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.go +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.go @@ -1,14 +1,14 @@ func numMovesStones(a int, b int, c int) []int { - x := min(min(a, b), c) - z := max(max(a, b), c) + x := min(a, min(b, c)) + z := max(a, max(b, c)) y := a + b + c - x - z - if z-x == 2 { - return []int{0, 0} - } - mx := z - x - 2 - mi := 2 - if y-x < 3 || z-y < 3 { - mi = 1 + mi, mx := 0, 0 + if z-x > 2 { + mi = 2 + if y-x < 3 || z-y < 3 { + mi = 1 + } + mx = z - x - 2 } return []int{mi, mx} } diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java index fcc3df99ad021..5f87b1e36a902 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java @@ -3,8 +3,11 @@ public int[] numMovesStones(int a, int b, int c) { int x = Math.min(a, Math.min(b, c)); int z = Math.max(a, Math.max(b, c)); int y = a + b + c - x - z; - int max = z - x - 2; - int min = y - x == 1 && z - y == 1 ? 0 : y - x <= 2 || z - y <= 2 ? 1 : 2; - return new int[] {min, max}; + int mi = 0, mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } + return new int[]{mi, mx}; } -} +} \ No newline at end of file diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.py b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.py index 2a47bcff6546d..03794bdd771ab 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.py +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.py @@ -1,12 +1,9 @@ class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: - a, b, c = sorted([a, b, c]) - ans = [0] * 2 - if c - a == 2: - return ans - if b - a < 3 or c - b < 3: - ans[0] = 1 - else: - ans[0] = 2 - ans[1] = c - a - 2 - return ans + x, z = min(a, b, c), max(a, b, c) + y = a + b + c - x - z + mi = mx = 0 + if z - x > 2: + mi = 1 if y - x < 3 or z - y < 3 else 2 + mx = z - x - 2 + return [mi, mx] From 2c5e36c84a01e52de73845657cab13019d692adb Mon Sep 17 00:00:00 2001 From: Qiu <99040799+Qiu-IT@users.noreply.github.com> Date: Thu, 23 Mar 2023 13:32:08 +0100 Subject: [PATCH 03/16] feat: add php solution to lc problem: No.0263 (#945) --- solution/0200-0299/0263.Ugly Number/README.md | 20 +++++++++++++++++++ .../0200-0299/0263.Ugly Number/README_EN.md | 20 +++++++++++++++++++ .../0200-0299/0263.Ugly Number/Solution.php | 15 ++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 solution/0200-0299/0263.Ugly Number/Solution.php diff --git a/solution/0200-0299/0263.Ugly Number/README.md b/solution/0200-0299/0263.Ugly Number/README.md index e9c91f66d8c44..caa39b1b96481 100644 --- a/solution/0200-0299/0263.Ugly Number/README.md +++ b/solution/0200-0299/0263.Ugly Number/README.md @@ -150,6 +150,26 @@ func isUgly(n int) bool { } ``` +### **PHP** + +```php +class Solution { + /** + * @param Integer $n + * @return Boolean + */ + function isUgly($n) { + while ($n) { + if ($n % 2 == 0) $n = $n / 2; + else if ($n % 3 == 0) $n = $n / 3; + else if ($n % 5 == 0) $n = $n / 5; + else break; + } + return $n == 1; + } +} +``` + ### **...** ``` diff --git a/solution/0200-0299/0263.Ugly Number/README_EN.md b/solution/0200-0299/0263.Ugly Number/README_EN.md index b0b1883155621..a5ac733c048e2 100644 --- a/solution/0200-0299/0263.Ugly Number/README_EN.md +++ b/solution/0200-0299/0263.Ugly Number/README_EN.md @@ -136,6 +136,26 @@ func isUgly(n int) bool { } ``` +### **PHP** + +```php +class Solution { + /** + * @param Integer $n + * @return Boolean + */ + function isUgly($n) { + while ($n) { + if ($n % 2 == 0) $n = $n / 2; + else if ($n % 3 == 0) $n = $n / 3; + else if ($n % 5 == 0) $n = $n / 5; + else break; + } + return $n == 1; + } +} +``` + ### **...** ``` diff --git a/solution/0200-0299/0263.Ugly Number/Solution.php b/solution/0200-0299/0263.Ugly Number/Solution.php new file mode 100644 index 0000000000000..62b9fb39818dc --- /dev/null +++ b/solution/0200-0299/0263.Ugly Number/Solution.php @@ -0,0 +1,15 @@ +class Solution { + /** + * @param Integer $n + * @return Boolean + */ + function isUgly($n) { + while ($n) { + if ($n % 2 == 0) $n = $n / 2; + else if ($n % 3 == 0) $n = $n / 3; + else if ($n % 5 == 0) $n = $n / 5; + else break; + } + return $n == 1; + } +} \ No newline at end of file From 107746a055a0a5f9b82103801569d3ee433c656e Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 20:33:11 +0800 Subject: [PATCH 04/16] feat: update solutions to lc problem: No.1030 No.1030.Matrix Cells in Distance Order --- .../README.md | 62 ++++++++++--------- .../README_EN.md | 56 +++++++++-------- .../Solution.cpp | 22 ++++--- .../Solution.go | 9 ++- .../Solution.java | 13 ++-- .../Solution.py | 12 ++-- 6 files changed, 91 insertions(+), 83 deletions(-) diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md b/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md index 8daa4aa706df8..c0daadcdf19a8 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md @@ -56,9 +56,11 @@ **方法一:BFS** -从坐标点 `(rCenter, cCenter)` 往上下左右 4 个方向进行搜索,将搜索到的坐标点添加到结果列表 ans 中,并记录访问过的节点,防止重复搜索。 +我们定义一个队列 $q$,初始时将坐标点 $(rCenter, cCenter)$ 入队,用一个二维布尔数组 $vis$ 记录已经访问过的点,初始时 $vis[rCenter][cCenter]$ 为 $true$。 -搜索结束,返回结果列表 ans 即可。 +接下来,我们不断地从队列中取出一个点,将其加入答案数组,然后将其上下左右四个相邻点加入队列,注意要判断这些点是否已经访问过,如果没有访问过,就将其标记为已访问,并将其加入队列。一直重复这个过程,直到队列为空,此时答案数组中的点就是按照距离从小到大的顺序排列的。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 @@ -71,19 +73,19 @@ class Solution: def allCellsDistOrder( self, rows: int, cols: int, rCenter: int, cCenter: int ) -> List[List[int]]: - q = deque([(rCenter, cCenter)]) + q = deque([[rCenter, cCenter]]) vis = [[False] * cols for _ in range(rows)] vis[rCenter][cCenter] = True ans = [] while q: for _ in range(len(q)): - i, j = q.popleft() - ans.append([i, j]) - for a, b in [[1, 0], [-1, 0], [0, 1], [0, -1]]: - x, y = i + a, j + b + p = q.popleft() + ans.append(p) + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = p[0] + a, p[1] + b if 0 <= x < rows and 0 <= y < cols and not vis[x][y]: - q.append((x, y)) vis[x][y] = True + q.append([x, y]) return ans ``` @@ -92,25 +94,26 @@ class Solution: ```java +import java.util.Deque; + class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { Deque q = new ArrayDeque<>(); - q.offer(new int[] {rCenter, cCenter}); + q.offer(new int[]{rCenter, cCenter}); boolean[][] vis = new boolean[rows][cols]; vis[rCenter][cCenter] = true; int[][] ans = new int[rows * cols][2]; - int idx = 0; int[] dirs = {-1, 0, 1, 0, -1}; + int idx = 0; while (!q.isEmpty()) { for (int n = q.size(); n > 0; --n) { - int[] p = q.poll(); + var p = q.poll(); ans[idx++] = p; for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k]; - int y = p[1] + dirs[k + 1]; + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - q.offer(new int[] {x, y}); vis[x][y] = true; + q.offer(new int[]{x, y}); } } } @@ -126,22 +129,24 @@ class Solution { class Solution { public: vector> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { - queue> q; - q.push({rCenter, cCenter}); - vector> vis(rows, vector(cols)); - vis[rCenter][cCenter] = true; + queue> q; + q.emplace(rCenter, cCenter); vector> ans; - vector dirs = {-1, 0, 1, 0, -1}; + bool vis[rows][cols]; + memset(vis, false, sizeof(vis)); + vis[rCenter][cCenter] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; while (!q.empty()) { - for (int n = q.size(); n > 0; --n) { - auto p = q.front(); + for (int n = q.size(); n; --n) { + auto [i, j] = q.front(); q.pop(); - ans.push_back(p); + ans.push_back({i, j}); for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + int x = i + dirs[k]; + int y = j + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - q.push({x, y}); vis[x][y] = true; + q.emplace(x, y); } } } @@ -154,15 +159,14 @@ public: ### **Go** ```go -func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { +func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]int) { q := [][]int{{rCenter, cCenter}} vis := make([][]bool, rows) for i := range vis { vis[i] = make([]bool, cols) } vis[rCenter][cCenter] = true - var ans [][]int - dirs := []int{-1, 0, 1, 0, -1} + dirs := [5]int{-1, 0, 1, 0, -1} for len(q) > 0 { for n := len(q); n > 0; n-- { p := q[0] @@ -171,13 +175,13 @@ func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { for k := 0; k < 4; k++ { x, y := p[0]+dirs[k], p[1]+dirs[k+1] if x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y] { - q = append(q, []int{x, y}) vis[x][y] = true + q = append(q, []int{x, y}) } } } } - return ans + return } ``` diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md b/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md index f76c8a8815a0a..00a4f3fdae8be 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md @@ -57,44 +57,45 @@ class Solution: def allCellsDistOrder( self, rows: int, cols: int, rCenter: int, cCenter: int ) -> List[List[int]]: - q = deque([(rCenter, cCenter)]) + q = deque([[rCenter, cCenter]]) vis = [[False] * cols for _ in range(rows)] vis[rCenter][cCenter] = True ans = [] while q: for _ in range(len(q)): - i, j = q.popleft() - ans.append([i, j]) - for a, b in [[1, 0], [-1, 0], [0, 1], [0, -1]]: - x, y = i + a, j + b + p = q.popleft() + ans.append(p) + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = p[0] + a, p[1] + b if 0 <= x < rows and 0 <= y < cols and not vis[x][y]: - q.append((x, y)) vis[x][y] = True + q.append([x, y]) return ans ``` ### **Java** ```java +import java.util.Deque; + class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { Deque q = new ArrayDeque<>(); - q.offer(new int[] {rCenter, cCenter}); + q.offer(new int[]{rCenter, cCenter}); boolean[][] vis = new boolean[rows][cols]; vis[rCenter][cCenter] = true; int[][] ans = new int[rows * cols][2]; - int idx = 0; int[] dirs = {-1, 0, 1, 0, -1}; + int idx = 0; while (!q.isEmpty()) { for (int n = q.size(); n > 0; --n) { - int[] p = q.poll(); + var p = q.poll(); ans[idx++] = p; for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k]; - int y = p[1] + dirs[k + 1]; + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - q.offer(new int[] {x, y}); vis[x][y] = true; + q.offer(new int[]{x, y}); } } } @@ -110,22 +111,24 @@ class Solution { class Solution { public: vector> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { - queue> q; - q.push({rCenter, cCenter}); - vector> vis(rows, vector(cols)); - vis[rCenter][cCenter] = true; + queue> q; + q.emplace(rCenter, cCenter); vector> ans; - vector dirs = {-1, 0, 1, 0, -1}; + bool vis[rows][cols]; + memset(vis, false, sizeof(vis)); + vis[rCenter][cCenter] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; while (!q.empty()) { - for (int n = q.size(); n > 0; --n) { - auto p = q.front(); + for (int n = q.size(); n; --n) { + auto [i, j] = q.front(); q.pop(); - ans.push_back(p); + ans.push_back({i, j}); for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + int x = i + dirs[k]; + int y = j + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - q.push({x, y}); vis[x][y] = true; + q.emplace(x, y); } } } @@ -138,15 +141,14 @@ public: ### **Go** ```go -func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { +func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]int) { q := [][]int{{rCenter, cCenter}} vis := make([][]bool, rows) for i := range vis { vis[i] = make([]bool, cols) } vis[rCenter][cCenter] = true - var ans [][]int - dirs := []int{-1, 0, 1, 0, -1} + dirs := [5]int{-1, 0, 1, 0, -1} for len(q) > 0 { for n := len(q); n > 0; n-- { p := q[0] @@ -155,13 +157,13 @@ func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { for k := 0; k < 4; k++ { x, y := p[0]+dirs[k], p[1]+dirs[k+1] if x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y] { - q = append(q, []int{x, y}) vis[x][y] = true + q = append(q, []int{x, y}) } } } } - return ans + return } ``` diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp index 515b7c28c228d..4046ec9a397d8 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.cpp @@ -1,22 +1,24 @@ class Solution { public: vector> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { - queue> q; - q.push({rCenter, cCenter}); - vector> vis(rows, vector(cols)); - vis[rCenter][cCenter] = true; + queue> q; + q.emplace(rCenter, cCenter); vector> ans; - vector dirs = {-1, 0, 1, 0, -1}; + bool vis[rows][cols]; + memset(vis, false, sizeof(vis)); + vis[rCenter][cCenter] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; while (!q.empty()) { - for (int n = q.size(); n > 0; --n) { - auto p = q.front(); + for (int n = q.size(); n; --n) { + auto [i, j] = q.front(); q.pop(); - ans.push_back(p); + ans.push_back({i, j}); for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; + int x = i + dirs[k]; + int y = j + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - q.push({x, y}); vis[x][y] = true; + q.emplace(x, y); } } } diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.go b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.go index f1aadd6a3b9e4..040f886679b94 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.go +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.go @@ -1,12 +1,11 @@ -func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { +func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]int) { q := [][]int{{rCenter, cCenter}} vis := make([][]bool, rows) for i := range vis { vis[i] = make([]bool, cols) } vis[rCenter][cCenter] = true - var ans [][]int - dirs := []int{-1, 0, 1, 0, -1} + dirs := [5]int{-1, 0, 1, 0, -1} for len(q) > 0 { for n := len(q); n > 0; n-- { p := q[0] @@ -15,11 +14,11 @@ func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { for k := 0; k < 4; k++ { x, y := p[0]+dirs[k], p[1]+dirs[k+1] if x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y] { - q = append(q, []int{x, y}) vis[x][y] = true + q = append(q, []int{x, y}) } } } } - return ans + return } \ No newline at end of file diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java index c5f26bde3b8b1..0b7cefe96c6f6 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java @@ -1,22 +1,23 @@ +import java.util.Deque; + class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { Deque q = new ArrayDeque<>(); - q.offer(new int[] {rCenter, cCenter}); + q.offer(new int[]{rCenter, cCenter}); boolean[][] vis = new boolean[rows][cols]; vis[rCenter][cCenter] = true; int[][] ans = new int[rows * cols][2]; - int idx = 0; int[] dirs = {-1, 0, 1, 0, -1}; + int idx = 0; while (!q.isEmpty()) { for (int n = q.size(); n > 0; --n) { - int[] p = q.poll(); + var p = q.poll(); ans[idx++] = p; for (int k = 0; k < 4; ++k) { - int x = p[0] + dirs[k]; - int y = p[1] + dirs[k + 1]; + int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { - q.offer(new int[] {x, y}); vis[x][y] = true; + q.offer(new int[]{x, y}); } } } diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py index f6f48704e015f..db138df35efaa 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.py @@ -2,17 +2,17 @@ class Solution: def allCellsDistOrder( self, rows: int, cols: int, rCenter: int, cCenter: int ) -> List[List[int]]: - q = deque([(rCenter, cCenter)]) + q = deque([[rCenter, cCenter]]) vis = [[False] * cols for _ in range(rows)] vis[rCenter][cCenter] = True ans = [] while q: for _ in range(len(q)): - i, j = q.popleft() - ans.append([i, j]) - for a, b in [[1, 0], [-1, 0], [0, 1], [0, -1]]: - x, y = i + a, j + b + p = q.popleft() + ans.append(p) + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = p[0] + a, p[1] + b if 0 <= x < rows and 0 <= y < cols and not vis[x][y]: - q.append((x, y)) vis[x][y] = True + q.append([x, y]) return ans From 5c4625566891be2c8b29c1a4ac289889f8a0c539 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 20:57:36 +0800 Subject: [PATCH 05/16] feat: add solutions to lc problem: No.1027 No.1027.Longest Arithmetic Subsequence --- .../README.md | 55 +++++++++++-------- .../README_EN.md | 47 ++++++++-------- .../Solution.cpp | 13 +++-- .../Solution.go | 14 ++--- .../Solution.java | 10 ++-- .../Solution.py | 10 ++-- 6 files changed, 80 insertions(+), 69 deletions(-) diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md index 117299114eeb5..6b7cbabe6a0fe 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md @@ -54,6 +54,14 @@ **方法一:动态规划** +我们定义 $f[i][j]$ 表示以 $nums[i]$ 结尾且公差为 $j$ 的等差数列的最大长度。初始时 $f[i][j]=1$,即每个元素自身都是一个长度为 $1$ 的等差数列。 + +考虑 $f[i][j]$,我们可以枚举 $nums[i]$ 的前一个元素 $nums[k]$,那么 $d=nums[i]-nums[k]+500$,此时有 $f[i][j]=\max(f[i][j], f[k][j]+1)$,然后我们更新答案 $ans=\max(ans, f[i][j])$。 + +最后返回答案即可。 + +时间复杂度 $O(n \times d)$,空间复杂度 $O(n \times d)$。其中 $n$ 和 $d$ 分别是数组 $nums$ 的长度以及数组 $nums$ 中元素的最大值与最小值的差值。 + ### **Python3** @@ -64,13 +72,13 @@ class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: n = len(nums) - dp = [[1] * 1001 for _ in range(n)] + f = [[1] * 1001 for _ in range(n)] ans = 0 for i in range(1, n): - for j in range(i): - d = nums[i] - nums[j] + 500 - dp[i][d] = max(dp[i][d], dp[j][d] + 1) - ans = max(ans, dp[i][d]) + for k in range(i): + j = nums[i] - nums[k] + 500 + f[i][j] = max(f[i][j], f[k][j] + 1) + ans = max(ans, f[i][j]) return ans ``` @@ -83,12 +91,12 @@ class Solution { public int longestArithSeqLength(int[] nums) { int n = nums.length; int ans = 0; - int[][] dp = new int[n][1001]; + int[][] f = new int[n][1001]; for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int d = nums[i] - nums[j] + 500; - dp[i][d] = Math.max(dp[i][d], dp[j][d] + 1); - ans = Math.max(ans, dp[i][d]); + for (int k = 0; k < i; ++k) { + int j = nums[i] - nums[k] + 500; + f[i][j] = Math.max(f[i][j], f[k][j] + 1); + ans = Math.max(ans, f[i][j]); } } return ans + 1; @@ -103,16 +111,17 @@ class Solution { public: int longestArithSeqLength(vector& nums) { int n = nums.size(); + int f[n][1001]; + memset(f, 0, sizeof(f)); int ans = 0; - vector> dp(n, vector(1001, 1)); for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int d = nums[i] - nums[j] + 500; - dp[i][d] = max(dp[i][d], dp[j][d] + 1); - ans = max(ans, dp[i][d]); + for (int k = 0; k < i; ++k) { + int j = nums[i] - nums[k] + 500; + f[i][j] = max(f[i][j], f[k][j] + 1); + ans = max(ans, f[i][j]); } } - return ans; + return ans + 1; } }; ``` @@ -122,16 +131,16 @@ public: ```go func longestArithSeqLength(nums []int) int { n := len(nums) - dp := make([][]int, n) - for i := range dp { - dp[i] = make([]int, 1001) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, 1001) } ans := 0 for i := 1; i < n; i++ { - for j := 0; j < i; j++ { - d := nums[i] - nums[j] + 500 - dp[i][d] = max(dp[i][d], dp[j][d]+1) - ans = max(ans, dp[i][d]) + for k := 0; k < i; k++ { + j := nums[i] - nums[k] + 500 + f[i][j] = max(f[i][j], f[k][j]+1) + ans = max(ans, f[i][j]) } } return ans + 1 diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md index 876ca131e0a27..ec013db8cb237 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md @@ -56,13 +56,13 @@ class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: n = len(nums) - dp = [[1] * 1001 for _ in range(n)] + f = [[1] * 1001 for _ in range(n)] ans = 0 for i in range(1, n): - for j in range(i): - d = nums[i] - nums[j] + 500 - dp[i][d] = max(dp[i][d], dp[j][d] + 1) - ans = max(ans, dp[i][d]) + for k in range(i): + j = nums[i] - nums[k] + 500 + f[i][j] = max(f[i][j], f[k][j] + 1) + ans = max(ans, f[i][j]) return ans ``` @@ -73,12 +73,12 @@ class Solution { public int longestArithSeqLength(int[] nums) { int n = nums.length; int ans = 0; - int[][] dp = new int[n][1001]; + int[][] f = new int[n][1001]; for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int d = nums[i] - nums[j] + 500; - dp[i][d] = Math.max(dp[i][d], dp[j][d] + 1); - ans = Math.max(ans, dp[i][d]); + for (int k = 0; k < i; ++k) { + int j = nums[i] - nums[k] + 500; + f[i][j] = Math.max(f[i][j], f[k][j] + 1); + ans = Math.max(ans, f[i][j]); } } return ans + 1; @@ -93,16 +93,17 @@ class Solution { public: int longestArithSeqLength(vector& nums) { int n = nums.size(); + int f[n][1001]; + memset(f, 0, sizeof(f)); int ans = 0; - vector> dp(n, vector(1001, 1)); for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int d = nums[i] - nums[j] + 500; - dp[i][d] = max(dp[i][d], dp[j][d] + 1); - ans = max(ans, dp[i][d]); + for (int k = 0; k < i; ++k) { + int j = nums[i] - nums[k] + 500; + f[i][j] = max(f[i][j], f[k][j] + 1); + ans = max(ans, f[i][j]); } } - return ans; + return ans + 1; } }; ``` @@ -112,16 +113,16 @@ public: ```go func longestArithSeqLength(nums []int) int { n := len(nums) - dp := make([][]int, n) - for i := range dp { - dp[i] = make([]int, 1001) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, 1001) } ans := 0 for i := 1; i < n; i++ { - for j := 0; j < i; j++ { - d := nums[i] - nums[j] + 500 - dp[i][d] = max(dp[i][d], dp[j][d]+1) - ans = max(ans, dp[i][d]) + for k := 0; k < i; k++ { + j := nums[i] - nums[k] + 500 + f[i][j] = max(f[i][j], f[k][j]+1) + ans = max(ans, f[i][j]) } } return ans + 1 diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.cpp b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.cpp index a36e7eb7154f5..0d817bde50964 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.cpp +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.cpp @@ -2,15 +2,16 @@ class Solution { public: int longestArithSeqLength(vector& nums) { int n = nums.size(); + int f[n][1001]; + memset(f, 0, sizeof(f)); int ans = 0; - vector> dp(n, vector(1001, 1)); for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int d = nums[i] - nums[j] + 500; - dp[i][d] = max(dp[i][d], dp[j][d] + 1); - ans = max(ans, dp[i][d]); + for (int k = 0; k < i; ++k) { + int j = nums[i] - nums[k] + 500; + f[i][j] = max(f[i][j], f[k][j] + 1); + ans = max(ans, f[i][j]); } } - return ans; + return ans + 1; } }; \ No newline at end of file diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.go b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.go index e320614cb81b0..8573f2b542724 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.go +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.go @@ -1,15 +1,15 @@ func longestArithSeqLength(nums []int) int { n := len(nums) - dp := make([][]int, n) - for i := range dp { - dp[i] = make([]int, 1001) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, 1001) } ans := 0 for i := 1; i < n; i++ { - for j := 0; j < i; j++ { - d := nums[i] - nums[j] + 500 - dp[i][d] = max(dp[i][d], dp[j][d]+1) - ans = max(ans, dp[i][d]) + for k := 0; k < i; k++ { + j := nums[i] - nums[k] + 500 + f[i][j] = max(f[i][j], f[k][j]+1) + ans = max(ans, f[i][j]) } } return ans + 1 diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.java b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.java index dd7ec05bf45bb..3248627579da2 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.java +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.java @@ -2,12 +2,12 @@ class Solution { public int longestArithSeqLength(int[] nums) { int n = nums.length; int ans = 0; - int[][] dp = new int[n][1001]; + int[][] f = new int[n][1001]; for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - int d = nums[i] - nums[j] + 500; - dp[i][d] = Math.max(dp[i][d], dp[j][d] + 1); - ans = Math.max(ans, dp[i][d]); + for (int k = 0; k < i; ++k) { + int j = nums[i] - nums[k] + 500; + f[i][j] = Math.max(f[i][j], f[k][j] + 1); + ans = Math.max(ans, f[i][j]); } } return ans + 1; diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.py b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.py index b349fe64d03e5..0160e1d858396 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.py +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/Solution.py @@ -1,11 +1,11 @@ class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: n = len(nums) - dp = [[1] * 1001 for _ in range(n)] + f = [[1] * 1001 for _ in range(n)] ans = 0 for i in range(1, n): - for j in range(i): - d = nums[i] - nums[j] + 500 - dp[i][d] = max(dp[i][d], dp[j][d] + 1) - ans = max(ans, dp[i][d]) + for k in range(i): + j = nums[i] - nums[k] + 500 + f[i][j] = max(f[i][j], f[k][j] + 1) + ans = max(ans, f[i][j]) return ans From e0d1d246edc63e7691d595146d582b16487e3a0b Mon Sep 17 00:00:00 2001 From: thinkasany <480968828@qq.com> Date: Thu, 23 Mar 2023 21:13:27 +0800 Subject: [PATCH 06/16] feat: update solutions to lc problem: No.0263 --- solution/0200-0299/0263.Ugly Number/README.md | 10 +++++----- solution/0200-0299/0263.Ugly Number/README_EN.md | 8 ++++---- solution/0200-0299/0263.Ugly Number/Solution.js | 8 ++++---- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/solution/0200-0299/0263.Ugly Number/README.md b/solution/0200-0299/0263.Ugly Number/README.md index caa39b1b96481..2080b6f45bc06 100644 --- a/solution/0200-0299/0263.Ugly Number/README.md +++ b/solution/0200-0299/0263.Ugly Number/README.md @@ -31,7 +31,7 @@
 输入:n = 14
 输出:false
-解释:14 不是丑数,因为它包含了另外一个质因数 7 。
+解释:14 不是丑数,因为它包含了另外一个质因数 7。
 

 

@@ -121,16 +121,16 @@ public: */ var isUgly = function (n) { if (n < 1) return false; - while (n % 2 == 0) { + while (n % 2 === 0) { n /= 2; } - while (n % 3 == 0) { + while (n % 3 === 0) { n /= 3; } - while (n % 5 == 0) { + while (n % 5 === 0) { n /= 5; } - return n == 1; + return n === 1; }; ``` diff --git a/solution/0200-0299/0263.Ugly Number/README_EN.md b/solution/0200-0299/0263.Ugly Number/README_EN.md index a5ac733c048e2..fb8681c2e00f9 100644 --- a/solution/0200-0299/0263.Ugly Number/README_EN.md +++ b/solution/0200-0299/0263.Ugly Number/README_EN.md @@ -107,16 +107,16 @@ public: */ var isUgly = function (n) { if (n < 1) return false; - while (n % 2 == 0) { + while (n % 2 === 0) { n /= 2; } - while (n % 3 == 0) { + while (n % 3 === 0) { n /= 3; } - while (n % 5 == 0) { + while (n % 5 === 0) { n /= 5; } - return n == 1; + return n === 1; }; ``` diff --git a/solution/0200-0299/0263.Ugly Number/Solution.js b/solution/0200-0299/0263.Ugly Number/Solution.js index 62572d7717787..1dee517ea4b2b 100644 --- a/solution/0200-0299/0263.Ugly Number/Solution.js +++ b/solution/0200-0299/0263.Ugly Number/Solution.js @@ -4,14 +4,14 @@ */ var isUgly = function (n) { if (n < 1) return false; - while (n % 2 == 0) { + while (n % 2 === 0) { n /= 2; } - while (n % 3 == 0) { + while (n % 3 === 0) { n /= 3; } - while (n % 5 == 0) { + while (n % 5 === 0) { n /= 5; } - return n == 1; + return n === 1; }; From d98c62aa7b4b3eb7700cc7765ea241f89bc3c819 Mon Sep 17 00:00:00 2001 From: thinkasany <480968828@qq.com> Date: Thu, 23 Mar 2023 21:26:26 +0800 Subject: [PATCH 07/16] feat: update solutions to lc problem: No.1033 --- .../README.md | 17 +++++++++++++++++ .../README_EN.md | 17 +++++++++++++++++ .../Solution.ts | 12 ++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.ts diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md index 61fb825847249..817bfba199be1 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md @@ -149,6 +149,23 @@ func min(a, b int) int { } ``` +### **TypeScript** + +```ts +function numMovesStones(a: number, b: number, c: number): number[] { + const x = Math.min(a, Math.min(b, c)); + const z = Math.max(a, Math.max(b, c)); + const y = a + b + c - x - z; + let mi = 0, + mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } + return [mi, mx]; +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md index 020d2b2c04e48..11c938fde70e8 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md @@ -138,6 +138,23 @@ func min(a, b int) int { } ``` +### **TypeScript** + +```ts +function numMovesStones(a: number, b: number, c: number): number[] { + const x = Math.min(a, Math.min(b, c)); + const z = Math.max(a, Math.max(b, c)); + const y = a + b + c - x - z; + let mi = 0, + mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } + return [mi, mx]; +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.ts b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.ts new file mode 100644 index 0000000000000..9ecac5c2f9fa1 --- /dev/null +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.ts @@ -0,0 +1,12 @@ +function numMovesStones(a: number, b: number, c: number): number[] { + const x = Math.min(a, Math.min(b, c)); + const z = Math.max(a, Math.max(b, c)); + const y = a + b + c - x - z; + let mi = 0, + mx = 0; + if (z - x > 2) { + mi = y - x < 3 || z - y < 3 ? 1 : 2; + mx = z - x - 2; + } + return [mi, mx]; +} From 4bdd08f9b6a3a040cf70e624d62c00e0e9911907 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 21:32:13 +0800 Subject: [PATCH 08/16] feat: update solutions to lc problem: No.1005 No.1005.Maximize Sum Of Array After K Negations --- .../README.md | 150 ++++++++++-------- .../README_EN.md | 138 ++++++++-------- .../Solution.cpp | 34 ++-- .../Solution.go | 40 +++-- .../Solution.java | 37 +++-- .../Solution.py | 27 ++-- 6 files changed, 219 insertions(+), 207 deletions(-) diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md index 7e12be06f4068..ab7e57a4b4f5e 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md @@ -56,6 +56,18 @@ +**方法一:贪心 + 计数** + +我们观察发现,要使得数组的和尽可能大,就应该尽可能地将数组中的最小负数变成正数。 + +而题目中元素的范围为 $[-100,100]$,因此,我们可以先用哈希表 $cnt$ 统计数组 $nums$ 中每个元素出现的次数。接着从 $-100$ 开始遍历 $x$,如果哈希表中存在 $x$,那么我们取 $m = \min(cnt[x], k)$ 作为元素 $x$ 取反的个数,然后我们将 $cnt[x]$ 减去 $m$,将 $cnt[-x]$ 加上 $m$,并将 $k$ 减去 $m$。如果 $k$ 为 $0$,说明操作已经结束,直接退出循环即可。 + +如果 $k$ 仍然为奇数,且 $cnt[0]=0$,那么我们还需要取 $cnt$ 中最小的一个正数 $x$,将 $cnt[x]$ 减去 $1$,将 $cnt[-x]$ 加上 $1$。 + +最后,我们遍历哈希表 $cnt$,将 $x$ 与 $cnt[x]$ 相乘的结果累加,即为答案。 + +时间复杂度 $O(n + M)$,空间复杂度 $O(M)$。其中 $n$ 和 $M$ 分别为数组 $nums$ 的长度和 $nums$ 的数据范围大小。 + ### **Python3** @@ -65,23 +77,22 @@ ```python class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: - counter = Counter(nums) - ans = sum(nums) - for i in range(-100, 0): - if counter[i]: - ops = min(counter[i], k) - ans -= i * ops * 2 - counter[i] -= ops - counter[-i] += ops - k -= ops + cnt = Counter(nums) + for x in range(-100, 0): + if cnt[x]: + m = min(cnt[x], k) + cnt[x] -= m + cnt[-x] += m + k -= m if k == 0: break - if k > 0 and k % 2 == 1 and not counter[0]: - for i in range(1, 101): - if counter[i]: - ans -= 2 * i + if k & 1 and cnt[0] == 0: + for x in range(1, 101): + if cnt[x]: + cnt[x] -= 1 + cnt[-x] += 1 break - return ans + return sum(x * v for x, v in cnt.items()) ``` ### **Java** @@ -91,32 +102,31 @@ class Solution: ```java class Solution { public int largestSumAfterKNegations(int[] nums, int k) { - int ans = 0; - Map counter = new HashMap<>(); - for (int num : nums) { - ans += num; - counter.put(num, counter.getOrDefault(num, 0) + 1); + Map cnt = new HashMap<>(); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); } - for (int i = -100; i < 0; ++i) { - if (counter.getOrDefault(i, 0) > 0) { - int ops = Math.min(counter.get(i), k); - ans -= (i * ops * 2); - counter.put(i, counter.getOrDefault(i, 0) - ops); - counter.put(-i, counter.getOrDefault(-i, 0) + ops); - k -= ops; - if (k == 0) { - break; - } + for (int x = -100; x < 0 && k > 0; ++x) { + if (cnt.getOrDefault(x, 0) > 0) { + int m = Math.min(cnt.get(x), k); + cnt.merge(x, -m, Integer::sum); + cnt.merge(-x, m, Integer::sum); + k -= m; } } - if (k > 0 && (k % 2) == 1 && counter.get(0) == null) { - for (int i = 1; i < 101; ++i) { - if (counter.getOrDefault(i, 0) > 0) { - ans -= 2 * i; + if ((k & 1) == 1 && cnt.getOrDefault(0, 0) == 0) { + for (int x = 1; x <= 100; ++x) { + if (cnt.getOrDefault(x, 0) > 0) { + cnt.merge(x, -1, Integer::sum); + cnt.merge(-x, 1, Integer::sum); break; } } } + int ans = 0; + for (var e : cnt.entrySet()) { + ans += e.getKey() * e.getValue(); + } return ans; } } @@ -128,27 +138,31 @@ class Solution { class Solution { public: int largestSumAfterKNegations(vector& nums, int k) { - unordered_map counter; - for (int num : nums) ++counter[num]; - int ans = accumulate(nums.begin(), nums.end(), 0); - for (int i = -100; i < 0; ++i) { - if (counter[i]) { - int ops = min(counter[i], k); - ans -= (i * ops * 2); - counter[i] -= ops; - counter[-i] += ops; - k -= ops; - if (k == 0) break; + unordered_map cnt; + for (int& x : nums) { + ++cnt[x]; + } + for (int x = -100; x < 0 && k > 0; ++x) { + if (cnt[x]) { + int m = min(cnt[x], k); + cnt[x] -= m; + cnt[-x] += m; + k -= m; } } - if (k > 0 && k % 2 == 1 && !counter[0]) { - for (int i = 1; i < 101; ++i) { - if (counter[i]) { - ans -= 2 * i; + if ((k & 1) && !cnt[0]) { + for (int x = 1; x <= 100; ++x) { + if (cnt[x]) { + --cnt[x]; + ++cnt[-x]; break; } } } + int ans = 0; + for (auto& [x, v] : cnt) { + ans += x * v; + } return ans; } }; @@ -157,34 +171,32 @@ public: ### **Go** ```cpp -func largestSumAfterKNegations(nums []int, k int) int { - ans := 0 - counter := make(map[int]int) - for _, num := range nums { - ans += num - counter[num]++ +func largestSumAfterKNegations(nums []int, k int) (ans int) { + cnt := map[int]int{} + for _, x := range nums { + cnt[x]++ } - for i := -100; i < 0; i++ { - if counter[i] > 0 { - ops := min(counter[i], k) - ans -= (i * ops * 2) - counter[i] -= ops - counter[-i] += ops - k -= ops - if k == 0 { - break - } + for x := -100; x < 0 && k > 0; x++ { + if cnt[x] > 0 { + m := min(k, cnt[x]) + cnt[x] -= m + cnt[-x] += m + k -= m } } - if k > 0 && k%2 == 1 && counter[0] == 0 { - for i := 1; i < 101; i++ { - if counter[i] > 0 { - ans -= 2 * i + if k&1 == 1 && cnt[0] == 0 { + for x := 1; x <= 100; x++ { + if cnt[x] > 0 { + cnt[x]-- + cnt[-x]++ break } } } - return ans + for x, v := range cnt { + ans += x * v + } + return } func min(a, b int) int { diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md index c39ecf0c79091..7eb9ff24dcdd3 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md @@ -57,23 +57,22 @@ ```python class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: - counter = Counter(nums) - ans = sum(nums) - for i in range(-100, 0): - if counter[i]: - ops = min(counter[i], k) - ans -= i * ops * 2 - counter[i] -= ops - counter[-i] += ops - k -= ops + cnt = Counter(nums) + for x in range(-100, 0): + if cnt[x]: + m = min(cnt[x], k) + cnt[x] -= m + cnt[-x] += m + k -= m if k == 0: break - if k > 0 and k % 2 == 1 and not counter[0]: - for i in range(1, 101): - if counter[i]: - ans -= 2 * i + if k & 1 and cnt[0] == 0: + for x in range(1, 101): + if cnt[x]: + cnt[x] -= 1 + cnt[-x] += 1 break - return ans + return sum(x * v for x, v in cnt.items()) ``` ### **Java** @@ -81,32 +80,31 @@ class Solution: ```java class Solution { public int largestSumAfterKNegations(int[] nums, int k) { - int ans = 0; - Map counter = new HashMap<>(); - for (int num : nums) { - ans += num; - counter.put(num, counter.getOrDefault(num, 0) + 1); + Map cnt = new HashMap<>(); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); } - for (int i = -100; i < 0; ++i) { - if (counter.getOrDefault(i, 0) > 0) { - int ops = Math.min(counter.get(i), k); - ans -= (i * ops * 2); - counter.put(i, counter.getOrDefault(i, 0) - ops); - counter.put(-i, counter.getOrDefault(-i, 0) + ops); - k -= ops; - if (k == 0) { - break; - } + for (int x = -100; x < 0 && k > 0; ++x) { + if (cnt.getOrDefault(x, 0) > 0) { + int m = Math.min(cnt.get(x), k); + cnt.merge(x, -m, Integer::sum); + cnt.merge(-x, m, Integer::sum); + k -= m; } } - if (k > 0 && (k % 2) == 1 && counter.get(0) == null) { - for (int i = 1; i < 101; ++i) { - if (counter.getOrDefault(i, 0) > 0) { - ans -= 2 * i; + if ((k & 1) == 1 && cnt.getOrDefault(0, 0) == 0) { + for (int x = 1; x <= 100; ++x) { + if (cnt.getOrDefault(x, 0) > 0) { + cnt.merge(x, -1, Integer::sum); + cnt.merge(-x, 1, Integer::sum); break; } } } + int ans = 0; + for (var e : cnt.entrySet()) { + ans += e.getKey() * e.getValue(); + } return ans; } } @@ -118,27 +116,31 @@ class Solution { class Solution { public: int largestSumAfterKNegations(vector& nums, int k) { - unordered_map counter; - for (int num : nums) ++counter[num]; - int ans = accumulate(nums.begin(), nums.end(), 0); - for (int i = -100; i < 0; ++i) { - if (counter[i]) { - int ops = min(counter[i], k); - ans -= (i * ops * 2); - counter[i] -= ops; - counter[-i] += ops; - k -= ops; - if (k == 0) break; + unordered_map cnt; + for (int& x : nums) { + ++cnt[x]; + } + for (int x = -100; x < 0 && k > 0; ++x) { + if (cnt[x]) { + int m = min(cnt[x], k); + cnt[x] -= m; + cnt[-x] += m; + k -= m; } } - if (k > 0 && k % 2 == 1 && !counter[0]) { - for (int i = 1; i < 101; ++i) { - if (counter[i]) { - ans -= 2 * i; + if ((k & 1) && !cnt[0]) { + for (int x = 1; x <= 100; ++x) { + if (cnt[x]) { + --cnt[x]; + ++cnt[-x]; break; } } } + int ans = 0; + for (auto& [x, v] : cnt) { + ans += x * v; + } return ans; } }; @@ -147,34 +149,32 @@ public: ### **Go** ```cpp -func largestSumAfterKNegations(nums []int, k int) int { - ans := 0 - counter := make(map[int]int) - for _, num := range nums { - ans += num - counter[num]++ +func largestSumAfterKNegations(nums []int, k int) (ans int) { + cnt := map[int]int{} + for _, x := range nums { + cnt[x]++ } - for i := -100; i < 0; i++ { - if counter[i] > 0 { - ops := min(counter[i], k) - ans -= (i * ops * 2) - counter[i] -= ops - counter[-i] += ops - k -= ops - if k == 0 { - break - } + for x := -100; x < 0 && k > 0; x++ { + if cnt[x] > 0 { + m := min(k, cnt[x]) + cnt[x] -= m + cnt[-x] += m + k -= m } } - if k > 0 && k%2 == 1 && counter[0] == 0 { - for i := 1; i < 101; i++ { - if counter[i] > 0 { - ans -= 2 * i + if k&1 == 1 && cnt[0] == 0 { + for x := 1; x <= 100; x++ { + if cnt[x] > 0 { + cnt[x]-- + cnt[-x]++ break } } } - return ans + for x, v := range cnt { + ans += x * v + } + return } func min(a, b int) int { diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.cpp b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.cpp index 9a5b8f822aaf8..2840424126251 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.cpp +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.cpp @@ -1,27 +1,31 @@ class Solution { public: int largestSumAfterKNegations(vector& nums, int k) { - unordered_map counter; - for (int num : nums) ++counter[num]; - int ans = accumulate(nums.begin(), nums.end(), 0); - for (int i = -100; i < 0; ++i) { - if (counter[i]) { - int ops = min(counter[i], k); - ans -= (i * ops * 2); - counter[i] -= ops; - counter[-i] += ops; - k -= ops; - if (k == 0) break; + unordered_map cnt; + for (int& x : nums) { + ++cnt[x]; + } + for (int x = -100; x < 0 && k > 0; ++x) { + if (cnt[x]) { + int m = min(cnt[x], k); + cnt[x] -= m; + cnt[-x] += m; + k -= m; } } - if (k > 0 && k % 2 == 1 && !counter[0]) { - for (int i = 1; i < 101; ++i) { - if (counter[i]) { - ans -= 2 * i; + if ((k & 1) && !cnt[0]) { + for (int x = 1; x <= 100; ++x) { + if (cnt[x]) { + --cnt[x]; + ++cnt[-x]; break; } } } + int ans = 0; + for (auto& [x, v] : cnt) { + ans += x * v; + } return ans; } }; \ No newline at end of file diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.go b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.go index b260d1ed18f9a..76ae55a665ef4 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.go +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.go @@ -1,31 +1,29 @@ -func largestSumAfterKNegations(nums []int, k int) int { - ans := 0 - counter := make(map[int]int) - for _, num := range nums { - ans += num - counter[num]++ +func largestSumAfterKNegations(nums []int, k int) (ans int) { + cnt := map[int]int{} + for _, x := range nums { + cnt[x]++ } - for i := -100; i < 0; i++ { - if counter[i] > 0 { - ops := min(counter[i], k) - ans -= (i * ops * 2) - counter[i] -= ops - counter[-i] += ops - k -= ops - if k == 0 { - break - } + for x := -100; x < 0 && k > 0; x++ { + if cnt[x] > 0 { + m := min(k, cnt[x]) + cnt[x] -= m + cnt[-x] += m + k -= m } } - if k > 0 && k%2 == 1 && counter[0] == 0 { - for i := 1; i < 101; i++ { - if counter[i] > 0 { - ans -= 2 * i + if k&1 == 1 && cnt[0] == 0 { + for x := 1; x <= 100; x++ { + if cnt[x] > 0 { + cnt[x]-- + cnt[-x]++ break } } } - return ans + for x, v := range cnt { + ans += x * v + } + return } func min(a, b int) int { diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.java b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.java index c69ef0a52c59f..d3ba52bcf892d 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.java +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.java @@ -1,31 +1,30 @@ class Solution { public int largestSumAfterKNegations(int[] nums, int k) { - int ans = 0; - Map counter = new HashMap<>(); - for (int num : nums) { - ans += num; - counter.put(num, counter.getOrDefault(num, 0) + 1); + Map cnt = new HashMap<>(); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); } - for (int i = -100; i < 0; ++i) { - if (counter.getOrDefault(i, 0) > 0) { - int ops = Math.min(counter.get(i), k); - ans -= (i * ops * 2); - counter.put(i, counter.getOrDefault(i, 0) - ops); - counter.put(-i, counter.getOrDefault(-i, 0) + ops); - k -= ops; - if (k == 0) { - break; - } + for (int x = -100; x < 0 && k > 0; ++x) { + if (cnt.getOrDefault(x, 0) > 0) { + int m = Math.min(cnt.get(x), k); + cnt.merge(x, -m, Integer::sum); + cnt.merge(-x, m, Integer::sum); + k -= m; } } - if (k > 0 && (k % 2) == 1 && counter.get(0) == null) { - for (int i = 1; i < 101; ++i) { - if (counter.getOrDefault(i, 0) > 0) { - ans -= 2 * i; + if ((k & 1) == 1 && cnt.getOrDefault(0, 0) == 0) { + for (int x = 1; x <= 100; ++x) { + if (cnt.getOrDefault(x, 0) > 0) { + cnt.merge(x, -1, Integer::sum); + cnt.merge(-x, 1, Integer::sum); break; } } } + int ans = 0; + for (var e : cnt.entrySet()) { + ans += e.getKey() * e.getValue(); + } return ans; } } \ No newline at end of file diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.py b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.py index f19a8cf9cc0d5..17511aa63e3c0 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.py +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.py @@ -1,19 +1,18 @@ class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: - counter = Counter(nums) - ans = sum(nums) - for i in range(-100, 0): - if counter[i]: - ops = min(counter[i], k) - ans -= i * ops * 2 - counter[i] -= ops - counter[-i] += ops - k -= ops + cnt = Counter(nums) + for x in range(-100, 0): + if cnt[x]: + m = min(cnt[x], k) + cnt[x] -= m + cnt[-x] += m + k -= m if k == 0: break - if k > 0 and k % 2 == 1 and not counter[0]: - for i in range(1, 101): - if counter[i]: - ans -= 2 * i + if k & 1 and cnt[0] == 0: + for x in range(1, 101): + if cnt[x]: + cnt[x] -= 1 + cnt[-x] += 1 break - return ans + return sum(x * v for x, v in cnt.items()) From 7ff27c4b7f986318df956c043da99b53ce96a87c Mon Sep 17 00:00:00 2001 From: thinkasany <480968828@qq.com> Date: Thu, 23 Mar 2023 21:54:34 +0800 Subject: [PATCH 09/16] feat: ChatGPT Code Review --- .github/workflows/chatgpt-cr.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/chatgpt-cr.yml diff --git a/.github/workflows/chatgpt-cr.yml b/.github/workflows/chatgpt-cr.yml new file mode 100644 index 0000000000000..41934d68172b9 --- /dev/null +++ b/.github/workflows/chatgpt-cr.yml @@ -0,0 +1,20 @@ +name: 🤖 ChatGPT Code Review + +permissions: + contents: read + pull-requests: write + +on: + pull_request: + types: [opened, reopened] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: anc95/ChatGPT-CodeReview@main + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + # Optional + LANGUAGE: Chinese From 4ea053153804d031cdc4751470dabd05d71ddf56 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 22:32:29 +0800 Subject: [PATCH 10/16] chore: update workflow --- .github/workflows/chatgpt-cr.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/chatgpt-cr.yml b/.github/workflows/chatgpt-cr.yml index 41934d68172b9..54a3fc3f3b70a 100644 --- a/.github/workflows/chatgpt-cr.yml +++ b/.github/workflows/chatgpt-cr.yml @@ -1,7 +1,8 @@ -name: 🤖 ChatGPT Code Review +name: chatgpt-cr permissions: contents: read + issues: write pull-requests: write on: @@ -14,7 +15,6 @@ jobs: steps: - uses: anc95/ChatGPT-CodeReview@main env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.ACTION_TOKEN }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - # Optional LANGUAGE: Chinese From 988163c429635d137ce4f2b736cd316c876c51a9 Mon Sep 17 00:00:00 2001 From: thinkasany <117748716+thinkasany@users.noreply.github.com> Date: Thu, 23 Mar 2023 22:44:44 +0800 Subject: [PATCH 11/16] feat: update solutions to lc problem: No.1005 (#946) --- .../README.md | 35 ++++++++++++++++++- .../README_EN.md | 35 ++++++++++++++++++- .../Solution.ts | 28 +++++++++++++++ 3 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.ts diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md index ab7e57a4b4f5e..b21d649adc80a 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md @@ -170,7 +170,7 @@ public: ### **Go** -```cpp +```go func largestSumAfterKNegations(nums []int, k int) (ans int) { cnt := map[int]int{} for _, x := range nums { @@ -207,6 +207,39 @@ func min(a, b int) int { } ``` +### **TypeScript** + +```ts +function largestSumAfterKNegations(nums: number[], k: number): number { + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + for (let x = -100; x < 0 && k > 0; ++x) { + if (cnt.get(x)! > 0) { + const m = Math.min(cnt.get(x) || 0, k); + cnt.set(x, (cnt.get(x) || 0) - m); + cnt.set(-x, (cnt.get(-x) || 0) + m); + k -= m; + } + } + if ((k & 1) === 1 && (cnt.get(0) || 0) === 0) { + for (let x = 1; x <= 100; ++x) { + if (cnt.get(x)! > 0) { + cnt.set(x, (cnt.get(x) || 0) - 1); + cnt.set(-x, (cnt.get(-x) || 0) + 1); + break; + } + } + } + let ans = 0; + for (const [key, value] of cnt.entries()) { + ans += key * value; + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md index 7eb9ff24dcdd3..7305be2ff834b 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md @@ -148,7 +148,7 @@ public: ### **Go** -```cpp +```go func largestSumAfterKNegations(nums []int, k int) (ans int) { cnt := map[int]int{} for _, x := range nums { @@ -185,6 +185,39 @@ func min(a, b int) int { } ``` +### **TypeScript** + +```ts +function largestSumAfterKNegations(nums: number[], k: number): number { + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + for (let x = -100; x < 0 && k > 0; ++x) { + if (cnt.get(x)! > 0) { + const m = Math.min(cnt.get(x) || 0, k); + cnt.set(x, (cnt.get(x) || 0) - m); + cnt.set(-x, (cnt.get(-x) || 0) + m); + k -= m; + } + } + if ((k & 1) === 1 && (cnt.get(0) || 0) === 0) { + for (let x = 1; x <= 100; ++x) { + if (cnt.get(x)! > 0) { + cnt.set(x, (cnt.get(x) || 0) - 1); + cnt.set(-x, (cnt.get(-x) || 0) + 1); + break; + } + } + } + let ans = 0; + for (const [key, value] of cnt.entries()) { + ans += key * value; + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.ts b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.ts new file mode 100644 index 0000000000000..98ac83f664b51 --- /dev/null +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/Solution.ts @@ -0,0 +1,28 @@ +function largestSumAfterKNegations(nums: number[], k: number): number { + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + for (let x = -100; x < 0 && k > 0; ++x) { + if (cnt.get(x)! > 0) { + const m = Math.min(cnt.get(x) || 0, k); + cnt.set(x, (cnt.get(x) || 0) - m); + cnt.set(-x, (cnt.get(-x) || 0) + m); + k -= m; + } + } + if ((k & 1) === 1 && (cnt.get(0) || 0) === 0) { + for (let x = 1; x <= 100; ++x) { + if (cnt.get(x)! > 0) { + cnt.set(x, (cnt.get(x) || 0) - 1); + cnt.set(-x, (cnt.get(-x) || 0) + 1); + break; + } + } + } + let ans = 0; + for (const [key, value] of cnt.entries()) { + ans += key * value; + } + return ans; +} From a7eebca370ca6bdd15ff206d555e586a1af7858b Mon Sep 17 00:00:00 2001 From: Yang Libin Date: Thu, 23 Mar 2023 22:46:23 +0800 Subject: [PATCH 12/16] feat: update solutions to lc problem: No.1002 (#947) No.1002.Find Common Characters --- .../1002.Find Common Characters/README.md | 107 ++++++++++-------- .../1002.Find Common Characters/README_EN.md | 101 +++++++++-------- .../1002.Find Common Characters/Solution.cpp | 28 +++-- .../1002.Find Common Characters/Solution.go | 30 ++--- .../1002.Find Common Characters/Solution.java | 22 ++-- .../1002.Find Common Characters/Solution.py | 21 ++-- 6 files changed, 159 insertions(+), 150 deletions(-) diff --git a/solution/1000-1099/1002.Find Common Characters/README.md b/solution/1000-1099/1002.Find Common Characters/README.md index 732a5bd9bbda2..3ad1ea50d8716 100644 --- a/solution/1000-1099/1002.Find Common Characters/README.md +++ b/solution/1000-1099/1002.Find Common Characters/README.md @@ -38,6 +38,12 @@ +**方法一:计数** + +我们用一个长度为 $26$ 的数组 $cnt$ 记录每个字符在所有字符串中出现的最小次数,最后遍历 $cnt$ 数组,将出现次数大于 $0$ 的字符加入答案即可。 + +时间复杂度 $O(n \sum w_i)$,空间复杂度 $O(C)$。其中 $n$ 为字符串数组 $words$ 的长度,而 $w_i$ 为字符串数组 $words$ 中第 $i$ 个字符串的长度,另外 $C$ 为字符集的大小,本题中 $C = 26$。 + ### **Python3** @@ -47,18 +53,15 @@ ```python class Solution: def commonChars(self, words: List[str]) -> List[str]: - freq = [10000] * 26 - for word in words: - t = [0] * 26 - for c in word: - t[ord(c) - ord('a')] += 1 - for i in range(26): - freq[i] = min(freq[i], t[i]) - res = [] - for i in range(26): - if freq[i] > 0: - res.extend([chr(i + ord("a"))] * freq[i]) - return res + cnt = Counter(words[0]) + for w in words: + ccnt = Counter(w) + for c in cnt.keys(): + cnt[c] = min(cnt[c], ccnt[c]) + ans = [] + for c, v in cnt.items(): + ans.extend([c] * v) + return ans ``` ### **Java** @@ -68,24 +71,24 @@ class Solution: ```java class Solution { public List commonChars(String[] words) { - int[] freq = new int[26]; - Arrays.fill(freq, 10000); - for (String word : words) { - int[] t = new int[26]; - for (char c : word.toCharArray()) { - ++t[c - 'a']; + int[] cnt = new int[26]; + Arrays.fill(cnt, 10000); + for (String w : words) { + int[] ccnt = new int[26]; + for (int i = 0; i < w.length(); ++i) { + ++ccnt[w.charAt(i) - 'a']; } for (int i = 0; i < 26; ++i) { - freq[i] = Math.min(freq[i], t[i]); + cnt[i] = Math.min(cnt[i], ccnt[i]); } } - List res = new ArrayList<>(); + List ans = new ArrayList<>(); for (int i = 0; i < 26; ++i) { - while (freq[i]-- > 0) { - res.add(String.valueOf((char) (i + 'a'))); + while (cnt[i]-- > 0) { + ans.add(String.valueOf((char) (i + 'a'))); } } - return res; + return ans; } } ``` @@ -96,20 +99,24 @@ class Solution { class Solution { public: vector commonChars(vector& words) { - vector freq(26, 10000); - for (auto word : words) { - vector t(26); - for (char c : word) - ++t[c - 'a']; - for (int i = 0; i < 26; ++i) - freq[i] = min(freq[i], t[i]); + int cnt[26]; + memset(cnt, 0x3f, sizeof(cnt)); + for (auto& w : words) { + int ccnt[26]{}; + for (char& c : w) { + ++ccnt[c - 'a']; + } + for (int i = 0; i < 26; ++i) { + cnt[i] = min(cnt[i], ccnt[i]); + } } - vector res; - for (int i = 0; i < 26; i++) { - while (freq[i]--) - res.emplace_back(1, i + 'a'); + vector ans; + for (int i = 0; i < 26; ++i) { + while (cnt[i]--) { + ans.emplace_back(1, i + 'a'); + } } - return res; + return ans; } }; ``` @@ -117,27 +124,27 @@ public: ### **Go** ```go -func commonChars(words []string) []string { - freq := make([]int, 26) - for i := 0; i < 26; i++ { - freq[i] = 10000 +func commonChars(words []string) (ans []string) { + cnt := [26]int{} + for i := range cnt { + cnt[i] = 1 << 30 } - for _, word := range words { - t := make([]int, 26) - for _, c := range word { - t[c-'a']++ + for _, w := range words { + ccnt := [26]int{} + for _, c := range w { + ccnt[c-'a']++ } - for i := 0; i < 26; i++ { - freq[i] = min(freq[i], t[i]) + for i, v := range cnt { + cnt[i] = min(v, ccnt[i]) } } - var res []string - for i := 0; i < 26; i++ { - for j := 0; j < freq[i]; j++ { - res = append(res, string('a'+i)) + for i, v := range cnt { + for v > 0 { + ans = append(ans, string(i+'a')) + v-- } } - return res + return } func min(a, b int) int { diff --git a/solution/1000-1099/1002.Find Common Characters/README_EN.md b/solution/1000-1099/1002.Find Common Characters/README_EN.md index c6e89b0a55af9..5a511e79472df 100644 --- a/solution/1000-1099/1002.Find Common Characters/README_EN.md +++ b/solution/1000-1099/1002.Find Common Characters/README_EN.md @@ -32,18 +32,15 @@ ```python class Solution: def commonChars(self, words: List[str]) -> List[str]: - freq = [10000] * 26 - for word in words: - t = [0] * 26 - for c in word: - t[ord(c) - ord('a')] += 1 - for i in range(26): - freq[i] = min(freq[i], t[i]) - res = [] - for i in range(26): - if freq[i] > 0: - res.extend([chr(i + ord("a"))] * freq[i]) - return res + cnt = Counter(words[0]) + for w in words: + ccnt = Counter(w) + for c in cnt.keys(): + cnt[c] = min(cnt[c], ccnt[c]) + ans = [] + for c, v in cnt.items(): + ans.extend([c] * v) + return ans ``` ### **Java** @@ -51,24 +48,24 @@ class Solution: ```java class Solution { public List commonChars(String[] words) { - int[] freq = new int[26]; - Arrays.fill(freq, 10000); - for (String word : words) { - int[] t = new int[26]; - for (char c : word.toCharArray()) { - ++t[c - 'a']; + int[] cnt = new int[26]; + Arrays.fill(cnt, 10000); + for (String w : words) { + int[] ccnt = new int[26]; + for (int i = 0; i < w.length(); ++i) { + ++ccnt[w.charAt(i) - 'a']; } for (int i = 0; i < 26; ++i) { - freq[i] = Math.min(freq[i], t[i]); + cnt[i] = Math.min(cnt[i], ccnt[i]); } } - List res = new ArrayList<>(); + List ans = new ArrayList<>(); for (int i = 0; i < 26; ++i) { - while (freq[i]-- > 0) { - res.add(String.valueOf((char) (i + 'a'))); + while (cnt[i]-- > 0) { + ans.add(String.valueOf((char) (i + 'a'))); } } - return res; + return ans; } } ``` @@ -79,20 +76,24 @@ class Solution { class Solution { public: vector commonChars(vector& words) { - vector freq(26, 10000); - for (auto word : words) { - vector t(26); - for (char c : word) - ++t[c - 'a']; - for (int i = 0; i < 26; ++i) - freq[i] = min(freq[i], t[i]); + int cnt[26]; + memset(cnt, 0x3f, sizeof(cnt)); + for (auto& w : words) { + int ccnt[26]{}; + for (char& c : w) { + ++ccnt[c - 'a']; + } + for (int i = 0; i < 26; ++i) { + cnt[i] = min(cnt[i], ccnt[i]); + } } - vector res; - for (int i = 0; i < 26; i++) { - while (freq[i]--) - res.emplace_back(1, i + 'a'); + vector ans; + for (int i = 0; i < 26; ++i) { + while (cnt[i]--) { + ans.emplace_back(1, i + 'a'); + } } - return res; + return ans; } }; ``` @@ -100,27 +101,27 @@ public: ### **Go** ```go -func commonChars(words []string) []string { - freq := make([]int, 26) - for i := 0; i < 26; i++ { - freq[i] = 10000 +func commonChars(words []string) (ans []string) { + cnt := [26]int{} + for i := range cnt { + cnt[i] = 1 << 30 } - for _, word := range words { - t := make([]int, 26) - for _, c := range word { - t[c-'a']++ + for _, w := range words { + ccnt := [26]int{} + for _, c := range w { + ccnt[c-'a']++ } - for i := 0; i < 26; i++ { - freq[i] = min(freq[i], t[i]) + for i, v := range cnt { + cnt[i] = min(v, ccnt[i]) } } - var res []string - for i := 0; i < 26; i++ { - for j := 0; j < freq[i]; j++ { - res = append(res, string('a'+i)) + for i, v := range cnt { + for v > 0 { + ans = append(ans, string(i+'a')) + v-- } } - return res + return } func min(a, b int) int { diff --git a/solution/1000-1099/1002.Find Common Characters/Solution.cpp b/solution/1000-1099/1002.Find Common Characters/Solution.cpp index b821a4185d47a..3dcd528d4d3b0 100644 --- a/solution/1000-1099/1002.Find Common Characters/Solution.cpp +++ b/solution/1000-1099/1002.Find Common Characters/Solution.cpp @@ -1,19 +1,23 @@ class Solution { public: vector commonChars(vector& words) { - vector freq(26, 10000); - for (auto word : words) { - vector t(26); - for (char c : word) - ++t[c - 'a']; - for (int i = 0; i < 26; ++i) - freq[i] = min(freq[i], t[i]); + int cnt[26]; + memset(cnt, 0x3f, sizeof(cnt)); + for (auto& w : words) { + int ccnt[26]{}; + for (char& c : w) { + ++ccnt[c - 'a']; + } + for (int i = 0; i < 26; ++i) { + cnt[i] = min(cnt[i], ccnt[i]); + } } - vector res; - for (int i = 0; i < 26; i++) { - while (freq[i]--) - res.emplace_back(1, i + 'a'); + vector ans; + for (int i = 0; i < 26; ++i) { + while (cnt[i]--) { + ans.emplace_back(1, i + 'a'); + } } - return res; + return ans; } }; \ No newline at end of file diff --git a/solution/1000-1099/1002.Find Common Characters/Solution.go b/solution/1000-1099/1002.Find Common Characters/Solution.go index 18ac5694cf1f4..9d3880130c755 100644 --- a/solution/1000-1099/1002.Find Common Characters/Solution.go +++ b/solution/1000-1099/1002.Find Common Characters/Solution.go @@ -1,24 +1,24 @@ -func commonChars(words []string) []string { - freq := make([]int, 26) - for i := 0; i < 26; i++ { - freq[i] = 10000 +func commonChars(words []string) (ans []string) { + cnt := [26]int{} + for i := range cnt { + cnt[i] = 1 << 30 } - for _, word := range words { - t := make([]int, 26) - for _, c := range word { - t[c-'a']++ + for _, w := range words { + ccnt := [26]int{} + for _, c := range w { + ccnt[c-'a']++ } - for i := 0; i < 26; i++ { - freq[i] = min(freq[i], t[i]) + for i, v := range cnt { + cnt[i] = min(v, ccnt[i]) } } - var res []string - for i := 0; i < 26; i++ { - for j := 0; j < freq[i]; j++ { - res = append(res, string('a'+i)) + for i, v := range cnt { + for v > 0 { + ans = append(ans, string(i+'a')) + v-- } } - return res + return } func min(a, b int) int { diff --git a/solution/1000-1099/1002.Find Common Characters/Solution.java b/solution/1000-1099/1002.Find Common Characters/Solution.java index b91c8bd8eb3b4..492a8b07370ea 100644 --- a/solution/1000-1099/1002.Find Common Characters/Solution.java +++ b/solution/1000-1099/1002.Find Common Characters/Solution.java @@ -1,22 +1,22 @@ class Solution { public List commonChars(String[] words) { - int[] freq = new int[26]; - Arrays.fill(freq, 10000); - for (String word : words) { - int[] t = new int[26]; - for (char c : word.toCharArray()) { - ++t[c - 'a']; + int[] cnt = new int[26]; + Arrays.fill(cnt, 10000); + for (String w : words) { + int[] ccnt = new int[26]; + for (int i = 0; i < w.length(); ++i) { + ++ccnt[w.charAt(i) - 'a']; } for (int i = 0; i < 26; ++i) { - freq[i] = Math.min(freq[i], t[i]); + cnt[i] = Math.min(cnt[i], ccnt[i]); } } - List res = new ArrayList<>(); + List ans = new ArrayList<>(); for (int i = 0; i < 26; ++i) { - while (freq[i]-- > 0) { - res.add(String.valueOf((char) (i + 'a'))); + while (cnt[i]-- > 0) { + ans.add(String.valueOf((char) (i + 'a'))); } } - return res; + return ans; } } \ No newline at end of file diff --git a/solution/1000-1099/1002.Find Common Characters/Solution.py b/solution/1000-1099/1002.Find Common Characters/Solution.py index b7be0e94d031d..5890567c612e7 100644 --- a/solution/1000-1099/1002.Find Common Characters/Solution.py +++ b/solution/1000-1099/1002.Find Common Characters/Solution.py @@ -1,14 +1,11 @@ class Solution: def commonChars(self, words: List[str]) -> List[str]: - freq = [10000] * 26 - for word in words: - t = [0] * 26 - for c in word: - t[ord(c) - ord('a')] += 1 - for i in range(26): - freq[i] = min(freq[i], t[i]) - res = [] - for i in range(26): - if freq[i] > 0: - res.extend([chr(i + ord("a"))] * freq[i]) - return res + cnt = Counter(words[0]) + for w in words: + ccnt = Counter(w) + for c in cnt.keys(): + cnt[c] = min(cnt[c], ccnt[c]) + ans = [] + for c, v in cnt.items(): + ans.extend([c] * v) + return ans From 017f330be8104cbeb3eb354a94ec48e97b6df399 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 23 Mar 2023 23:52:56 +0800 Subject: [PATCH 13/16] feat: add solutions to lcp problem: No.66 --- .github/workflows/chatgpt-cr.yml | 2 +- .../README.md" | 90 ++++++++++++++++++- .../Solution.cpp" | 20 +++++ .../Solution.go" | 16 ++++ .../Solution.java" | 21 +++++ .../Solution.py" | 13 +++ 6 files changed, 160 insertions(+), 2 deletions(-) create mode 100644 "lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.cpp" create mode 100644 "lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.go" create mode 100644 "lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.java" create mode 100644 "lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.py" diff --git a/.github/workflows/chatgpt-cr.yml b/.github/workflows/chatgpt-cr.yml index 54a3fc3f3b70a..593b9c20ad1b2 100644 --- a/.github/workflows/chatgpt-cr.yml +++ b/.github/workflows/chatgpt-cr.yml @@ -15,6 +15,6 @@ jobs: steps: - uses: anc95/ChatGPT-CodeReview@main env: - GITHUB_TOKEN: ${{ secrets.ACTION_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} LANGUAGE: Chinese diff --git "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" index 999223c229229..8f501f03449f7 100644 --- "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" +++ "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" @@ -39,6 +39,16 @@ +**方法一:计数** + +我们用哈希表或数组 $cnt$ 记录当前可用的展台以及数量。 + +然后遍历 $demand$,对于每一天,遍历该天的展台需求,如果 $cnt$ 中有该展台,则将其数量减一,否则我们需要准备一个新的展台,答案加一。遍历结束后,将该天的所有展台都加入 $cnt$ 中。 + +最后返回答案即可。 + +时间复杂度 $O(L)$,空间复杂度 $O(C)$。其中 $L$ 为 $demand$ 中所有字符串的长度之和,而 $C$ 为字符集的大小,本题中 $C = 26$。 + ### **Python3** @@ -46,7 +56,19 @@ ```python - +class Solution: + def minNumBooths(self, demand: List[str]) -> int: + cnt = Counter() + ans = 0 + for s in demand: + for c in s: + if cnt[c]: + cnt[c] -= 1 + else: + ans += 1 + for c in s: + cnt[c] += 1 + return ans ``` ### **Java** @@ -54,7 +76,73 @@ ```java +class Solution { + public int minNumBooths(String[] demand) { + int[] cnt = new int[26]; + int ans = 0; + for (var s : demand) { + int m = s.length(); + for (int i = 0; i < m; ++i) { + int j = s.charAt(i) - 'a'; + if (cnt[j] > 0) { + --cnt[j]; + } else { + ++ans; + } + } + for (int i = 0; i < m; ++i) { + ++cnt[s.charAt(i) - 'a']; + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minNumBooths(vector& demand) { + int cnt[26]{}; + int ans = 0; + for (auto& s : demand) { + for (char& c : s) { + if (cnt[c - 'a']) { + --cnt[c - 'a']; + } else { + ++ans; + } + } + for (char& c : s) { + ++cnt[c - 'a']; + } + } + return ans; + } +}; +``` +### **Go** + +```go +func minNumBooths(demand []string) (ans int) { + cnt := [26]int{} + for _, s := range demand { + for _, c := range s { + if cnt[c-'a'] > 0 { + cnt[c-'a']-- + } else { + ans++ + } + } + for _, c := range s { + cnt[c-'a']++ + } + } + return +} ``` ### **...** diff --git "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.cpp" "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.cpp" new file mode 100644 index 0000000000000..553a8134adb65 --- /dev/null +++ "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.cpp" @@ -0,0 +1,20 @@ +class Solution { +public: + int minNumBooths(vector& demand) { + int cnt[26]{}; + int ans = 0; + for (auto& s : demand) { + for (char& c : s) { + if (cnt[c - 'a']) { + --cnt[c - 'a']; + } else { + ++ans; + } + } + for (char& c : s) { + ++cnt[c - 'a']; + } + } + return ans; + } +}; \ No newline at end of file diff --git "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.go" "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.go" new file mode 100644 index 0000000000000..acbf426291274 --- /dev/null +++ "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.go" @@ -0,0 +1,16 @@ +func minNumBooths(demand []string) (ans int) { + cnt := [26]int{} + for _, s := range demand { + for _, c := range s { + if cnt[c-'a'] > 0 { + cnt[c-'a']-- + } else { + ans++ + } + } + for _, c := range s { + cnt[c-'a']++ + } + } + return +} \ No newline at end of file diff --git "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.java" "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.java" new file mode 100644 index 0000000000000..79a9e772ac8c7 --- /dev/null +++ "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.java" @@ -0,0 +1,21 @@ +class Solution { + public int minNumBooths(String[] demand) { + int[] cnt = new int[26]; + int ans = 0; + for (var s : demand) { + int m = s.length(); + for (int i = 0; i < m; ++i) { + int j = s.charAt(i) - 'a'; + if (cnt[j] > 0) { + --cnt[j]; + } else { + ++ans; + } + } + for (int i = 0; i < m; ++i) { + ++cnt[s.charAt(i) - 'a']; + } + } + return ans; + } +} \ No newline at end of file diff --git "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.py" "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.py" new file mode 100644 index 0000000000000..90b9b6063213c --- /dev/null +++ "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/Solution.py" @@ -0,0 +1,13 @@ +class Solution: + def minNumBooths(self, demand: List[str]) -> int: + cnt = Counter() + ans = 0 + for s in demand: + for c in s: + if cnt[c]: + cnt[c] -= 1 + else: + ans += 1 + for c in s: + cnt[c] += 1 + return ans From 9b8e63987207531b6ee78ce4dcd8c3a5fb05cb8c Mon Sep 17 00:00:00 2001 From: thinkasany <117748716+thinkasany@users.noreply.github.com> Date: Fri, 24 Mar 2023 00:01:43 +0800 Subject: [PATCH 14/16] feat: add solutions to lc problem: No.1002 (#948) --- .../1002.Find Common Characters/README.md | 30 +++++++++++++++++++ .../1002.Find Common Characters/README_EN.md | 24 +++++++++++++++ .../1002.Find Common Characters/Solution.ts | 19 ++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 solution/1000-1099/1002.Find Common Characters/Solution.ts diff --git a/solution/1000-1099/1002.Find Common Characters/README.md b/solution/1000-1099/1002.Find Common Characters/README.md index 3ad1ea50d8716..9223345fb06d8 100644 --- a/solution/1000-1099/1002.Find Common Characters/README.md +++ b/solution/1000-1099/1002.Find Common Characters/README.md @@ -155,4 +155,34 @@ func min(a, b int) int { } ``` +### **TypeScript** + +```ts +function commonChars(words: string[]): string[] { + const freq: number[] = new Array(26).fill(10000); + for (const word of words) { + const t: number[] = new Array(26).fill(0); + for (const c of word.split('')) { + ++t[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (let i = 0; i < 26; ++i) { + freq[i] = Math.min(freq[i], t[i]); + } + } + const res: string[] = []; + for (let i = 0; i < 26; ++i) { + while (freq[i]-- > 0) { + res.push(String.fromCharCode(i + 'a'.charCodeAt(0))); + } + } + return res; +} +``` + +### **...** + +``` + +``` + diff --git a/solution/1000-1099/1002.Find Common Characters/README_EN.md b/solution/1000-1099/1002.Find Common Characters/README_EN.md index 5a511e79472df..079e1b89ff5b6 100644 --- a/solution/1000-1099/1002.Find Common Characters/README_EN.md +++ b/solution/1000-1099/1002.Find Common Characters/README_EN.md @@ -132,6 +132,30 @@ func min(a, b int) int { } ``` +### **TypeScript** + +```ts +function commonChars(words: string[]): string[] { + const freq: number[] = new Array(26).fill(10000); + for (const word of words) { + const t: number[] = new Array(26).fill(0); + for (const c of word.split('')) { + ++t[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (let i = 0; i < 26; ++i) { + freq[i] = Math.min(freq[i], t[i]); + } + } + const res: string[] = []; + for (let i = 0; i < 26; ++i) { + while (freq[i]-- > 0) { + res.push(String.fromCharCode(i + 'a'.charCodeAt(0))); + } + } + return res; +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1002.Find Common Characters/Solution.ts b/solution/1000-1099/1002.Find Common Characters/Solution.ts new file mode 100644 index 0000000000000..1b58e342a453a --- /dev/null +++ b/solution/1000-1099/1002.Find Common Characters/Solution.ts @@ -0,0 +1,19 @@ +function commonChars(words: string[]): string[] { + const freq: number[] = new Array(26).fill(10000); + for (const word of words) { + const t: number[] = new Array(26).fill(0); + for (const c of word.split('')) { + ++t[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (let i = 0; i < 26; ++i) { + freq[i] = Math.min(freq[i], t[i]); + } + } + const res: string[] = []; + for (let i = 0; i < 26; ++i) { + while (freq[i]-- > 0) { + res.push(String.fromCharCode(i + 'a'.charCodeAt(0))); + } + } + return res; +} From 028a87bebfa3a8982b8213e5eddb32b22e307f78 Mon Sep 17 00:00:00 2001 From: Yang Libin Date: Fri, 24 Mar 2023 09:16:57 +0800 Subject: [PATCH 15/16] feat: update solutions to lc problem: No.1032 (#949) No.1032.Stream of Characters --- .../1032.Stream of Characters/README.md | 41 ++++++++++++------- .../1032.Stream of Characters/README_EN.md | 30 +++++++++----- .../1032.Stream of Characters/Solution.cpp | 17 +++++--- .../1032.Stream of Characters/Solution.py | 13 +++--- 4 files changed, 64 insertions(+), 37 deletions(-) diff --git a/solution/1000-1099/1032.Stream of Characters/README.md b/solution/1000-1099/1032.Stream of Characters/README.md index 6be7ef7388678..46c72c20a9b88 100644 --- a/solution/1000-1099/1032.Stream of Characters/README.md +++ b/solution/1000-1099/1032.Stream of Characters/README.md @@ -62,13 +62,16 @@ streamChecker.query("l"); // 返回 True ,因为 'kl' 在 words 中 **方法一:前缀树** -构建前缀树,每个节点保存一个字符,从根节点开始,每次遍历到一个字符,就将其加入到当前节点的子节点中,同时将当前节点的 `isEnd` 标记为 `true`。当遍历到字符串的末尾时,将当前节点的 `isEnd` 标记为 `true`。 +我们可以根据初始化时的字符串数组 $words$ 构建前缀树,前缀树的每个节点包含两个属性: -查询时,从根节点开始,每次遍历到一个字符,就将其加入到当前节点的子节点中,同时将当前节点的 `isEnd` 标记为 `true`。当遍历到字符串的末尾时,将当前节点的 `isEnd` 标记为 `true`。 +- `children`:指向 $26$ 个字母的指针数组,用于存储当前节点的子节点。 +- `is_end`:标记当前节点是否为某个字符串的结尾。 -对于本题,我们采用**字符串的反序**来构建前缀树,这样在查询时,只需要从根节点开始,遍历到当前字符即可,不需要遍历到字符串的末尾。 +在构造函数中,我们遍历字符串数组 $words$,对于每个字符串 $w$,我们将其反转后,逐个字符插入到前缀树中,插入结束后,将当前节点的 `is_end` 标记为 `true`。 -初始化前缀树的时间复杂度为 $O(n)$,其中 $n$ 为 `words` 所有字符总数。单次查询的时间复杂度为 $O(m)$,其中 $m$ 为 `words` 中单词的最大长度。 +在 `query` 函数中,我们将当前字符 $c$ 加入到字符流中,然后从后往前遍历字符流,对于每个字符 $c$,我们在前缀树中查找是否存在以 $c$ 为结尾的字符串,如果存在,返回 `true`,否则返回 `false`。注意到 $words$ 中的字符串长度不超过 $200$,因此查询时最多只需要遍历 $200$ 个字符。 + +时间复杂度方面,构造函数的时间复杂度为 $O(L)$,而 `query` 函数的时间复杂度为 $O(M)$。其中 $L$ 为字符串数组 $words$ 中所有字符串的长度之和,而 $M$ 为字符串数组 $words$ 中字符串的最大长度。空间复杂度 $O(L)$。 @@ -82,7 +85,7 @@ class Trie: self.children = [None] * 26 self.is_end = False - def insert(self, w): + def insert(self, w: str): node = self for c in w[::-1]: idx = ord(c) - ord('a') @@ -91,7 +94,7 @@ class Trie: node = node.children[idx] node.is_end = True - def search(self, w): + def search(self, w: List[str]) -> bool: node = self for c in w[::-1]: idx = ord(c) - ord('a') @@ -107,13 +110,14 @@ class StreamChecker: def __init__(self, words: List[str]): self.trie = Trie() - self.s = [] + self.cs = [] + self.limit = 201 for w in words: self.trie.insert(w) def query(self, letter: str) -> bool: - self.s.append(letter) - return self.trie.search(self.s[-201:]) + self.cs.append(letter) + return self.trie.search(self.cs[-self.limit:]) # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) @@ -190,14 +194,16 @@ public: Trie() : children(26) - , isEnd(false) { } + , isEnd(false) {} void insert(string& w) { Trie* node = this; reverse(w.begin(), w.end()); - for (char c : w) { + for (char& c : w) { int idx = c - 'a'; - if (!node->children[idx]) node->children[idx] = new Trie(); + if (!node->children[idx]) { + node->children[idx] = new Trie(); + } node = node->children[idx]; } node->isEnd = true; @@ -207,9 +213,13 @@ public: Trie* node = this; for (int i = w.size() - 1, j = 0; ~i && j < 201; --i, ++j) { int idx = w[i] - 'a'; - if (!node->children[idx]) return false; + if (!node->children[idx]) { + return false; + } node = node->children[idx]; - if (node->isEnd) return true; + if (node->isEnd) { + return true; + } } return false; } @@ -219,8 +229,9 @@ class StreamChecker { public: Trie* trie = new Trie(); string s; + StreamChecker(vector& words) { - for (string& w : words) { + for (auto& w : words) { trie->insert(w); } } diff --git a/solution/1000-1099/1032.Stream of Characters/README_EN.md b/solution/1000-1099/1032.Stream of Characters/README_EN.md index a4c1a94b3044f..a671f1bc333c0 100644 --- a/solution/1000-1099/1032.Stream of Characters/README_EN.md +++ b/solution/1000-1099/1032.Stream of Characters/README_EN.md @@ -64,7 +64,7 @@ class Trie: self.children = [None] * 26 self.is_end = False - def insert(self, w): + def insert(self, w: str): node = self for c in w[::-1]: idx = ord(c) - ord('a') @@ -73,7 +73,7 @@ class Trie: node = node.children[idx] node.is_end = True - def search(self, w): + def search(self, w: List[str]) -> bool: node = self for c in w[::-1]: idx = ord(c) - ord('a') @@ -89,13 +89,14 @@ class StreamChecker: def __init__(self, words: List[str]): self.trie = Trie() - self.s = [] + self.cs = [] + self.limit = 201 for w in words: self.trie.insert(w) def query(self, letter: str) -> bool: - self.s.append(letter) - return self.trie.search(self.s[-201:]) + self.cs.append(letter) + return self.trie.search(self.cs[-self.limit:]) # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) @@ -170,14 +171,16 @@ public: Trie() : children(26) - , isEnd(false) { } + , isEnd(false) {} void insert(string& w) { Trie* node = this; reverse(w.begin(), w.end()); - for (char c : w) { + for (char& c : w) { int idx = c - 'a'; - if (!node->children[idx]) node->children[idx] = new Trie(); + if (!node->children[idx]) { + node->children[idx] = new Trie(); + } node = node->children[idx]; } node->isEnd = true; @@ -187,9 +190,13 @@ public: Trie* node = this; for (int i = w.size() - 1, j = 0; ~i && j < 201; --i, ++j) { int idx = w[i] - 'a'; - if (!node->children[idx]) return false; + if (!node->children[idx]) { + return false; + } node = node->children[idx]; - if (node->isEnd) return true; + if (node->isEnd) { + return true; + } } return false; } @@ -199,8 +206,9 @@ class StreamChecker { public: Trie* trie = new Trie(); string s; + StreamChecker(vector& words) { - for (string& w : words) { + for (auto& w : words) { trie->insert(w); } } diff --git a/solution/1000-1099/1032.Stream of Characters/Solution.cpp b/solution/1000-1099/1032.Stream of Characters/Solution.cpp index 0cc62b733c830..2bcd06bd18cb4 100644 --- a/solution/1000-1099/1032.Stream of Characters/Solution.cpp +++ b/solution/1000-1099/1032.Stream of Characters/Solution.cpp @@ -10,9 +10,11 @@ class Trie { void insert(string& w) { Trie* node = this; reverse(w.begin(), w.end()); - for (char c : w) { + for (char& c : w) { int idx = c - 'a'; - if (!node->children[idx]) node->children[idx] = new Trie(); + if (!node->children[idx]) { + node->children[idx] = new Trie(); + } node = node->children[idx]; } node->isEnd = true; @@ -22,9 +24,13 @@ class Trie { Trie* node = this; for (int i = w.size() - 1, j = 0; ~i && j < 201; --i, ++j) { int idx = w[i] - 'a'; - if (!node->children[idx]) return false; + if (!node->children[idx]) { + return false; + } node = node->children[idx]; - if (node->isEnd) return true; + if (node->isEnd) { + return true; + } } return false; } @@ -34,8 +40,9 @@ class StreamChecker { public: Trie* trie = new Trie(); string s; + StreamChecker(vector& words) { - for (string& w : words) { + for (auto& w : words) { trie->insert(w); } } diff --git a/solution/1000-1099/1032.Stream of Characters/Solution.py b/solution/1000-1099/1032.Stream of Characters/Solution.py index 1e785dbd7c274..ef978585efaf1 100644 --- a/solution/1000-1099/1032.Stream of Characters/Solution.py +++ b/solution/1000-1099/1032.Stream of Characters/Solution.py @@ -3,7 +3,7 @@ def __init__(self): self.children = [None] * 26 self.is_end = False - def insert(self, w): + def insert(self, w: str): node = self for c in w[::-1]: idx = ord(c) - ord('a') @@ -12,7 +12,7 @@ def insert(self, w): node = node.children[idx] node.is_end = True - def search(self, w): + def search(self, w: List[str]) -> bool: node = self for c in w[::-1]: idx = ord(c) - ord('a') @@ -25,16 +25,17 @@ def search(self, w): class StreamChecker: + def __init__(self, words: List[str]): self.trie = Trie() - self.s = [] + self.cs = [] + self.limit = 201 for w in words: self.trie.insert(w) def query(self, letter: str) -> bool: - self.s.append(letter) - return self.trie.search(self.s[-201:]) - + self.cs.append(letter) + return self.trie.search(self.cs[-self.limit:]) # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) From 3041b33d1dc3e29fd7ad89cf5d0d7a3a1e60189b Mon Sep 17 00:00:00 2001 From: Yang Libin Date: Fri, 24 Mar 2023 12:20:02 +0800 Subject: [PATCH 16/16] feat: add solutions to lc problem: No.2599 (#950) --- solution/0200-0299/0263.Ugly Number/README.md | 2 +- .../README.md | 2 +- .../README_EN.md | 2 +- .../0605.Can Place Flowers/README_EN.md | 2 +- .../0665.Non-decreasing Array/README_EN.md | 2 +- .../1406.Stone Game III/README_EN.md | 4 +- .../1630.Arithmetic Subarrays/README.md | 8 +- .../1630.Arithmetic Subarrays/README_EN.md | 2 +- .../README.md | 14 +- .../README_EN.md | 2 + .../1943.Describe the Painting/README.md | 17 +- .../README_EN.md | 10 +- .../README.md | 187 ++++++++++++++++++ .../README_EN.md | 171 ++++++++++++++++ .../Solution.cpp | 20 ++ .../Solution.go | 26 +++ .../Solution.java | 18 ++ .../Solution.py | 12 ++ .../Solution.ts | 16 ++ solution/README.md | 27 +-- solution/README_EN.md | 25 +-- solution/summary.md | 3 +- solution/summary_en.md | 1 + 23 files changed, 516 insertions(+), 57 deletions(-) create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.cpp create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.go create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.java create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.py create mode 100644 solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.ts diff --git a/solution/0200-0299/0263.Ugly Number/README.md b/solution/0200-0299/0263.Ugly Number/README.md index 2080b6f45bc06..1b160e0f81161 100644 --- a/solution/0200-0299/0263.Ugly Number/README.md +++ b/solution/0200-0299/0263.Ugly Number/README.md @@ -31,7 +31,7 @@
 输入:n = 14
 输出:false
-解释:14 不是丑数,因为它包含了另外一个质因数 7。
+解释:14 不是丑数,因为它包含了另外一个质因数 7 

 

diff --git a/solution/0300-0399/0387.First Unique Character in a String/README.md b/solution/0300-0399/0387.First Unique Character in a String/README.md index 82ec83e524ffa..70818329b69fd 100644 --- a/solution/0300-0399/0387.First Unique Character in a String/README.md +++ b/solution/0300-0399/0387.First Unique Character in a String/README.md @@ -188,7 +188,7 @@ class Solution { return -1; } } -``` +``` ### **...** diff --git a/solution/0300-0399/0387.First Unique Character in a String/README_EN.md b/solution/0300-0399/0387.First Unique Character in a String/README_EN.md index e87f4b0b42d6a..7f4b6c8ce1837 100644 --- a/solution/0300-0399/0387.First Unique Character in a String/README_EN.md +++ b/solution/0300-0399/0387.First Unique Character in a String/README_EN.md @@ -157,7 +157,7 @@ class Solution { return -1; } } -``` +``` ### **...** diff --git a/solution/0600-0699/0605.Can Place Flowers/README_EN.md b/solution/0600-0699/0605.Can Place Flowers/README_EN.md index ffb414f3101b4..6770c350022e6 100644 --- a/solution/0600-0699/0605.Can Place Flowers/README_EN.md +++ b/solution/0600-0699/0605.Can Place Flowers/README_EN.md @@ -6,7 +6,7 @@

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

-

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

+

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

 

Example 1:

diff --git a/solution/0600-0699/0665.Non-decreasing Array/README_EN.md b/solution/0600-0699/0665.Non-decreasing Array/README_EN.md index 28b39cb2b998f..cff20c9edeeff 100644 --- a/solution/0600-0699/0665.Non-decreasing Array/README_EN.md +++ b/solution/0600-0699/0665.Non-decreasing Array/README_EN.md @@ -77,7 +77,7 @@ class Solution { } return true; } - + private boolean isSorted(int[] nums) { for (int i = 0; i < nums.length - 1; ++i) { if (nums[i] > nums[i + 1]) { diff --git a/solution/1400-1499/1406.Stone Game III/README_EN.md b/solution/1400-1499/1406.Stone Game III/README_EN.md index 94789f20eefd9..1f921ea56b771 100644 --- a/solution/1400-1499/1406.Stone Game III/README_EN.md +++ b/solution/1400-1499/1406.Stone Game III/README_EN.md @@ -83,7 +83,7 @@ class Solution { private int n; private int[] s; private Integer[] f; - + public String stoneGameIII(int[] stoneValue) { n = stoneValue.length; s = new int[n + 1]; @@ -95,7 +95,7 @@ class Solution { int b = s[n] - a; return a == b ? "Tie" : a > b ? "Alice" : "Bob"; } - + private int dfs(int i) { if (i >= n) { return 0; diff --git a/solution/1600-1699/1630.Arithmetic Subarrays/README.md b/solution/1600-1699/1630.Arithmetic Subarrays/README.md index 93c9d2b17b391..b88b9a31e52a3 100644 --- a/solution/1600-1699/1630.Arithmetic Subarrays/README.md +++ b/solution/1600-1699/1630.Arithmetic Subarrays/README.md @@ -63,9 +63,9 @@ 函数 $check(nums, l, r)$ 的实现逻辑如下: -- 首先,我们计算子数组的长度 $n = r - l + 1$,并将子数组中的元素放入集合 $s$ 中,方便后续的查找; -- 然后,我们获取子数组中的最小值 $a_1$ 和最大值 $a_n$,如果 $a_n - a_1$ 不能被 $n - 1$ 整除,那么子数组不可能形成等差数列,直接返回 $false$;否则,我们计算等差数列的公差 $d = \frac{a_n - a_1}{n - 1}$; -- 接下来从 $a_1$ 开始,依次计算等差数列中第 $i$ 项元素,如果第 $i$ 项元素 $a_1 + (i - 1) \times d$ 不在集合 $s$ 中,那么子数组不可能形成等差数列,直接返回 $false$;否则,当我们遍历完所有的元素,说明子数组可以重新排列形成等差数列,返回 $true$。 +- 首先,我们计算子数组的长度 $n = r - l + 1$,并将子数组中的元素放入集合 $s$ 中,方便后续的查找; +- 然后,我们获取子数组中的最小值 $a_1$ 和最大值 $a_n$,如果 $a_n - a_1$ 不能被 $n - 1$ 整除,那么子数组不可能形成等差数列,直接返回 $false$;否则,我们计算等差数列的公差 $d = \frac{a_n - a_1}{n - 1}$; +- 接下来从 $a_1$ 开始,依次计算等差数列中第 $i$ 项元素,如果第 $i$ 项元素 $a_1 + (i - 1) \times d$ 不在集合 $s$ 中,那么子数组不可能形成等差数列,直接返回 $false$;否则,当我们遍历完所有的元素,说明子数组可以重新排列形成等差数列,返回 $true$。 在主函数中,我们遍历所有的查询,对于每个查询 $l[i]$ 和 $r[i]$,我们调用函数 $check(nums, l[i], r[i])$ 判断子数组是否可以重新排列形成等差数列,将结果存入答案数组中。 @@ -86,7 +86,7 @@ class Solution: a1, an = min(nums[l: l + n]), max(nums[l: l + n]) d, mod = divmod(an - a1, n - 1) return mod == 0 and all((a1 + (i - 1) * d) in s for i in range(1, n)) - + return [check(nums, left, right) for left, right in zip(l, r)] ``` diff --git a/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md b/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md index a741ff4b4e8a3..fb4e6e575b961 100644 --- a/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md +++ b/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md @@ -68,7 +68,7 @@ class Solution: a1, an = min(nums[l: l + n]), max(nums[l: l + n]) d, mod = divmod(an - a1, n - 1) return mod == 0 and all((a1 + (i - 1) * d) in s for i in range(1, n)) - + return [check(nums, left, right) for left, right in zip(l, r)] ``` diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md b/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md index 8e601085ec693..c226231892fd9 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md @@ -6,15 +6,15 @@ -

给你两个字符串 s 和 t ,请你找出 s 中的非空子串的数目,这些子串满足替换 一个不同字符 以后,是 t 串的子串。换言之,请你找到 s 和 t 串中 恰好 只有一个字符不同的子字符串对的数目。

+

给你两个字符串 s 和 t ,请你找出 s 中的非空子串的数目,这些子串满足替换 一个不同字符 以后,是 t 串的子串。换言之,请你找到 s 和 t 串中 恰好 只有一个字符不同的子字符串对的数目。

-

比方说, "computer" 和 "computation" 加粗部分只有一个字符不同: 'e'/'a' ,所以这一对子字符串会给答案加 1 。

+

比方说, "computer" and "computation" 只有一个字符不同: 'e'/'a' ,所以这一对子字符串会给答案加 1 。

请你返回满足上述条件的不同子字符串对数目。

-

一个 子字符串 是一个字符串中连续的字符。

+

一个 子字符串 是一个字符串中连续的字符。

-

 

+

 

示例 1:

@@ -57,13 +57,13 @@ 输出:10 -

 

+

 

提示:

    -
  • 1 <= s.length, t.length <= 100
  • -
  • s 和 t 都只包含小写英文字母。
  • +
  • 1 <= s.length, t.length <= 100
  • +
  • s 和 t 都只包含小写英文字母。
## 解法 diff --git a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md index a9ff29d3ee201..c1482b7c67db1 100644 --- a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md +++ b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md @@ -10,10 +10,12 @@
  • Take any bag of balls and divide it into two new bags with a positive number of balls. +
    • For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.
  • +

Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.

diff --git a/solution/1900-1999/1943.Describe the Painting/README.md b/solution/1900-1999/1943.Describe the Painting/README.md index 8684e3b9331ba..25ae959d87698 100644 --- a/solution/1900-1999/1943.Describe the Painting/README.md +++ b/solution/1900-1999/1943.Describe the Painting/README.md @@ -36,17 +36,19 @@

 

示例 1:

- -
输入:segments = [[1,4,5],[4,7,7],[1,7,9]]
+
+
+输入:segments = [[1,4,5],[4,7,7],[1,7,9]]
 输出:[[1,4,14],[4,7,16]]
-解释:绘画借故偶可以表示为:
+解释:绘画结果可以表示为:
 - [1,4) 颜色为 {5,9} (和为 14),分别来自第一和第二个线段。
 - [4,7) 颜色为 {7,9} (和为 16),分别来自第二和第三个线段。
 

示例 2:

- -
输入:segments = [[1,7,9],[6,8,15],[8,10,7]]
+
+
+输入:segments = [[1,7,9],[6,8,15],[8,10,7]]
 输出:[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]
 解释:绘画结果可以以表示为:
 - [1,6) 颜色为 9 ,来自第一个线段。
@@ -56,8 +58,9 @@
 

示例 3:

- -
输入:segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]
+
+
+输入:segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]
 输出:[[1,4,12],[4,7,12]]
 解释:绘画结果可以表示为:
 - [1,4) 颜色为 {5,7} (和为 12),分别来自第一和第二个线段。
diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md b/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md
index 55bc3dad03783..13c9e63f4a373 100644
--- a/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md	
+++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md	
@@ -4,7 +4,7 @@
 
 ## Description
 
-

You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers.

+

You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where poeple[i] is the time that the ith person will arrive to see the flowers.

Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.

@@ -12,7 +12,7 @@

Example 1:

-Input: flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]
+Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11]
 Output: [1,2,2,2]
 Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
 For each person, we return the number of flowers in full bloom during their arrival.
@@ -21,7 +21,7 @@ For each person, we return the number of flowers in full bloom during their arri
 

Example 2:

-Input: flowers = [[1,10],[3,3]], persons = [3,3,2]
+Input: flowers = [[1,10],[3,3]], poeple = [3,3,2]
 Output: [2,2,1]
 Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
 For each person, we return the number of flowers in full bloom during their arrival.
@@ -34,8 +34,8 @@ For each person, we return the number of flowers in full bloom during their arri
 	
  • 1 <= flowers.length <= 5 * 104
  • flowers[i].length == 2
  • 1 <= starti <= endi <= 109
  • -
  • 1 <= persons.length <= 5 * 104
  • -
  • 1 <= persons[i] <= 109
  • +
  • 1 <= people.length <= 5 * 104
  • +
  • 1 <= people[i] <= 109
  • ## Solutions diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md new file mode 100644 index 0000000000000..5f8b656d4d1a2 --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md @@ -0,0 +1,187 @@ +# [2599. Make the Prefix Sum Non-negative](https://leetcode.cn/problems/make-the-prefix-sum-non-negative) + +[English Version](/solution/2500-2599/2599.Make%20the%20Prefix%20Sum%20Non-negative/README_EN.md) + +## 题目描述 + + + +

    You are given a 0-indexed integer array nums. You can apply the following operation any number of times:

    + +
      +
    • Pick any element from nums and put it at the end of nums.
    • +
    + +

    The prefix sum array of nums is an array prefix of the same length as nums such that prefix[i] is the sum of all the integers nums[j] where j is in the inclusive range [0, i].

    + +

    Return the minimum number of operations such that the prefix sum array does not contain negative integers. The test cases are generated such that it is always possible to make the prefix sum array non-negative.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,3,-5,4]
    +Output: 0
    +Explanation: we do not need to do any operations.
    +The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,-5,-2,6]
    +Output: 1
    +Explanation: we can do one operation on index 1.
    +The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -109 <= nums[i] <= 109
    • +
    + +## 解法 + + + +**方法一:贪心 + 优先队列(小根堆)** + +我们用变量 $s$ 记录当前数组的前缀和。 + +遍历数组 $nums$,将当前元素 $x$ 加入前缀和 $s$ 中,如果 $x$ 为负数,则将 $x$ 加入小根堆中。如果此时 $s$ 为负数,我们贪心地取出最小的负数,将其从 $s$ 中减去,同时将答案加一。最终返回答案即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +### **Python3** + + + +```python +class Solution: + def makePrefSumNonNegative(self, nums: List[int]) -> int: + h = [] + ans = s = 0 + for x in nums: + s += x + if x < 0: + heappush(h, x) + while s < 0: + s -= heappop(h) + ans += 1 + return ans +``` + +### **Java** + + + +```java +class Solution { + public int makePrefSumNonNegative(int[] nums) { + PriorityQueue pq = new PriorityQueue<>(); + int ans = 0; + long s = 0; + for (int x : nums) { + s += x; + if (x < 0) { + pq.offer(x); + } + while (s < 0) { + s -= pq.poll(); + ++ans; + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int makePrefSumNonNegative(vector& nums) { + priority_queue, greater> pq; + int ans = 0; + long long s = 0; + for (int& x : nums) { + s += x; + if (x < 0) { + pq.push(x); + } + while (s < 0) { + s -= pq.top(); + pq.pop(); + ++ans; + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func makePrefSumNonNegative(nums []int) (ans int) { + pq := hp{} + s := 0 + for _, x := range nums { + s += x + if x < 0 { + heap.Push(&pq, x) + } + for s < 0 { + s -= heap.Pop(&pq).(int) + ans++ + } + } + return ans +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } +func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() interface{} { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v +} +``` + +### **TypeScript** + +```ts +function makePrefSumNonNegative(nums: number[]): number { + const pq = new MinPriorityQueue(); + let ans = 0; + let s = 0; + for (const x of nums) { + s += x; + if (x < 0) { + pq.enqueue(x); + } + while (s < 0) { + s -= pq.dequeue().element; + ++ans; + } + } + return ans; +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md new file mode 100644 index 0000000000000..3992bba412709 --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md @@ -0,0 +1,171 @@ +# [2599. Make the Prefix Sum Non-negative](https://leetcode.com/problems/make-the-prefix-sum-non-negative) + +[中文文档](/solution/2500-2599/2599.Make%20the%20Prefix%20Sum%20Non-negative/README.md) + +## Description + +

    You are given a 0-indexed integer array nums. You can apply the following operation any number of times:

    + +
      +
    • Pick any element from nums and put it at the end of nums.
    • +
    + +

    The prefix sum array of nums is an array prefix of the same length as nums such that prefix[i] is the sum of all the integers nums[j] where j is in the inclusive range [0, i].

    + +

    Return the minimum number of operations such that the prefix sum array does not contain negative integers. The test cases are generated such that it is always possible to make the prefix sum array non-negative.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,3,-5,4]
    +Output: 0
    +Explanation: we do not need to do any operations.
    +The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,-5,-2,6]
    +Output: 1
    +Explanation: we can do one operation on index 1.
    +The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -109 <= nums[i] <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def makePrefSumNonNegative(self, nums: List[int]) -> int: + h = [] + ans = s = 0 + for x in nums: + s += x + if x < 0: + heappush(h, x) + while s < 0: + s -= heappop(h) + ans += 1 + return ans +``` + +### **Java** + +```java +class Solution { + public int makePrefSumNonNegative(int[] nums) { + PriorityQueue pq = new PriorityQueue<>(); + int ans = 0; + long s = 0; + for (int x : nums) { + s += x; + if (x < 0) { + pq.offer(x); + } + while (s < 0) { + s -= pq.poll(); + ++ans; + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int makePrefSumNonNegative(vector& nums) { + priority_queue, greater> pq; + int ans = 0; + long long s = 0; + for (int& x : nums) { + s += x; + if (x < 0) { + pq.push(x); + } + while (s < 0) { + s -= pq.top(); + pq.pop(); + ++ans; + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func makePrefSumNonNegative(nums []int) (ans int) { + pq := hp{} + s := 0 + for _, x := range nums { + s += x + if x < 0 { + heap.Push(&pq, x) + } + for s < 0 { + s -= heap.Pop(&pq).(int) + ans++ + } + } + return ans +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } +func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() interface{} { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v +} +``` + +### **TypeScript** + +```ts +function makePrefSumNonNegative(nums: number[]): number { + const pq = new MinPriorityQueue(); + let ans = 0; + let s = 0; + for (const x of nums) { + s += x; + if (x < 0) { + pq.enqueue(x); + } + while (s < 0) { + s -= pq.dequeue().element; + ++ans; + } + } + return ans; +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.cpp b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.cpp new file mode 100644 index 0000000000000..b27db89ff165a --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int makePrefSumNonNegative(vector& nums) { + priority_queue, greater> pq; + int ans = 0; + long long s = 0; + for (int& x : nums) { + s += x; + if (x < 0) { + pq.push(x); + } + while (s < 0) { + s -= pq.top(); + pq.pop(); + ++ans; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.go b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.go new file mode 100644 index 0000000000000..230c5a0abc1b6 --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.go @@ -0,0 +1,26 @@ +func makePrefSumNonNegative(nums []int) (ans int) { + pq := hp{} + s := 0 + for _, x := range nums { + s += x + if x < 0 { + heap.Push(&pq, x) + } + for s < 0 { + s -= heap.Pop(&pq).(int) + ans++ + } + } + return ans +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } +func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() interface{} { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v +} \ No newline at end of file diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.java b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.java new file mode 100644 index 0000000000000..af23ee619e462 --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.java @@ -0,0 +1,18 @@ +class Solution { + public int makePrefSumNonNegative(int[] nums) { + PriorityQueue pq = new PriorityQueue<>(); + int ans = 0; + long s = 0; + for (int x : nums) { + s += x; + if (x < 0) { + pq.offer(x); + } + while (s < 0) { + s -= pq.poll(); + ++ans; + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.py b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.py new file mode 100644 index 0000000000000..a5b3482a234cc --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.py @@ -0,0 +1,12 @@ +class Solution: + def makePrefSumNonNegative(self, nums: List[int]) -> int: + h = [] + ans = s = 0 + for x in nums: + s += x + if x < 0: + heappush(h, x) + while s < 0: + s -= heappop(h) + ans += 1 + return ans diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.ts b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.ts new file mode 100644 index 0000000000000..9f339be7f1849 --- /dev/null +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/Solution.ts @@ -0,0 +1,16 @@ +function makePrefSumNonNegative(nums: number[]): number { + const pq = new MinPriorityQueue(); + let ans = 0; + let s = 0; + for (const x of nums) { + s += x; + if (x < 0) { + pq.enqueue(x); + } + while (s < 0) { + s -= pq.dequeue().element; + ++ans; + } + } + return ans; +} diff --git a/solution/README.md b/solution/README.md index 00720e83b7e9e..e83bf44ebc4fd 100644 --- a/solution/README.md +++ b/solution/README.md @@ -33,7 +33,7 @@ | 0020 | [有效的括号](/solution/0000-0099/0020.Valid%20Parentheses/README.md) | `栈`,`字符串` | 简单 | | | 0021 | [合并两个有序链表](/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/README.md) | `递归`,`链表` | 简单 | | | 0022 | [括号生成](/solution/0000-0099/0022.Generate%20Parentheses/README.md) | `字符串`,`动态规划`,`回溯` | 中等 | | -| 0023 | [合并K个升序链表](/solution/0000-0099/0023.Merge%20k%20Sorted%20Lists/README.md) | `链表`,`分治`,`堆(优先队列)`,`归并排序` | 困难 | | +| 0023 | [合并 K 个升序链表](/solution/0000-0099/0023.Merge%20k%20Sorted%20Lists/README.md) | `链表`,`分治`,`堆(优先队列)`,`归并排序` | 困难 | | | 0024 | [两两交换链表中的节点](/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/README.md) | `递归`,`链表` | 中等 | | | 0025 | [K 个一组翻转链表](/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/README.md) | `递归`,`链表` | 困难 | | | 0026 | [删除有序数组中的重复项](/solution/0000-0099/0026.Remove%20Duplicates%20from%20Sorted%20Array/README.md) | `数组`,`双指针` | 简单 | | @@ -974,7 +974,7 @@ | 0961 | [在长度 2N 的数组中找出重复 N 次的元素](/solution/0900-0999/0961.N-Repeated%20Element%20in%20Size%202N%20Array/README.md) | `数组`,`哈希表` | 简单 | 第 116 场周赛 | | 0962 | [最大宽度坡](/solution/0900-0999/0962.Maximum%20Width%20Ramp/README.md) | `栈`,`数组`,`单调栈` | 中等 | 第 116 场周赛 | | 0963 | [最小面积矩形 II](/solution/0900-0999/0963.Minimum%20Area%20Rectangle%20II/README.md) | `几何`,`数组`,`数学` | 中等 | 第 116 场周赛 | -| 0964 | [表示数字的最少运算符](/solution/0900-0999/0964.Least%20Operators%20to%20Express%20Number/README.md) | `数学`,`动态规划` | 困难 | 第 116 场周赛 | +| 0964 | [表示数字的最少运算符](/solution/0900-0999/0964.Least%20Operators%20to%20Express%20Number/README.md) | `记忆化搜索`,`数学`,`动态规划` | 困难 | 第 116 场周赛 | | 0965 | [单值二叉树](/solution/0900-0999/0965.Univalued%20Binary%20Tree/README.md) | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | 第 117 场周赛 | | 0966 | [元音拼写检查器](/solution/0900-0999/0966.Vowel%20Spellchecker/README.md) | `数组`,`哈希表`,`字符串` | 中等 | 第 117 场周赛 | | 0967 | [连续差相同的数字](/solution/0900-0999/0967.Numbers%20With%20Same%20Consecutive%20Differences/README.md) | `广度优先搜索`,`回溯` | 中等 | 第 117 场周赛 | @@ -1697,7 +1697,7 @@ | 1684 | [统计一致字符串的数目](/solution/1600-1699/1684.Count%20the%20Number%20of%20Consistent%20Strings/README.md) | `位运算`,`数组`,`哈希表`,`字符串` | 简单 | 第 41 场双周赛 | | 1685 | [有序数组中差绝对值之和](/solution/1600-1699/1685.Sum%20of%20Absolute%20Differences%20in%20a%20Sorted%20Array/README.md) | `数组`,`数学`,`前缀和` | 中等 | 第 41 场双周赛 | | 1686 | [石子游戏 VI](/solution/1600-1699/1686.Stone%20Game%20VI/README.md) | `贪心`,`数组`,`数学`,`博弈`,`排序`,`堆(优先队列)` | 中等 | 第 41 场双周赛 | -| 1687 | [从仓库到码头运输箱子](/solution/1600-1699/1687.Delivering%20Boxes%20from%20Storage%20to%20Ports/README.md) | `线段树`,`队列`,`数组`,`动态规划`,`单调队列`,`堆(优先队列)` | 困难 | 第 41 场双周赛 | +| 1687 | [从仓库到码头运输箱子](/solution/1600-1699/1687.Delivering%20Boxes%20from%20Storage%20to%20Ports/README.md) | `线段树`,`队列`,`数组`,`动态规划`,`前缀和`,`单调队列`,`堆(优先队列)` | 困难 | 第 41 场双周赛 | | 1688 | [比赛中的配对次数](/solution/1600-1699/1688.Count%20of%20Matches%20in%20Tournament/README.md) | `数学`,`模拟` | 简单 | 第 219 场周赛 | | 1689 | [十-二进制数的最少数目](/solution/1600-1699/1689.Partitioning%20Into%20Minimum%20Number%20Of%20Deci-Binary%20Numbers/README.md) | `贪心`,`字符串` | 中等 | 第 219 场周赛 | | 1690 | [石子游戏 VII](/solution/1600-1699/1690.Stone%20Game%20VII/README.md) | `数组`,`数学`,`动态规划`,`博弈` | 中等 | 第 219 场周赛 | @@ -2582,7 +2582,7 @@ | 2569 | [更新数组后处理求和查询](/solution/2500-2599/2569.Handling%20Sum%20Queries%20After%20Update/README.md) | `线段树`,`数组` | 困难 | 第 98 场双周赛 | | 2570 | [合并两个二维数组 - 求和法](/solution/2500-2599/2570.Merge%20Two%202D%20Arrays%20by%20Summing%20Values/README.md) | `数组`,`哈希表`,`双指针` | 简单 | 第 333 场周赛 | | 2571 | [将整数减少到零需要的最少操作数](/solution/2500-2599/2571.Minimum%20Operations%20to%20Reduce%20an%20Integer%20to%200/README.md) | `贪心`,`位运算`,`动态规划` | 中等 | 第 333 场周赛 | -| 2572 | [无平方子集计数](/solution/2500-2599/2572.Count%20the%20Number%20of%20Square-Free%20Subsets/README.md) | `数组`,`数学`,`动态规划`,`状态压缩` | 中等 | 第 333 场周赛 | +| 2572 | [无平方子集计数](/solution/2500-2599/2572.Count%20the%20Number%20of%20Square-Free%20Subsets/README.md) | `位运算`,`数组`,`数学`,`动态规划`,`状态压缩` | 中等 | 第 333 场周赛 | | 2573 | [找出对应 LCP 矩阵的字符串](/solution/2500-2599/2573.Find%20the%20String%20with%20LCP/README.md) | `贪心`,`并查集`,`字符串`,`动态规划` | 困难 | 第 333 场周赛 | | 2574 | [左右元素和的差值](/solution/2500-2599/2574.Left%20and%20Right%20Sum%20Differences/README.md) | `数组`,`前缀和` | 简单 | 第 334 场周赛 | | 2575 | [找出字符串的可整除数组](/solution/2500-2599/2575.Find%20the%20Divisibility%20Array%20of%20a%20String/README.md) | `数组`,`数学`,`字符串` | 中等 | 第 334 场周赛 | @@ -2600,15 +2600,16 @@ | 2587 | [重排数组以得到最大前缀分数](/solution/2500-2599/2587.Rearrange%20Array%20to%20Maximize%20Prefix%20Score/README.md) | `贪心`,`数组`,`前缀和`,`排序` | 中等 | 第 336 场周赛 | | 2588 | [统计美丽子数组数目](/solution/2500-2599/2588.Count%20the%20Number%20of%20Beautiful%20Subarrays/README.md) | `位运算`,`数组`,`哈希表`,`前缀和` | 中等 | 第 336 场周赛 | | 2589 | [完成所有任务的最少时间](/solution/2500-2599/2589.Minimum%20Time%20to%20Complete%20All%20Tasks/README.md) | `栈`,`贪心`,`数组`,`二分查找`,`排序` | 困难 | 第 336 场周赛 | -| 2590 | [Design a Todo List](/solution/2500-2599/2590.Design%20a%20Todo%20List/README.md) | | 中等 | 🔒 | -| 2591 | [将钱分给最多的儿童](/solution/2500-2599/2591.Distribute%20Money%20to%20Maximum%20Children/README.md) | | 简单 | 第 100 场双周赛 | -| 2592 | [最大化数组的伟大值](/solution/2500-2599/2592.Maximize%20Greatness%20of%20an%20Array/README.md) | | 中等 | 第 100 场双周赛 | -| 2593 | [标记所有元素后数组的分数](/solution/2500-2599/2593.Find%20Score%20of%20an%20Array%20After%20Marking%20All%20Elements/README.md) | | 中等 | 第 100 场双周赛 | -| 2594 | [修车的最少时间](/solution/2500-2599/2594.Minimum%20Time%20to%20Repair%20Cars/README.md) | | 中等 | 第 100 场双周赛 | -| 2595 | [奇偶位数](/solution/2500-2599/2595.Number%20of%20Even%20and%20Odd%20Bits/README.md) | | 简单 | 第 337 场周赛 | -| 2596 | [检查骑士巡视方案](/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/README.md) | | 中等 | 第 337 场周赛 | -| 2597 | [美丽子集的数目](/solution/2500-2599/2597.The%20Number%20of%20Beautiful%20Subsets/README.md) | | 中等 | 第 337 场周赛 | -| 2598 | [执行操作后的最大 MEX](/solution/2500-2599/2598.Smallest%20Missing%20Non-negative%20Integer%20After%20Operations/README.md) | | 中等 | 第 337 场周赛 | +| 2590 | [Design a Todo List](/solution/2500-2599/2590.Design%20a%20Todo%20List/README.md) | `设计`,`数组`,`哈希表`,`字符串`,`排序` | 中等 | 🔒 | +| 2591 | [将钱分给最多的儿童](/solution/2500-2599/2591.Distribute%20Money%20to%20Maximum%20Children/README.md) | `贪心`,`数学` | 简单 | 第 100 场双周赛 | +| 2592 | [最大化数组的伟大值](/solution/2500-2599/2592.Maximize%20Greatness%20of%20an%20Array/README.md) | `贪心`,`数组`,`双指针`,`排序` | 中等 | 第 100 场双周赛 | +| 2593 | [标记所有元素后数组的分数](/solution/2500-2599/2593.Find%20Score%20of%20an%20Array%20After%20Marking%20All%20Elements/README.md) | `数组`,`排序`,`模拟`,`堆(优先队列)` | 中等 | 第 100 场双周赛 | +| 2594 | [修车的最少时间](/solution/2500-2599/2594.Minimum%20Time%20to%20Repair%20Cars/README.md) | `数组`,`二分查找` | 中等 | 第 100 场双周赛 | +| 2595 | [奇偶位数](/solution/2500-2599/2595.Number%20of%20Even%20and%20Odd%20Bits/README.md) | `位运算` | 简单 | 第 337 场周赛 | +| 2596 | [检查骑士巡视方案](/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/README.md) | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵`,`模拟` | 中等 | 第 337 场周赛 | +| 2597 | [美丽子集的数目](/solution/2500-2599/2597.The%20Number%20of%20Beautiful%20Subsets/README.md) | `数组`,`动态规划`,`回溯` | 中等 | 第 337 场周赛 | +| 2598 | [执行操作后的最大 MEX](/solution/2500-2599/2598.Smallest%20Missing%20Non-negative%20Integer%20After%20Operations/README.md) | `贪心`,`数组`,`哈希表`,`数学` | 中等 | 第 337 场周赛 | +| 2599 | [Make the Prefix Sum Non-negative](/solution/2500-2599/2599.Make%20the%20Prefix%20Sum%20Non-negative/README.md) | | 中等 | 🔒 | ## 版权 diff --git a/solution/README_EN.md b/solution/README_EN.md index 6dea2de360fb9..21ff9cbd9d99f 100644 --- a/solution/README_EN.md +++ b/solution/README_EN.md @@ -972,7 +972,7 @@ Press Control+F(or Command+F on the | 0961 | [N-Repeated Element in Size 2N Array](/solution/0900-0999/0961.N-Repeated%20Element%20in%20Size%202N%20Array/README_EN.md) | `Array`,`Hash Table` | Easy | Weekly Contest 116 | | 0962 | [Maximum Width Ramp](/solution/0900-0999/0962.Maximum%20Width%20Ramp/README_EN.md) | `Stack`,`Array`,`Monotonic Stack` | Medium | Weekly Contest 116 | | 0963 | [Minimum Area Rectangle II](/solution/0900-0999/0963.Minimum%20Area%20Rectangle%20II/README_EN.md) | `Geometry`,`Array`,`Math` | Medium | Weekly Contest 116 | -| 0964 | [Least Operators to Express Number](/solution/0900-0999/0964.Least%20Operators%20to%20Express%20Number/README_EN.md) | `Math`,`Dynamic Programming` | Hard | Weekly Contest 116 | +| 0964 | [Least Operators to Express Number](/solution/0900-0999/0964.Least%20Operators%20to%20Express%20Number/README_EN.md) | `Memoization`,`Math`,`Dynamic Programming` | Hard | Weekly Contest 116 | | 0965 | [Univalued Binary Tree](/solution/0900-0999/0965.Univalued%20Binary%20Tree/README_EN.md) | `Tree`,`Depth-First Search`,`Breadth-First Search`,`Binary Tree` | Easy | Weekly Contest 117 | | 0966 | [Vowel Spellchecker](/solution/0900-0999/0966.Vowel%20Spellchecker/README_EN.md) | `Array`,`Hash Table`,`String` | Medium | Weekly Contest 117 | | 0967 | [Numbers With Same Consecutive Differences](/solution/0900-0999/0967.Numbers%20With%20Same%20Consecutive%20Differences/README_EN.md) | `Breadth-First Search`,`Backtracking` | Medium | Weekly Contest 117 | @@ -1695,7 +1695,7 @@ Press Control+F(or Command+F on the | 1684 | [Count the Number of Consistent Strings](/solution/1600-1699/1684.Count%20the%20Number%20of%20Consistent%20Strings/README_EN.md) | `Bit Manipulation`,`Array`,`Hash Table`,`String` | Easy | Biweekly Contest 41 | | 1685 | [Sum of Absolute Differences in a Sorted Array](/solution/1600-1699/1685.Sum%20of%20Absolute%20Differences%20in%20a%20Sorted%20Array/README_EN.md) | `Array`,`Math`,`Prefix Sum` | Medium | Biweekly Contest 41 | | 1686 | [Stone Game VI](/solution/1600-1699/1686.Stone%20Game%20VI/README_EN.md) | `Greedy`,`Array`,`Math`,`Game Theory`,`Sorting`,`Heap (Priority Queue)` | Medium | Biweekly Contest 41 | -| 1687 | [Delivering Boxes from Storage to Ports](/solution/1600-1699/1687.Delivering%20Boxes%20from%20Storage%20to%20Ports/README_EN.md) | `Segment Tree`,`Queue`,`Array`,`Dynamic Programming`,`Monotonic Queue`,`Heap (Priority Queue)` | Hard | Biweekly Contest 41 | +| 1687 | [Delivering Boxes from Storage to Ports](/solution/1600-1699/1687.Delivering%20Boxes%20from%20Storage%20to%20Ports/README_EN.md) | `Segment Tree`,`Queue`,`Array`,`Dynamic Programming`,`Prefix Sum`,`Monotonic Queue`,`Heap (Priority Queue)` | Hard | Biweekly Contest 41 | | 1688 | [Count of Matches in Tournament](/solution/1600-1699/1688.Count%20of%20Matches%20in%20Tournament/README_EN.md) | `Math`,`Simulation` | Easy | Weekly Contest 219 | | 1689 | [Partitioning Into Minimum Number Of Deci-Binary Numbers](/solution/1600-1699/1689.Partitioning%20Into%20Minimum%20Number%20Of%20Deci-Binary%20Numbers/README_EN.md) | `Greedy`,`String` | Medium | Weekly Contest 219 | | 1690 | [Stone Game VII](/solution/1600-1699/1690.Stone%20Game%20VII/README_EN.md) | `Array`,`Math`,`Dynamic Programming`,`Game Theory` | Medium | Weekly Contest 219 | @@ -2580,7 +2580,7 @@ Press Control+F(or Command+F on the | 2569 | [Handling Sum Queries After Update](/solution/2500-2599/2569.Handling%20Sum%20Queries%20After%20Update/README_EN.md) | `Segment Tree`,`Array` | Hard | Biweekly Contest 98 | | 2570 | [Merge Two 2D Arrays by Summing Values](/solution/2500-2599/2570.Merge%20Two%202D%20Arrays%20by%20Summing%20Values/README_EN.md) | `Array`,`Hash Table`,`Two Pointers` | Easy | Weekly Contest 333 | | 2571 | [Minimum Operations to Reduce an Integer to 0](/solution/2500-2599/2571.Minimum%20Operations%20to%20Reduce%20an%20Integer%20to%200/README_EN.md) | `Greedy`,`Bit Manipulation`,`Dynamic Programming` | Medium | Weekly Contest 333 | -| 2572 | [Count the Number of Square-Free Subsets](/solution/2500-2599/2572.Count%20the%20Number%20of%20Square-Free%20Subsets/README_EN.md) | `Array`,`Math`,`Dynamic Programming`,`Bitmask` | Medium | Weekly Contest 333 | +| 2572 | [Count the Number of Square-Free Subsets](/solution/2500-2599/2572.Count%20the%20Number%20of%20Square-Free%20Subsets/README_EN.md) | `Bit Manipulation`,`Array`,`Math`,`Dynamic Programming`,`Bitmask` | Medium | Weekly Contest 333 | | 2573 | [Find the String with LCP](/solution/2500-2599/2573.Find%20the%20String%20with%20LCP/README_EN.md) | `Greedy`,`Union Find`,`String`,`Dynamic Programming` | Hard | Weekly Contest 333 | | 2574 | [Left and Right Sum Differences](/solution/2500-2599/2574.Left%20and%20Right%20Sum%20Differences/README_EN.md) | `Array`,`Prefix Sum` | Easy | Weekly Contest 334 | | 2575 | [Find the Divisibility Array of a String](/solution/2500-2599/2575.Find%20the%20Divisibility%20Array%20of%20a%20String/README_EN.md) | `Array`,`Math`,`String` | Medium | Weekly Contest 334 | @@ -2598,15 +2598,16 @@ Press Control+F(or Command+F on the | 2587 | [Rearrange Array to Maximize Prefix Score](/solution/2500-2599/2587.Rearrange%20Array%20to%20Maximize%20Prefix%20Score/README_EN.md) | `Greedy`,`Array`,`Prefix Sum`,`Sorting` | Medium | Weekly Contest 336 | | 2588 | [Count the Number of Beautiful Subarrays](/solution/2500-2599/2588.Count%20the%20Number%20of%20Beautiful%20Subarrays/README_EN.md) | `Bit Manipulation`,`Array`,`Hash Table`,`Prefix Sum` | Medium | Weekly Contest 336 | | 2589 | [Minimum Time to Complete All Tasks](/solution/2500-2599/2589.Minimum%20Time%20to%20Complete%20All%20Tasks/README_EN.md) | `Stack`,`Greedy`,`Array`,`Binary Search`,`Sorting` | Hard | Weekly Contest 336 | -| 2590 | [Design a Todo List](/solution/2500-2599/2590.Design%20a%20Todo%20List/README_EN.md) | | Medium | 🔒 | -| 2591 | [Distribute Money to Maximum Children](/solution/2500-2599/2591.Distribute%20Money%20to%20Maximum%20Children/README_EN.md) | | Easy | Biweekly Contest 100 | -| 2592 | [Maximize Greatness of an Array](/solution/2500-2599/2592.Maximize%20Greatness%20of%20an%20Array/README_EN.md) | | Medium | Biweekly Contest 100 | -| 2593 | [Find Score of an Array After Marking All Elements](/solution/2500-2599/2593.Find%20Score%20of%20an%20Array%20After%20Marking%20All%20Elements/README_EN.md) | | Medium | Biweekly Contest 100 | -| 2594 | [Minimum Time to Repair Cars](/solution/2500-2599/2594.Minimum%20Time%20to%20Repair%20Cars/README_EN.md) | | Medium | Biweekly Contest 100 | -| 2595 | [Number of Even and Odd Bits](/solution/2500-2599/2595.Number%20of%20Even%20and%20Odd%20Bits/README_EN.md) | | Easy | Weekly Contest 337 | -| 2596 | [Check Knight Tour Configuration](/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/README_EN.md) | | Medium | Weekly Contest 337 | -| 2597 | [The Number of Beautiful Subsets](/solution/2500-2599/2597.The%20Number%20of%20Beautiful%20Subsets/README_EN.md) | | Medium | Weekly Contest 337 | -| 2598 | [Smallest Missing Non-negative Integer After Operations](/solution/2500-2599/2598.Smallest%20Missing%20Non-negative%20Integer%20After%20Operations/README_EN.md) | | Medium | Weekly Contest 337 | +| 2590 | [Design a Todo List](/solution/2500-2599/2590.Design%20a%20Todo%20List/README_EN.md) | `Design`,`Array`,`Hash Table`,`String`,`Sorting` | Medium | 🔒 | +| 2591 | [Distribute Money to Maximum Children](/solution/2500-2599/2591.Distribute%20Money%20to%20Maximum%20Children/README_EN.md) | `Greedy`,`Math` | Easy | Biweekly Contest 100 | +| 2592 | [Maximize Greatness of an Array](/solution/2500-2599/2592.Maximize%20Greatness%20of%20an%20Array/README_EN.md) | `Greedy`,`Array`,`Two Pointers`,`Sorting` | Medium | Biweekly Contest 100 | +| 2593 | [Find Score of an Array After Marking All Elements](/solution/2500-2599/2593.Find%20Score%20of%20an%20Array%20After%20Marking%20All%20Elements/README_EN.md) | `Array`,`Sorting`,`Simulation`,`Heap (Priority Queue)` | Medium | Biweekly Contest 100 | +| 2594 | [Minimum Time to Repair Cars](/solution/2500-2599/2594.Minimum%20Time%20to%20Repair%20Cars/README_EN.md) | `Array`,`Binary Search` | Medium | Biweekly Contest 100 | +| 2595 | [Number of Even and Odd Bits](/solution/2500-2599/2595.Number%20of%20Even%20and%20Odd%20Bits/README_EN.md) | `Bit Manipulation` | Easy | Weekly Contest 337 | +| 2596 | [Check Knight Tour Configuration](/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/README_EN.md) | `Depth-First Search`,`Breadth-First Search`,`Array`,`Matrix`,`Simulation` | Medium | Weekly Contest 337 | +| 2597 | [The Number of Beautiful Subsets](/solution/2500-2599/2597.The%20Number%20of%20Beautiful%20Subsets/README_EN.md) | `Array`,`Dynamic Programming`,`Backtracking` | Medium | Weekly Contest 337 | +| 2598 | [Smallest Missing Non-negative Integer After Operations](/solution/2500-2599/2598.Smallest%20Missing%20Non-negative%20Integer%20After%20Operations/README_EN.md) | `Greedy`,`Array`,`Hash Table`,`Math` | Medium | Weekly Contest 337 | +| 2599 | [Make the Prefix Sum Non-negative](/solution/2500-2599/2599.Make%20the%20Prefix%20Sum%20Non-negative/README_EN.md) | | Medium | 🔒 | ## Copyright diff --git a/solution/summary.md b/solution/summary.md index 9d5ba43a67ec6..6b169187ad6b3 100644 --- a/solution/summary.md +++ b/solution/summary.md @@ -22,7 +22,7 @@ - [0020.有效的括号](/solution/0000-0099/0020.Valid%20Parentheses/README.md) - [0021.合并两个有序链表](/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/README.md) - [0022.括号生成](/solution/0000-0099/0022.Generate%20Parentheses/README.md) - - [0023.合并K个升序链表](/solution/0000-0099/0023.Merge%20k%20Sorted%20Lists/README.md) + - [0023.合并 K 个升序链表](/solution/0000-0099/0023.Merge%20k%20Sorted%20Lists/README.md) - [0024.两两交换链表中的节点](/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/README.md) - [0025.K 个一组翻转链表](/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/README.md) - [0026.删除有序数组中的重复项](/solution/0000-0099/0026.Remove%20Duplicates%20from%20Sorted%20Array/README.md) @@ -2648,3 +2648,4 @@ - [2596.检查骑士巡视方案](/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/README.md) - [2597.美丽子集的数目](/solution/2500-2599/2597.The%20Number%20of%20Beautiful%20Subsets/README.md) - [2598.执行操作后的最大 MEX](/solution/2500-2599/2598.Smallest%20Missing%20Non-negative%20Integer%20After%20Operations/README.md) + - [2599.Make the Prefix Sum Non-negative](/solution/2500-2599/2599.Make%20the%20Prefix%20Sum%20Non-negative/README.md) diff --git a/solution/summary_en.md b/solution/summary_en.md index 0e0c7a6200e5b..08169a0e21468 100644 --- a/solution/summary_en.md +++ b/solution/summary_en.md @@ -2648,3 +2648,4 @@ - [2596.Check Knight Tour Configuration](/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/README_EN.md) - [2597.The Number of Beautiful Subsets](/solution/2500-2599/2597.The%20Number%20of%20Beautiful%20Subsets/README_EN.md) - [2598.Smallest Missing Non-negative Integer After Operations](/solution/2500-2599/2598.Smallest%20Missing%20Non-negative%20Integer%20After%20Operations/README_EN.md) + - [2599.Make the Prefix Sum Non-negative](/solution/2500-2599/2599.Make%20the%20Prefix%20Sum%20Non-negative/README_EN.md)