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 01/12] 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 02/12] 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 03/12] 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 04/12] 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 05/12] 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 06/12] 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 07/12] 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 08/12] 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 09/12] 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 10/12] 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 11/12] 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 12/12] 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; +}