diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index c9d1ff08444c5..9cbadf57631dc 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -15,58 +15,101 @@ on:
- basic/**
concurrency:
- group: ${{github.workflow}} - ${{github.ref}}
+ group: ${{ github.workflow }} - ${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
- - uses: actions/checkout@v4
+ - name: Checkout main branch
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Checkout docs branch
+ uses: actions/checkout@v4
with:
ref: docs
path: mkdocs
- - run: |
- mv -f mkdocs/* .
+ fetch-depth: 0
+
+ - name: Sync docs branch content
+ run: |
+ rsync -a --remove-source-files --exclude='.git' mkdocs/ ./
+ rm -rf mkdocs
mv solution/CONTEST_README.md docs/contest.md
mv solution/CONTEST_README_EN.md docs-en/contest.md
+
- name: Configure Git Credentials
run: |
- git config user.name github-actions[bot]
- git config user.email 41898282+github-actions[bot]@users.noreply.github.com
+ git config --global user.name github-actions[bot]
+ git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
- - uses: actions/setup-python@v5
+ - name: Setup Python
+ uses: actions/setup-python@v5
with:
python-version: 3.x
- - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
+ - name: Restore pip cache
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-
- - uses: actions/cache@v4
+ - name: Restore mkdocs-material cache
+ uses: actions/cache@v4
with:
- key: mkdocs-material-${{ env.cache_id }}
path: .cache
+ key: mkdocs-material-${{ env.cache_id }}
restore-keys: |
mkdocs-material-
-
+
- name: Install dependencies
run: |
python3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt
python3 -m pip install "mkdocs-material[imaging]"
- sudo apt-get install pngquant
-
- - name: Set MKDOCS_API_KEYS environment variable
+ sudo apt-get install -y pngquant
+
+ - name: Set MKDOCS_API_KEYS
run: echo "MKDOCS_API_KEYS=${{ secrets.MKDOCS_API_KEYS }}" >> $GITHUB_ENV
- - run: |
+ - name: Build site
+ run: |
python3 main.py
mkdocs build -f mkdocs.yml
mkdocs build -f mkdocs-en.yml
- - name: Generate CNAME file
+ - name: Generate CNAME
run: echo "leetcode.doocs.org" > ./site/CNAME
+ - name: Commit committer cache to docs branch
+ if: github.ref == 'refs/heads/main'
+ env:
+ GH_REPO: ${{ github.repository }}
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ CACHE_FILE=".git-committers-cache.json"
+ if [[ ! -f "$CACHE_FILE" ]]; then
+ echo "Cache file not found; skip commit."
+ exit 0
+ fi
+
+ echo "Cloning docs branch ..."
+ git clone --depth 1 --branch docs "https://x-access-token:${GH_TOKEN}@github.com/${GH_REPO}.git" docs-cache
+ cp "$CACHE_FILE" docs-cache/
+
+ cd docs-cache
+ git config user.name github-actions[bot]
+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com
+
+ git add .git-committers-cache.json
+ git commit -m "chore: update committer cache [skip ci]" || echo "No changes to commit"
+ git push origin docs
+
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
@@ -74,13 +117,13 @@ jobs:
deploy:
needs: build
+ runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github_pages
url: ${{ steps.deployment.outputs.page_url }}
- runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
diff --git a/.gitignore b/.gitignore
index e8ebbedd5ad1e..521323b59d92d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,10 +3,13 @@
.vscode
.temp
.vitepress
-.cache
*.iml
__pycache__
/node_modules
/solution/result.json
/solution/__pycache__
/solution/.env
+.cache
+!.cache/plugin/
+!.cache/plugin/git-committers/
+!.cache/plugin/git-committers/page-authors.json
\ No newline at end of file
diff --git a/README.md b/README.md
index 761cfcad81eae..aa8c9b92c5efa 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,8 @@
-
+
+
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
- -字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
+给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
示例 1:
-
-输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
-输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
+输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
+ +输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
+ +解释:
+ +"bat"
。"nat"
和 "tan"
是字母异位词,因为它们可以重新排列以形成彼此。"ate"
,"eat"
和 "tea"
是字母异位词,因为它们可以重新排列以形成彼此。示例 2:
-
-输入: strs = [""]
-输出: [[""]]
-
+输入: strs = [""]
+ +输出: [[""]]
+示例 3:
-
-输入: strs = ["a"]
-输出: [["a"]]
+输入: strs = ["a"]
+ +输出: [["a"]]
+diff --git a/solution/0000-0099/0066.Plus One/README.md b/solution/0000-0099/0066.Plus One/README.md index 6c48f063bb6d3..a63a22c802037 100644 --- a/solution/0000-0099/0066.Plus One/README.md +++ b/solution/0000-0099/0066.Plus One/README.md @@ -17,11 +17,9 @@ tags: -
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
+给定一个表示 大整数 的整数数组 digits
,其中 digits[i]
是整数的第 i
位数字。这些数字按从左到右,从最高位到最低位排列。这个大整数不包含任何前导 0
。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
- -你可以假设除了整数 0 之外,这个整数不会以零开头。
+将大整数加 1,并返回结果的数字数组。
@@ -31,6 +29,8 @@ tags: 输入:digits = [1,2,3] 输出:[1,2,4] 解释:输入数组表示数字 123。 +加 1 后得到 123 + 1 = 124。 +因此,结果应该是 [1,2,4]。
示例 2:
@@ -39,6 +39,8 @@ tags: 输入:digits = [4,3,2,1] 输出:[4,3,2,2] 解释:输入数组表示数字 4321。 +加 1 后得到 4321 + 1 = 4322。 +因此,结果应该是 [4,3,2,2]。示例 3:
@@ -58,6 +60,7 @@ tags:1 <= digits.length <= 100
0 <= digits[i] <= 9
digits
不包含任何前导 0
。给你两个字符串 s
和 t
,统计并返回在 s
的 子序列 中 t
出现的个数,结果需要对 109 + 7 取模。
给你两个字符串 s
和 t
,统计并返回在 s
的 子序列 中 t
出现的个数。
测试用例保证结果在 32 位有符号整数范围内。
diff --git a/solution/0100-0199/0134.Gas Station/README.md b/solution/0100-0199/0134.Gas Station/README.md index 3ae6856d3f254..b350fca1ed379 100644 --- a/solution/0100-0199/0134.Gas Station/README.md +++ b/solution/0100-0199/0134.Gas Station/README.md @@ -57,10 +57,10 @@ tags:
提示:
gas.length == n
cost.length == n
n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
-
查询 Employee
表中第 n
高的工资。如果没有第 n
个最高工资,查询结果应该为 null
。
编写一个解决方案查询 Employee
表中第 n
高的 不同 工资。如果少于 n
个不同工资,查询结果应该为 null
。
查询结果格式如下所示。
diff --git a/solution/0100-0199/0177.Nth Highest Salary/README_EN.md b/solution/0100-0199/0177.Nth Highest Salary/README_EN.md index 37c056f9d75ef..3373a1cd68980 100644 --- a/solution/0100-0199/0177.Nth Highest Salary/README_EN.md +++ b/solution/0100-0199/0177.Nth Highest Salary/README_EN.md @@ -31,7 +31,7 @@ Each row of this table contains information about the salary of an employee.-
Write a solution to find the nth
highest salary from the Employee
table. If there is no nth
highest salary, return null
.
Write a solution to find the nth
highest distinct salary from the Employee
table. If there are less than n
distinct salaries, return null
.
The result format is in the following example.
diff --git a/solution/0100-0199/0195.Tenth Line/README_EN.md b/solution/0100-0199/0195.Tenth Line/README_EN.md index 7ca9f7187d210..69bdfb2395242 100644 --- a/solution/0100-0199/0195.Tenth Line/README_EN.md +++ b/solution/0100-0199/0195.Tenth Line/README_EN.md @@ -23,26 +23,41 @@ tags:Assume that file.txt
has the following content:
+ Line 1 + Line 2 + Line 3 + Line 4 + Line 5 + Line 6 + Line 7 + Line 8 + Line 9 + Line 10 +
Your script should output the tenth line, which is:
+ Line 10 +
给定一个 无重复元素 的 有序 整数数组 nums
。
返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说,nums
的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums
的数字 x
。
区间 [a,b]
是从 a
到 b
(包含)的所有整数的集合。
返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说,nums
的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个区间但不属于 nums
的数字 x
。
列表中的每个区间范围 [a,b]
应该按如下格式输出:
给定一个二叉树,统计该二叉树数值相同的子树个数。
+给定一个二叉树,统计该二叉树数值相同的 子树 个数。
同值子树是指该子树的所有节点都拥有相同的数值。
-示例:
++
示例 1:
+-输入: root = [5,1,5,5,5,null,5] +输入:root = [5,1,5,5,5,null,5] +输出:4 +- 5 - / \ - 1 5 - / \ \ - 5 5 5 +
示例 2:
-输出: 4 ++输入:root = [] +输出:0+
示例 3:
+ ++输入:root = [5,5,5,5,5,null,5] +输出:6 ++ +
+ +
提示:
+ +[0, 1000]
范围内-1000 <= Node.val <= 1000
-
表:Users
-
取消率 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数)。
编写解决方案找出 "2013-10-01"
至 "2013-10-03"
期间有 至少 一次行程的非禁止用户(乘客和司机都必须未被禁止)的 取消率。非禁止用户即 banned 为 No 的用户,禁止用户即 banned 为 Yes 的用户。其中取消率 Cancellation Rate
需要四舍五入保留 两位小数 。
+
Table: Users
+
The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.
@@ -59,7 +59,7 @@ banned is an ENUM (category) type of ('Yes', 'No').Return the result table in any order.
-The result format is in the following example.
+The result format is in the following example.
Example 1:
diff --git a/solution/0200-0299/0269.Alien Dictionary/README.md b/solution/0200-0299/0269.Alien Dictionary/README.md index b1185f65b06a0..308a96369b8e8 100644 --- a/solution/0200-0299/0269.Alien Dictionary/README.md +++ b/solution/0200-0299/0269.Alien Dictionary/README.md @@ -288,6 +288,87 @@ public: }; ``` +#### Go + +```go +func alienOrder(words []string) string { + g := [26][26]bool{} + s := [26]bool{} + cnt := 0 + n := len(words) + for i := 0; i < n-1; i++ { + for _, c := range words[i] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + m := len(words[i]) + for j := 0; j < m; j++ { + if j >= len(words[i+1]) { + return "" + } + c1, c2 := words[i][j]-'a', words[i+1][j]-'a' + if c1 == c2 { + continue + } + if g[c2][c1] { + return "" + } + g[c1][c2] = true + break + } + } + for _, c := range words[n-1] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + + inDegree := [26]int{} + for _, out := range g { + for i, v := range out { + if v { + inDegree[i]++ + } + } + } + q := []int{} + for i, in := range inDegree { + if in == 0 && s[i] { + q = append(q, i) + } + } + ans := "" + for len(q) > 0 { + t := q[0] + q = q[1:] + ans += string(t + 'a') + for i, v := range g[t] { + if v { + inDegree[i]-- + if inDegree[i] == 0 && s[i] { + q = append(q, i) + } + } + } + } + if len(ans) < cnt { + return "" + } + return ans +} +``` + diff --git a/solution/0200-0299/0269.Alien Dictionary/README_EN.md b/solution/0200-0299/0269.Alien Dictionary/README_EN.md index 9677cf9f30970..24d8925dfb9a6 100644 --- a/solution/0200-0299/0269.Alien Dictionary/README_EN.md +++ b/solution/0200-0299/0269.Alien Dictionary/README_EN.md @@ -269,6 +269,87 @@ public: }; ``` +#### Go + +```go +func alienOrder(words []string) string { + g := [26][26]bool{} + s := [26]bool{} + cnt := 0 + n := len(words) + for i := 0; i < n-1; i++ { + for _, c := range words[i] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + m := len(words[i]) + for j := 0; j < m; j++ { + if j >= len(words[i+1]) { + return "" + } + c1, c2 := words[i][j]-'a', words[i+1][j]-'a' + if c1 == c2 { + continue + } + if g[c2][c1] { + return "" + } + g[c1][c2] = true + break + } + } + for _, c := range words[n-1] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + + inDegree := [26]int{} + for _, out := range g { + for i, v := range out { + if v { + inDegree[i]++ + } + } + } + q := []int{} + for i, in := range inDegree { + if in == 0 && s[i] { + q = append(q, i) + } + } + ans := "" + for len(q) > 0 { + t := q[0] + q = q[1:] + ans += string(t + 'a') + for i, v := range g[t] { + if v { + inDegree[i]-- + if inDegree[i] == 0 && s[i] { + q = append(q, i) + } + } + } + } + if len(ans) < cnt { + return "" + } + return ans +} +``` + diff --git a/solution/0200-0299/0269.Alien Dictionary/Solution.go b/solution/0200-0299/0269.Alien Dictionary/Solution.go new file mode 100644 index 0000000000000..b49abee4bad20 --- /dev/null +++ b/solution/0200-0299/0269.Alien Dictionary/Solution.go @@ -0,0 +1,76 @@ +func alienOrder(words []string) string { + g := [26][26]bool{} + s := [26]bool{} + cnt := 0 + n := len(words) + for i := 0; i < n-1; i++ { + for _, c := range words[i] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + m := len(words[i]) + for j := 0; j < m; j++ { + if j >= len(words[i+1]) { + return "" + } + c1, c2 := words[i][j]-'a', words[i+1][j]-'a' + if c1 == c2 { + continue + } + if g[c2][c1] { + return "" + } + g[c1][c2] = true + break + } + } + for _, c := range words[n-1] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + + inDegree := [26]int{} + for _, out := range g { + for i, v := range out { + if v { + inDegree[i]++ + } + } + } + q := []int{} + for i, in := range inDegree { + if in == 0 && s[i] { + q = append(q, i) + } + } + ans := "" + for len(q) > 0 { + t := q[0] + q = q[1:] + ans += string(t + 'a') + for i, v := range g[t] { + if v { + inDegree[i]-- + if inDegree[i] == 0 && s[i] { + q = append(q, i) + } + } + } + } + if len(ans) < cnt { + return "" + } + return ans +} diff --git a/solution/0200-0299/0275.H-Index II/README.md b/solution/0200-0299/0275.H-Index II/README.md index 546a3242358e5..47b3a5e04dfb9 100644 --- a/solution/0200-0299/0275.H-Index II/README.md +++ b/solution/0200-0299/0275.H-Index II/README.md @@ -17,7 +17,7 @@ tags: -给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数,citations
已经按照 升序排列 。计算并返回该研究者的 h 指数。
给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数,citations
已经按照 非降序排列 。计算并返回该研究者的 h 指数。
h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h
指数是指他(她)的 (n
篇论文中)至少 有 h
篇论文分别被引用了至少 h
次。
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper and citations
is sorted in ascending order, return the researcher's h-index.
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper and citations
is sorted in non-descending order, return the researcher's h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h
such that the given researcher has published at least h
papers that have each been cited at least h
times.
总旅行距离 是朋友们家到聚会地点的距离之和。
-使用 曼哈顿距离 计算距离,其中距离 (p1, p2) = |p2.x - p1.x | + | p2.y - p1.y |
。
示例 1:
diff --git a/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md b/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md index 816bbabef6c3d..edd540c52e03d 100644 --- a/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md +++ b/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md @@ -32,8 +32,6 @@ tags:The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
-The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.
Example 1:
给定单链表的头节点 head
,将所有索引为奇数的节点和索引为偶数的节点分别组合在一起,然后返回重新排序的列表。
给定单链表的头节点 head
,将所有索引为奇数的节点和索引为偶数的节点分别分组,保持它们原有的相对顺序,然后把偶数索引节点分组连接到奇数索引节点分组之后,返回重新排序的链表。
第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。
diff --git a/solution/0400-0499/0412.Fizz Buzz/README.md b/solution/0400-0499/0412.Fizz Buzz/README.md index e700c0a3089e9..19d4d3abe8a6c 100644 --- a/solution/0400-0499/0412.Fizz Buzz/README.md +++ b/solution/0400-0499/0412.Fizz Buzz/README.md @@ -18,7 +18,7 @@ tags: -给你一个整数 n
,找出从 1
到 n
各个整数的 Fizz Buzz 表示,并用字符串数组 answer
(下标从 1 开始)返回结果,其中:
给你一个整数 n
,返回一个字符串数组 answer
(下标从 1 开始),其中:
answer[i] == "FizzBuzz"
如果 i
同时是 3
和 5
的倍数。示例 3:
-输入:sentence = ["I", "had", "apple", "pie"], rows = 4, cols = 5 +输入:sentence = ["i", "had", "apple", "pie"], rows = 4, cols = 5 输出:1 解释: -I-had +i-had apple -pie-I +pie-i had-- 字符 '-' 表示屏幕上的一个空白位置。diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md index 79d1666a074ef..04f5e0e21142b 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md @@ -49,7 +49,37 @@ tags: -### 方法一 +### 方法一:字典树计数 + 贪心构造 + +本题要求在区间 $[1, n]$ 中,按**字典序**排序后,找到第 $k$ 小的数字。由于 $n$ 的范围非常大(最多可达 $10^9$),我们无法直接枚举所有数字后排序。因此我们采用**贪心 + 字典树模拟**的策略。 + +我们将 $[1, n]$ 看作一棵 **十叉字典树(Trie)**: + +- 每个节点是一个前缀,根节点为空串; +- 节点的子节点是当前前缀拼接上 $0 \sim 9$; +- 例如前缀 $1$ 会有子节点 $10, 11, \ldots, 19$,而 $10$ 会有 $100, 101, \ldots, 109$; +- 这种结构天然符合字典序遍历。 + +``` +根 +├── 1 +│ ├── 10 +│ ├── 11 +│ ├── ... +├── 2 +├── ... +``` + +我们使用变量 $\textit{curr}$ 表示当前前缀,初始为 $1$。每次我们尝试向下扩展前缀,直到找到第 $k$ 小的数字。 + +每次我们计算当前前缀下有多少个合法数字(即以 $\textit{curr}$ 为前缀、且不超过 $n$ 的整数个数),记作 $\textit{count}(\text{curr})$: + +- 如果 $k \ge \text{count}(\text{curr})$:说明目标不在这棵子树中,跳过整棵子树,前缀右移:$\textit{curr} \leftarrow \text{curr} + 1$,并更新 $k \leftarrow k - \text{count}(\text{curr})$; +- 否则:说明目标在当前前缀的子树中,进入下一层:$\textit{curr} \leftarrow \text{curr} \times 10$,并消耗一个前缀:$k \leftarrow k - 1$。 + +每一层我们将当前区间扩大 $10$ 倍,向下延伸到更长的前缀,直到超出 $n$。 + +时间复杂度 $O(\log^2 n)$,空间复杂度 $O(1)$。 @@ -181,6 +211,75 @@ func findKthNumber(n int, k int) int { } ``` +#### TypeScript + +```ts +function findKthNumber(n: number, k: number): number { + function count(curr: number): number { + let next = curr + 1; + let cnt = 0; + while (curr <= n) { + cnt += Math.min(n - curr + 1, next - curr); + curr *= 10; + next *= 10; + } + return cnt; + } + + let curr = 1; + k--; + + while (k > 0) { + const cnt = count(curr); + if (k >= cnt) { + k -= cnt; + curr += 1; + } else { + k -= 1; + curr *= 10; + } + } + + return curr; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn find_kth_number(n: i32, k: i32) -> i32 { + fn count(mut curr: i64, n: i32) -> i32 { + let mut next = curr + 1; + let mut total = 0; + let n = n as i64; + while curr <= n { + total += std::cmp::min(n - curr + 1, next - curr); + curr *= 10; + next *= 10; + } + total as i32 + } + + let mut curr = 1; + let mut k = k - 1; + + while k > 0 { + let cnt = count(curr as i64, n); + if k >= cnt { + k -= cnt; + curr += 1; + } else { + k -= 1; + curr *= 10; + } + } + + curr + } +} +``` + diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md index f8c7bc38a68b3..abdae7d0cad00 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md @@ -47,7 +47,46 @@ tags: -### Solution 1 +### Solution 1: Trie-Based Counting + Greedy Construction + +The problem asks for the \$k\$-th smallest number in the range $[1, n]$ when all numbers are sorted in **lexicographical order**. Since $n$ can be as large as $10^9$, we cannot afford to generate and sort all the numbers explicitly. Instead, we adopt a strategy based on **greedy traversal over a conceptual Trie**. + +We treat the range $[1, n]$ as a **10-ary prefix tree (Trie)**: + +- Each node represents a numeric prefix, starting from an empty root; +- Each node has 10 children, corresponding to appending digits $0 \sim 9$; +- For example, prefix $1$ has children $10, 11, \ldots, 19$, and node $10$ has children $100, 101, \ldots, 109$; +- This tree naturally reflects lexicographical order traversal. + +``` +root +├── 1 +│ ├── 10 +│ ├── 11 +│ ├── ... +├── 2 +├── ... +``` + +We use a variable $\textit{curr}$ to denote the current prefix, initialized as $1$. At each step, we try to expand or skip prefixes until we find the \$k\$-th smallest number. + +At each step, we calculate how many valid numbers (i.e., numbers $\le n$ with prefix $\textit{curr}$) exist under this prefix subtree. Let this count be $\textit{count}(\text{curr})$: + +- If $k \ge \text{count}(\text{curr})$: the target number is not in this subtree. We skip the entire subtree by moving to the next sibling: + + $$ + \textit{curr} \leftarrow \textit{curr} + 1,\quad k \leftarrow k - \text{count}(\text{curr}) + $$ + +- Otherwise: the target is within this subtree. We go one level deeper: + + $$ + \textit{curr} \leftarrow \textit{curr} \times 10,\quad k \leftarrow k - 1 + $$ + +At each level, we enlarge the current range by multiplying by 10 and continue descending until we exceed $n$. + +The time complexity is $O(\log^2 n)$, as we perform logarithmic operations for counting and traversing the Trie structure. The space complexity is $O(1)$ since we only use a few variables to track the current prefix and count. @@ -179,6 +218,75 @@ func findKthNumber(n int, k int) int { } ``` +#### TypeScript + +```ts +function findKthNumber(n: number, k: number): number { + function count(curr: number): number { + let next = curr + 1; + let cnt = 0; + while (curr <= n) { + cnt += Math.min(n - curr + 1, next - curr); + curr *= 10; + next *= 10; + } + return cnt; + } + + let curr = 1; + k--; + + while (k > 0) { + const cnt = count(curr); + if (k >= cnt) { + k -= cnt; + curr += 1; + } else { + k -= 1; + curr *= 10; + } + } + + return curr; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn find_kth_number(n: i32, k: i32) -> i32 { + fn count(mut curr: i64, n: i32) -> i32 { + let mut next = curr + 1; + let mut total = 0; + let n = n as i64; + while curr <= n { + total += std::cmp::min(n - curr + 1, next - curr); + curr *= 10; + next *= 10; + } + total as i32 + } + + let mut curr = 1; + let mut k = k - 1; + + while k > 0 { + let cnt = count(curr as i64, n); + if k >= cnt { + k -= cnt; + curr += 1; + } else { + k -= 1; + curr *= 10; + } + } + + curr + } +} +``` + diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.rs b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.rs new file mode 100644 index 0000000000000..52351a5f8ff07 --- /dev/null +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn find_kth_number(n: i32, k: i32) -> i32 { + fn count(mut curr: i64, n: i32) -> i32 { + let mut next = curr + 1; + let mut total = 0; + let n = n as i64; + while curr <= n { + total += std::cmp::min(n - curr + 1, next - curr); + curr *= 10; + next *= 10; + } + total as i32 + } + + let mut curr = 1; + let mut k = k - 1; + + while k > 0 { + let cnt = count(curr as i64, n); + if k >= cnt { + k -= cnt; + curr += 1; + } else { + k -= 1; + curr *= 10; + } + } + + curr + } +} diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.ts b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.ts new file mode 100644 index 0000000000000..7e54456e1b47a --- /dev/null +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/Solution.ts @@ -0,0 +1,28 @@ +function findKthNumber(n: number, k: number): number { + function count(curr: number): number { + let next = curr + 1; + let cnt = 0; + while (curr <= n) { + cnt += Math.min(n - curr + 1, next - curr); + curr *= 10; + next *= 10; + } + return cnt; + } + + let curr = 1; + k--; + + while (k > 0) { + const cnt = count(curr); + if (k >= cnt) { + k -= cnt; + curr += 1; + } else { + k -= 1; + curr *= 10; + } + } + + return curr; +} diff --git a/solution/0500-0599/0506.Relative Ranks/README.md b/solution/0500-0599/0506.Relative Ranks/README.md index 2f1fa1b09f81b..8dc348d38fa3e 100644 --- a/solution/0500-0599/0506.Relative Ranks/README.md +++ b/solution/0500-0599/0506.Relative Ranks/README.md @@ -97,9 +97,7 @@ class Solution { public String[] findRelativeRanks(int[] score) { int n = score.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i1, i2) -> score[i2] - score[i1]); String[] ans = new String[n]; String[] top3 = new String[] {"Gold Medal", "Silver Medal", "Bronze Medal"}; diff --git a/solution/0500-0599/0506.Relative Ranks/README_EN.md b/solution/0500-0599/0506.Relative Ranks/README_EN.md index 8bb99b92b780c..7abeba13e8be4 100644 --- a/solution/0500-0599/0506.Relative Ranks/README_EN.md +++ b/solution/0500-0599/0506.Relative Ranks/README_EN.md @@ -96,9 +96,7 @@ class Solution { public String[] findRelativeRanks(int[] score) { int n = score.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i1, i2) -> score[i2] - score[i1]); String[] ans = new String[n]; String[] top3 = new String[] {"Gold Medal", "Silver Medal", "Bronze Medal"}; diff --git a/solution/0500-0599/0506.Relative Ranks/Solution.java b/solution/0500-0599/0506.Relative Ranks/Solution.java index 700c854e36bcb..a855b14e5cb57 100644 --- a/solution/0500-0599/0506.Relative Ranks/Solution.java +++ b/solution/0500-0599/0506.Relative Ranks/Solution.java @@ -2,9 +2,7 @@ class Solution { public String[] findRelativeRanks(int[] score) { int n = score.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i1, i2) -> score[i2] - score[i1]); String[] ans = new String[n]; String[] top3 = new String[] {"Gold Medal", "Silver Medal", "Bronze Medal"}; diff --git a/solution/0500-0599/0520.Detect Capital/README.md b/solution/0500-0599/0520.Detect Capital/README.md index b97c875d43010..ecb68de064c73 100644 --- a/solution/0500-0599/0520.Detect Capital/README.md +++ b/solution/0500-0599/0520.Detect Capital/README.md @@ -20,8 +20,8 @@ tags:
"USA"
。"leetcode"
。"Google"
。"leetcode"
。"Google"
。给你一个字符串 word
。如果大写用法正确,返回 true
;否则,返回 false
。
- -
编写解决方案,报告在首次登录的第二天再次登录的玩家的 比率,四舍五入到小数点后两位。换句话说,你需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。
+编写解决方案,报告在首次登录的第二天再次登录的玩家的 比率,四舍五入到小数点后两位。换句话说,你需要计算从首次登录后的第二天登录的玩家数量,并将其除以总玩家数。
结果格式如下所示:
diff --git a/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md b/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md index 75774152565b6..3612f647d84ed 100644 --- a/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md +++ b/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md @@ -32,11 +32,11 @@ This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. -+
-
Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
+Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to determine the number of players who logged in on the day immediately following their initial login, and divide it by the number of total players.
-The result format is in the following example.
+The result format is in the following example.
Example 1:
diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md index 6d3765e61f6cb..2cf6f98195019 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md @@ -173,32 +173,20 @@ function findUnsortedSubarray(nums: number[]): number { ```rust impl Solution { pub fn find_unsorted_subarray(nums: Vec假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。
+给定两个字符串数组 list1
和 list2
,找到 索引和最小的公共字符串。
你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设答案总是存在。
+公共字符串 是同时出现在 list1
和 list2
中的字符串。
具有 最小索引和的公共字符串 是指,如果它在 list1[i]
和 list2[j]
中出现,那么 i + j
应该是所有其他 公共字符串 中的最小值。
返回所有 具有最小索引和的公共字符串。以 任何顺序 返回答案。
@@ -29,7 +33,7 @@ tags:
输入: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] 输出: ["Shogun"] -解释: 他们唯一共同喜爱的餐厅是“Shogun”。 +解释: 唯一的公共字符串是 “Shogun”。
示例 2:
@@ -37,9 +41,20 @@ tags:输入:list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["KFC", "Shogun", "Burger King"] 输出: ["Shogun"] -解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。 +解释: 具有最小索引和的公共字符串是 “Shogun”,它有最小的索引和 = (0 + 1) = 1。+
示例 3:
+ ++输入:list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] +输出:["sad","happy"] +解释:有三个公共字符串: +"happy" 索引和 = (0 + 1) = 1. +"sad" 索引和 = (1 + 0) = 1. +"good" 索引和 = (2 + 2) = 4. +最小索引和的字符串是 "sad" 和 "happy"。+
提示:
diff --git a/solution/0600-0699/0636.Exclusive Time of Functions/README.md b/solution/0600-0699/0636.Exclusive Time of Functions/README.md index 9dc839b951335..7f5e3268f6a69 100644 --- a/solution/0600-0699/0636.Exclusive Time of Functions/README.md +++ b/solution/0600-0699/0636.Exclusive Time of Functions/README.md @@ -73,7 +73,7 @@ tags:1 <= n <= 100
1 <= logs.length <= 500
2 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
1 <= n <= 100
1 <= logs.length <= 500
2 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
树可以看成是一个连通且 无环 的 无向 图。
-给定往一棵 n
个节点 (节点值 1~n
) 的树中添加一条边后的图。添加的边的两个顶点包含在 1
到 n
中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n
的二维数组 edges
,edges[i] = [ai, bi]
表示图中在 ai
和 bi
之间存在一条边。
给定一个图,该图从一棵 n
个节点 (节点值 1~n
) 的树中添加一条边后获得。添加的边的两个不同顶点编号在 1
到 n
中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n
的二维数组 edges
,edges[i] = [ai, bi]
表示图中在 ai
和 bi
之间存在一条边。
请找出一条可以删去的边,删除后可使得剩余部分是一个有着 n
个节点的树。如果有多个答案,则返回数组 edges
中最后出现的那个。
示例 2:
diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md index 4f842e5001bae..3d1fb0e0c7da3 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md @@ -5,6 +5,8 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0600-0699/0689.Ma tags: - Array - Dynamic Programming + - Prefix Sum + - Sliding Window --- @@ -28,7 +30,7 @@ tags: Input: nums = [1,2,1,2,6,7,5,1], k = 2 Output: [0,3,5] Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. -We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically smaller. +We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.Example 2:
diff --git a/solution/0700-0799/0704.Binary Search/README.md b/solution/0700-0799/0704.Binary Search/README.md index 293c01438e03b..e58c3aed1d10e 100644 --- a/solution/0700-0799/0704.Binary Search/README.md +++ b/solution/0700-0799/0704.Binary Search/README.md @@ -17,19 +17,23 @@ tags: -给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果 target
存在返回下标,否则返回 -1
。
+
你必须编写一个具有 O(log n)
时间复杂度的算法。
示例 1:
输入:nums
= [-1,0,3,5,9,12],target
= 9 ++输入:nums
= [-1,0,3,5,9,12],target
= 9 输出: 4 解释: 9 出现在nums
中并且下标为 4示例 2:
-输入:diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/README.md b/solution/0700-0799/0790.Domino and Tromino Tiling/README.md index da30ee9b60a10..9311772e724de 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/README.md +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/README.md @@ -86,7 +86,7 @@ tags: 注意,过程中的状态数值可能会很大,因此需要对 $10^9+7$ 取模。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为面板的列数。 +时间复杂度 $O(n)$,其中 $n$ 为面板的列数。空间复杂度 $O(1)$。 @@ -132,12 +132,11 @@ class Solution { ```cpp class Solution { public: - const int mod = 1e9 + 7; - int numTilings(int n) { - long f[4] = {1, 0, 0, 0}; + const int mod = 1e9 + 7; + long long f[4] = {1, 0, 0, 0}; for (int i = 1; i <= n; ++i) { - long g[4] = {0, 0, 0, 0}; + long long g[4]; g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; g[1] = (f[2] + f[3]) % mod; g[2] = (f[1] + f[3]) % mod; @@ -168,6 +167,46 @@ func numTilings(n int) int { } ``` +#### TypeScript + +```ts +function numTilings(n: number): number { + const mod = 1_000_000_007; + let f: number[] = [1, 0, 0, 0]; + + for (let i = 1; i <= n; ++i) { + const g: number[] = Array(4); + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; + g[1] = (f[2] + f[3]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[0] % mod; + f = g; + } + + return f[0]; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_tilings(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut f: [i64; 4] = [1, 0, 0, 0]; + for _ in 1..=n { + let mut g = [0i64; 4]; + g[0] = (f[0] + f[1] + f[2] + f[3]) % MOD; + g[1] = (f[2] + f[3]) % MOD; + g[2] = (f[1] + f[3]) % MOD; + g[3] = f[0] % MOD; + f = g; + } + f[0] as i32 + } +} +``` + diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md b/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md index 04f89b3e86cd6..9d5dc63b7ff65 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md @@ -28,7 +28,7 @@ tags:nums
= [-1,0,3,5,9,12],target
= 2 ++输入:diff --git a/solution/0700-0799/0720.Longest Word in Dictionary/README.md b/solution/0700-0799/0720.Longest Word in Dictionary/README.md index bf15fcb915ab3..3a80e81888f9e 100644 --- a/solution/0700-0799/0720.Longest Word in Dictionary/README.md +++ b/solution/0700-0799/0720.Longest Word in Dictionary/README.md @@ -20,7 +20,7 @@ tags: -nums
= [-1,0,3,5,9,12],target
= 2 输出: -1 解释: 2 不存在nums
中因此返回 -1给出一个字符串数组
+words
组成的一本英语词典。返回words
中最长的一个单词,该单词是由words
词典中其他单词逐步添加一个字母组成。给出一个字符串数组
words
组成的一本英语词典。返回能够通过words
中其它单词逐步添加一个字母来构造得到的words
中最长的单词。若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
diff --git a/solution/0700-0799/0759.Employee Free Time/README.md b/solution/0700-0799/0759.Employee Free Time/README.md index cf8212b6bb7f5..e422bbd125252 100644 --- a/solution/0700-0799/0759.Employee Free Time/README.md +++ b/solution/0700-0799/0759.Employee Free Time/README.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0700-0799/0759.Em tags: - 数组 - 排序 + - 扫描线 - 堆(优先队列) --- diff --git a/solution/0700-0799/0759.Employee Free Time/README_EN.md b/solution/0700-0799/0759.Employee Free Time/README_EN.md index 9543d4e2e9379..7c0a64ed0b949 100644 --- a/solution/0700-0799/0759.Employee Free Time/README_EN.md +++ b/solution/0700-0799/0759.Employee Free Time/README_EN.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0700-0799/0759.Em tags: - Array - Sorting + - Line Sweep - Heap (Priority Queue) --- diff --git a/solution/0700-0799/0781.Rabbits in Forest/README.md b/solution/0700-0799/0781.Rabbits in Forest/README.md index ba4b1c52bf77e..e0deffabd8ff3 100644 --- a/solution/0700-0799/0781.Rabbits in Forest/README.md +++ b/solution/0700-0799/0781.Rabbits in Forest/README.md @@ -31,10 +31,10 @@ tags: 输入:answers = [1,1,2] 输出:5 解释: -两只回答了 "1" 的兔子可能有相同的颜色,设为红色。 +两只回答了 "1" 的兔子可能有相同的颜色,设为红色。 之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。 -设回答了 "2" 的兔子为蓝色。 -此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。 +设回答了 "2" 的兔子为蓝色。 +此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。 因此森林中兔子的最少数量是 5 只:3 只回答的和 2 只没有回答的。Input: n = 3 Output: 5 -Explanation: The five different ways are show above. +Explanation: The five different ways are shown above.Example 2:
@@ -126,12 +126,11 @@ class Solution { ```cpp class Solution { public: - const int mod = 1e9 + 7; - int numTilings(int n) { - long f[4] = {1, 0, 0, 0}; + const int mod = 1e9 + 7; + long long f[4] = {1, 0, 0, 0}; for (int i = 1; i <= n; ++i) { - long g[4] = {0, 0, 0, 0}; + long long g[4]; g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; g[1] = (f[2] + f[3]) % mod; g[2] = (f[1] + f[3]) % mod; @@ -162,6 +161,46 @@ func numTilings(n int) int { } ``` +#### TypeScript + +```ts +function numTilings(n: number): number { + const mod = 1_000_000_007; + let f: number[] = [1, 0, 0, 0]; + + for (let i = 1; i <= n; ++i) { + const g: number[] = Array(4); + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; + g[1] = (f[2] + f[3]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[0] % mod; + f = g; + } + + return f[0]; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_tilings(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut f: [i64; 4] = [1, 0, 0, 0]; + for _ in 1..=n { + let mut g = [0i64; 4]; + g[0] = (f[0] + f[1] + f[2] + f[3]) % MOD; + g[1] = (f[2] + f[3]) % MOD; + g[2] = (f[1] + f[3]) % MOD; + g[3] = f[0] % MOD; + f = g; + } + f[0] as i32 + } +} +``` + diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp index 7dee343d57916..835d82ee5f184 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp @@ -1,11 +1,10 @@ class Solution { public: - const int mod = 1e9 + 7; - int numTilings(int n) { - long f[4] = {1, 0, 0, 0}; + const int mod = 1e9 + 7; + long long f[4] = {1, 0, 0, 0}; for (int i = 1; i <= n; ++i) { - long g[4] = {0, 0, 0, 0}; + long long g[4]; g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; g[1] = (f[2] + f[3]) % mod; g[2] = (f[1] + f[3]) % mod; diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.rs b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.rs new file mode 100644 index 0000000000000..fa193c65eb056 --- /dev/null +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn num_tilings(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut f: [i64; 4] = [1, 0, 0, 0]; + for _ in 1..=n { + let mut g = [0i64; 4]; + g[0] = (f[0] + f[1] + f[2] + f[3]) % MOD; + g[1] = (f[2] + f[3]) % MOD; + g[2] = (f[1] + f[3]) % MOD; + g[3] = f[0] % MOD; + f = g; + } + f[0] as i32 + } +} diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.ts b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.ts new file mode 100644 index 0000000000000..1550567f5375c --- /dev/null +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.ts @@ -0,0 +1,15 @@ +function numTilings(n: number): number { + const mod = 1_000_000_007; + let f: number[] = [1, 0, 0, 0]; + + for (let i = 1; i <= n; ++i) { + const g: number[] = Array(4); + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; + g[1] = (f[2] + f[3]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[0] % mod; + f = g; + } + + return f[0]; +} diff --git a/solution/0700-0799/0797.All Paths From Source to Target/README.md b/solution/0700-0799/0797.All Paths From Source to Target/README.md index 4deb1aa603807..1d36139c345de 100644 --- a/solution/0700-0799/0797.All Paths From Source to Target/README.md +++ b/solution/0700-0799/0797.All Paths From Source to Target/README.md @@ -19,7 +19,7 @@ tags: -给你一个有
+n
个节点的 有向无环图(DAG),请你找出所有从节点0
到节点n-1
的路径并输出(不要求按特定顺序)给你一个有
n
个节点的 有向无环图(DAG),请你找出从节点0
到节点n-1
的所有路径并输出(不要求按特定顺序)diff --git a/solution/0700-0799/0799.Champagne Tower/README_EN.md b/solution/0700-0799/0799.Champagne Tower/README_EN.md index 7c1df1e554754..c04fa21334900 100644 --- a/solution/0700-0799/0799.Champagne Tower/README_EN.md +++ b/solution/0700-0799/0799.Champagne Tower/README_EN.md @@ -27,35 +27,51 @@ tags:
graph[i]
是一个从节点i
可以访问的所有节点的列表(即从节点i
到节点graph[i][j]
存在一条有向边)。Now after pouring some non-negative integer cups of champagne, return how full the
jth
glass in theith
row is (bothi
andj
are 0-indexed.)+
Example 1:
+ Input: poured = 1, query_row = 1, query_glass = 1 + Output: 0.00000 + Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. +Example 2:
+ Input: poured = 2, query_row = 1, query_glass = 1 + Output: 0.50000 + Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. +Example 3:
+ Input: poured = 100000009, query_row = 33, query_glass = 17 + Output: 1.00000 ++
Constraints:
0 <= poured <= 109
0 <= query_glass <= query_row < 100
0 <= poured <= 109
0 <= query_glass <= query_row < 100
有一个有 n
个节点的有向图,节点按 0
到 n - 1
编号。图由一个 索引从 0 开始 的 2D 整数数组 graph
表示, graph[i]
是与节点 i
相邻的节点的整数数组,这意味着从节点 i
到 graph[i]
中的每个节点都有一条边。
如果一个节点没有连出的有向边,则该节点是 终端节点 。如果从该节点开始的所有可能路径都通向 终端节点 ,则该节点为 安全节点 。
+如果一个节点没有连出的有向边,则该节点是 终端节点 。如果从该节点开始的所有可能路径都通向 终端节点 ,则该节点为 终端节点(或另一个安全节点)。
返回一个由图中所有 安全节点 组成的数组作为答案。答案数组中的元素应当按 升序 排列。
diff --git a/solution/0800-0899/0819.Most Common Word/README.md b/solution/0800-0899/0819.Most Common Word/README.md index f3adddcb4620e..20a453ae26ab5 100644 --- a/solution/0800-0899/0819.Most Common Word/README.md +++ b/solution/0800-0899/0819.Most Common Word/README.md @@ -23,6 +23,8 @@ tags:paragraph
中的单词 不区分大小写 ,答案应以 小写 形式返回。
注意 单词不包含标点符号。
+
示例 1:
diff --git a/solution/0800-0899/0819.Most Common Word/README_EN.md b/solution/0800-0899/0819.Most Common Word/README_EN.md index ebcacda3c5c8e..2aae27ab03f78 100644 --- a/solution/0800-0899/0819.Most Common Word/README_EN.md +++ b/solution/0800-0899/0819.Most Common Word/README_EN.md @@ -23,6 +23,8 @@ tags:The words in paragraph
are case-insensitive and the answer should be returned in lowercase.
Note that words can not contain punctuation symbols.
+
Example 1:
diff --git a/solution/0800-0899/0838.Push Dominoes/README.md b/solution/0800-0899/0838.Push Dominoes/README.md index e6f79c7abba0b..d37d4feea673e 100644 --- a/solution/0800-0899/0838.Push Dominoes/README.md +++ b/solution/0800-0899/0838.Push Dominoes/README.md @@ -68,7 +68,30 @@ tags: -### 方法一 +### 方法一:多源 BFS + +把所有初始受到推力的骨牌(`L` 或 `R`)视作 **源点**,它们会同时向外扩散各自的力。用队列按时间层级(0, 1, 2 …)进行 BFS: + +我们定义 $\text{time[i]}$ 记录第 *i* 张骨牌第一次受力的时刻,`-1` 表示尚未受力,定义 $\text{force[i]}$ 是一个长度可变的列表,存放该骨牌在同一时刻收到的方向(`'L'`、`'R'`)。初始时把所有 `L/R` 的下标压入队列,并将它们的时间置 0。 + +当弹出下标 *i* 时,若 $\text{force[i]}$ 只有一个方向,骨牌就会倒向该方向 $f$。设下一张骨牌下标为 + +$$ +j = +\begin{cases} +i - 1, & f = L,\\ +i + 1, & f = R. +\end{cases} +$$ + +若 $0 \leq j < n$: + +- 若 $\text{time[j]}=-1$,说明 *j* 从未受力,记录 $\text{time[j]}=\text{time[i]}+1$ 并入队,同时把 $f$ 写入 $\text{force[j]}$。 +- 若 $\text{time[j]}=\text{time[i]}+1$,说明它在同一“下一刻”已受过另一股力,此时只把 $f$ 追加到 $\text{force[j]}$,形成对冲;后续因 `len(force[j])==2`,它将保持竖直。 + +队列清空后,所有 $\text{force[i]}$ 长度为 1 的位置倒向对应方向;长度为 2 的位置保持 `.`。最终将字符数组拼接为答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是骨牌的数量。 @@ -242,44 +265,40 @@ func pushDominoes(dominoes string) string { ```ts function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } ``` diff --git a/solution/0800-0899/0838.Push Dominoes/README_EN.md b/solution/0800-0899/0838.Push Dominoes/README_EN.md index ce232677d18a7..ec5ef4c80d36c 100644 --- a/solution/0800-0899/0838.Push Dominoes/README_EN.md +++ b/solution/0800-0899/0838.Push Dominoes/README_EN.md @@ -67,7 +67,30 @@ tags: -### Solution 1 +### Solution 1: Multi-Source BFS + +Treat all initially pushed dominoes (`L` or `R`) as **sources**, which simultaneously propagate their forces outward. Use a queue to perform BFS layer by layer (0, 1, 2, ...): + +We define $\text{time[i]}$ to record the first moment when the _i_-th domino is affected by a force, with `-1` indicating it has not been affected yet. We also define $\text{force[i]}$ as a variable-length list that stores the directions (`'L'`, `'R'`) of forces acting on the domino at the same moment. Initially, push all indices of `L/R` dominoes into the queue and set their `time` to 0. + +When dequeuing index _i_, if $\text{force[i]}$ contains only one direction, the domino will fall in that direction $f$. Let the index of the next domino be: + +$$ +j = +\begin{cases} +i - 1, & f = L,\\ +i + 1, & f = R. +\end{cases} +$$ + +If $0 \leq j < n$: + +- If $\text{time[j]} = -1$, it means _j_ has not been affected yet. Record $\text{time[j]} = \text{time[i]} + 1$, enqueue it, and append $f$ to $\text{force[j]}$. +- If $\text{time[j]} = \text{time[i]} + 1$, it means _j_ has already been affected by another force at the same "next moment." In this case, append $f$ to $\text{force[j]}$, causing a standoff. Subsequently, since $\text{len(force[j])} = 2$, it will remain upright. + +After the queue is emptied, all positions where $\text{force[i]}$ has a length of 1 will fall in the corresponding direction, while positions with a length of 2 will remain as `.`. Finally, concatenate the character array to form the answer. + +The complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of dominoes. @@ -241,44 +264,40 @@ func pushDominoes(dominoes string) string { ```ts function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } ``` diff --git a/solution/0800-0899/0838.Push Dominoes/Solution.ts b/solution/0800-0899/0838.Push Dominoes/Solution.ts index d9e8412c5d062..0b912d31ca203 100644 --- a/solution/0800-0899/0838.Push Dominoes/Solution.ts +++ b/solution/0800-0899/0838.Push Dominoes/Solution.ts @@ -1,41 +1,37 @@ function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } diff --git a/solution/0800-0899/0853.Car Fleet/README.md b/solution/0800-0899/0853.Car Fleet/README.md index fadb1d60e4f77..c8bb9502b2c1e 100644 --- a/solution/0800-0899/0853.Car Fleet/README.md +++ b/solution/0800-0899/0853.Car Fleet/README.md @@ -125,9 +125,7 @@ class Solution { public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> position[j] - position[i]); int ans = 0; double pre = 0; diff --git a/solution/0800-0899/0853.Car Fleet/README_EN.md b/solution/0800-0899/0853.Car Fleet/README_EN.md index baba8b025d9bf..29c9d8eef5cd8 100644 --- a/solution/0800-0899/0853.Car Fleet/README_EN.md +++ b/solution/0800-0899/0853.Car Fleet/README_EN.md @@ -117,9 +117,7 @@ class Solution { public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> position[j] - position[i]); int ans = 0; double pre = 0; diff --git a/solution/0800-0899/0853.Car Fleet/Solution.java b/solution/0800-0899/0853.Car Fleet/Solution.java index c346687da335c..593a14db56bc7 100644 --- a/solution/0800-0899/0853.Car Fleet/Solution.java +++ b/solution/0800-0899/0853.Car Fleet/Solution.java @@ -2,9 +2,7 @@ class Solution { public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> position[j] - position[i]); int ans = 0; double pre = 0; diff --git a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md index ed6e907943729..4a4ddd95f3f1f 100644 --- a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md +++ b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md @@ -18,18 +18,18 @@ tags: -如果序列 X_1, X_2, ..., X_n
满足下列条件,就说它是 斐波那契式 的:
如果序列 x1, x2, ..., x2
满足下列条件,就说它是 斐波那契式 的:
n >= 3
i + 2 <= n
,都有 X_i + X_{i+1} = X_{i+2}
n >= 3
i + 2 <= n
,都有 xi + xi+1 == xi+2
给定一个严格递增的正整数数组形成序列 arr ,找到 arr 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。
+给定一个 严格递增 的正整数数组形成序列 arr
,找到 arr
中最长的斐波那契式的子序列的长度。如果不存在,返回 0
。
(回想一下,子序列是从原序列 arr 中派生出来的,它从 arr 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8]
是 [3, 4, 5, 6, 7, 8]
的一个子序列)
子序列 是通过从另一个序列 arr
中删除任意数量的元素(包括删除 0 个元素)得到的,同时不改变剩余元素顺序。例如,[3, 5, 8]
是 [3, 4, 5, 6, 7, 8]
的子序列。
+
示例 2:
+示例 2:
输入: arr = [1,3,7,11,12,14,18] @@ -50,14 +50,14 @@ tags: 解释: 最长的斐波那契式子序列有 [1,11,12]、[3,11,14] 以及 [7,11,18] 。-
+
提示:
3 <= arr.length <= 1000
3 <= arr.length <= 1000
1 <= arr[i] < arr[i + 1] <= 10^9
1 <= arr[i] < arr[i + 1] <= 109
输入:nums = [5,2,3,1] 输出:[1,2,3,5] +解释:数组排序后,某些数字的位置没有改变(例如,2 和 3),而其他数字的位置发生了改变(例如,1 和 5)。
示例 2:
@@ -44,6 +45,7 @@ tags:输入:nums = [5,1,1,2,0,0] 输出:[0,0,1,1,2,5] +解释:请注意,nums 的值不一定唯一。
diff --git a/solution/0900-0999/0912.Sort an Array/README_EN.md b/solution/0900-0999/0912.Sort an Array/README_EN.md index 4459f121075b6..fe0d0ef1d3c87 100644 --- a/solution/0900-0999/0912.Sort an Array/README_EN.md +++ b/solution/0900-0999/0912.Sort an Array/README_EN.md @@ -41,7 +41,7 @@ tags:
Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] -Explanation: Note that the values of nums are not necessairly unique. +Explanation: Note that the values of nums are not necessarily unique.
diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/README.md b/solution/0900-0999/0923.3Sum With Multiplicity/README.md index 8304f7ca2d34d..88ec551f961a0 100644 --- a/solution/0900-0999/0923.3Sum With Multiplicity/README.md +++ b/solution/0900-0999/0923.3Sum With Multiplicity/README.md @@ -12,7 +12,7 @@ tags: -# [923. 三数之和的多种可能](https://leetcode.cn/problems/3sum-with-multiplicity) +# [923. 多重三数之和](https://leetcode.cn/problems/3sum-with-multiplicity) [English Version](/solution/0900-0999/0923.3Sum%20With%20Multiplicity/README_EN.md) diff --git a/solution/0900-0999/0949.Largest Time for Given Digits/README.md b/solution/0900-0999/0949.Largest Time for Given Digits/README.md index a6c6088450230..5cda14059e019 100644 --- a/solution/0900-0999/0949.Largest Time for Given Digits/README.md +++ b/solution/0900-0999/0949.Largest Time for Given Digits/README.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0900-0999/0949.La tags: - 数组 - 字符串 + - 回溯 - 枚举 --- diff --git a/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md b/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md index 3e37133c552f9..abd01a85c19b0 100644 --- a/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md +++ b/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0900-0999/0949.La tags: - Array - String + - Backtracking - Enumeration --- diff --git a/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md b/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md index a8055d4e5e1ae..e7308c5d9ad60 100644 --- a/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md +++ b/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md @@ -199,6 +199,35 @@ function minDominoRotations(tops: number[], bottoms: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn min_domino_rotations(tops: Vec
输入:s1 = "parker", s2 = "morris", baseStr = "parser" 输出:"makkek" -解释:根据A
和B 中的等价信息,
我们可以将这些字符分为[m,p]
,[a,o]
,[k,r,s]
,[e,i] 共 4 组
。每组中的字符都是等价的,并按字典序排列。所以答案是"makkek"
。 +解释:根据A
和B
中的等价信息,我们可以将这些字符分为[m,p]
,[a,o]
,[k,r,s]
,[e,i]
共 4 组。每组中的字符都是等价的,并按字典序排列。所以答案是"makkek"
。
示例 2:
@@ -52,7 +52,7 @@ tags:输入:s1 = "hello", s2 = "world", baseStr = "hold" 输出:"hdld" -解释:根据A
和B 中的等价信息,
我们可以将这些字符分为[h,w]
,[d,e,o]
,[l,r] 共 3 组
。所以只有 S 中的第二个字符'o'
变成'd',最后答案为
"hdld"
。 +解释:根据A
和B
中的等价信息,我们可以将这些字符分为[h,w]
,[d,e,o]
,[l,r]
共 3 组。所以只有 S 中的第二个字符'o'
变成'd'
,最后答案为"hdld"
。
示例 3:
@@ -60,7 +60,7 @@ tags:输入:s1 = "leetcode", s2 = "programs", baseStr = "sourcecode" 输出:"aauaaaaada" -解释:我们可以把 A 和 B 中的等价字符分为[a,o,e,r,s,c]
,[l,p]
,[g,t]
和[d,m] 共 4 组
,因此S
中除了'u'
和'd'
之外的所有字母都转化成了'a'
,最后答案为"aauaaaaada"
。 +解释:我们可以把A
和B
中的等价字符分为[a,o,e,r,s,c]
,[l,p]
,[g,t]
和[d,m]
共 4 组,因此S
中除了'u'
和'd'
之外的所有字母都转化成了'a'
,最后答案为"aauaaaaada"
。
@@ -79,7 +79,11 @@ tags: -### 方法一 +### 方法一:并查集 + +我们可以使用并查集来处理等价字符的关系。每个字符可以看作一个节点,等价关系可以看作是连接这些节点的边。通过并查集,我们可以将所有等价的字符归为一类,并且在查询时能够快速找到每个字符的代表元素。我们在进行合并操作时,始终将代表元素设置为字典序最小的字符,这样可以确保最终得到的字符串是按字典序排列的最小等价字符串。 + +时间复杂度 $O((n + m) \times \log |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $n$ 是字符串 $s1$ 和 $s2$ 的长度,而 $m$ 是字符串 $baseStr$ 的长度,而 $|\Sigma|$ 是字符集的大小,本题中 $|\Sigma| = 26$。 @@ -88,54 +92,47 @@ tags: ```python class Solution: def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str: - p = list(range(26)) - - def find(x): + def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] - for i in range(len(s1)): - a, b = ord(s1[i]) - ord('a'), ord(s2[i]) - ord('a') - pa, pb = find(a), find(b) - if pa < pb: - p[pb] = pa + p = list(range(26)) + for a, b in zip(s1, s2): + x, y = ord(a) - ord("a"), ord(b) - ord("a") + px, py = find(x), find(y) + if px < py: + p[py] = px else: - p[pa] = pb - - res = [] - for a in baseStr: - a = ord(a) - ord('a') - res.append(chr(find(a) + ord('a'))) - return ''.join(res) + p[px] = py + return "".join(chr(find(ord(c) - ord("a")) + ord("a")) for c in baseStr) ``` #### Java ```java class Solution { - private int[] p; + private final int[] p = new int[26]; public String smallestEquivalentString(String s1, String s2, String baseStr) { - p = new int[26]; - for (int i = 0; i < 26; ++i) { + for (int i = 0; i < p.length; ++i) { p[i] = i; } for (int i = 0; i < s1.length(); ++i) { - int a = s1.charAt(i) - 'a', b = s2.charAt(i) - 'a'; - int pa = find(a), pb = find(b); - if (pa < pb) { - p[pb] = pa; + int x = s1.charAt(i) - 'a'; + int y = s2.charAt(i) - 'a'; + int px = find(x), py = find(y); + if (px < py) { + p[py] = px; } else { - p[pa] = pb; + p[px] = py; } } - StringBuilder sb = new StringBuilder(); - for (char a : baseStr.toCharArray()) { - char b = (char) (find(a - 'a') + 'a'); - sb.append(b); + char[] s = baseStr.toCharArray(); + for (int i = 0; i < s.length; ++i) { + s[i] = (char) ('a' + find(s[i] - 'a')); } - return sb.toString(); + return String.valueOf(s); } private int find(int x) { @@ -152,32 +149,30 @@ class Solution { ```cpp class Solution { public: - vector
给出 字符串 text
和 字符串列表 words
, 返回所有的索引对 [i, j]
使得在索引对范围内的子字符串 text[i]...text[j]
(包括 i
和 j
)属于字符串列表 words
。
给出 字符串 text
和 字符串列表 words
, 返回所有的索引对 [i, j]
使得子字符串 text[i]...text[j]
(包括 i
和 j
)属于字符串列表 words
。
按顺序返回索引对 [i, j]
(即,按它们的第一个坐标进行排序,如果相同,则按它们的第二个坐标对它们进行排序)。
示例 1:
-输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] ++输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] 输出: [[3,7],[9,13],[10,17]]示例 2:
-输入: text = "ababa", words = ["aba","ab"] ++输入: text = "ababa", words = ["aba","ab"] 输出: [[0,1],[0,2],[2,3],[2,4]] 解释: -注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中 +注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中
提示:
--
+- 所有字符串都只包含小写字母。
-- 保证
+words
中的字符串无重复。
1 <= text.length <= 100
1 <= words.length <= 20
- -
1 <= words[i].length <= 50
- 按序返回索引对
-[i,j]
(即,按照索引对的第一个索引进行排序,当第一个索引对相同时按照第二个索引对排序)。
text
和 words[i]
都只包含小写字母。words
中的字符串无重复。- -
产品表 Product
:
-+--------------+---------+ -| Column Name | Type | -+--------------+---------+ -| product_id | int | -| product_name | varchar | -+--------------+---------+ -product_id 是这张表的主键(具有唯一值的列)。 -这张表的每一行都标识:每个产品的 id 和 产品名称。+
编写解决方案,选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。
-+
product_id
,找到其在Sales表中首次出现的最早年份。编写解决方案,选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。
+返回一张有这些列的表:product_id,first_year,quantity 和 price。
结果表中的条目可以按 任意顺序 排列。
-结果格式如下例所示:
-
示例 1:
@@ -70,14 +60,6 @@ Sales 表: | 2 | 100 | 2009 | 12 | 5000 | | 7 | 200 | 2011 | 15 | 9000 | +---------+------------+------+----------+-------+ -Product 表: -+------------+--------------+ -| product_id | product_name | -+------------+--------------+ -| 100 | Nokia | -| 200 | Apple | -| 300 | Samsung | -+------------+--------------+ 输出: +------------+------------+----------+-------+ | product_id | first_year | quantity | price | diff --git a/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md b/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md index 03c8643cae525..c948fe652735b 100644 --- a/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md +++ b/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md @@ -30,32 +30,25 @@ tags: +-------------+-------+ (sale_id, year) is the primary key (combination of columns with unique values) of this table. product_id is a foreign key (reference column) toProduct
table.
-Each row of this table shows a sale on the product product_id in a certain year.
-Note that the price is per unit.
-
-
-- -
Table: Product
-+--------------+---------+ -| Column Name | Type | -+--------------+---------+ -| product_id | int | -| product_name | varchar | -+--------------+---------+ -product_id is the primary key (column with unique values) of this table. -Each row of this table indicates the product name of each product.-
- -
Write a solution to select the product id, year, quantity, and price for the first year of every product sold.
+Write a solution to find all sales that occurred in the first year each product was sold.
-Return the resulting table in any order.
+For each product_id
, identify the earliest year
it appears in the Sales
table.
Return all sales entries for that product in that year.
+The result format is in the following example.
+Return a table with the following columns: product_id, first_year, quantity, and price.
+Return the result in any order.
Example 1:
@@ -70,14 +63,7 @@ Sales table: | 2 | 100 | 2009 | 12 | 5000 | | 7 | 200 | 2011 | 15 | 9000 | +---------+------------+------+----------+-------+ -Product table: -+------------+--------------+ -| product_id | product_name | -+------------+--------------+ -| 100 | Nokia | -| 200 | Apple | -| 300 | Samsung | -+------------+--------------+ + Output: +------------+------------+----------+-------+ | product_id | first_year | quantity | price | diff --git a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md index d141c92ba6e45..537e7be2aa54c 100644 --- a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md +++ b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md @@ -23,18 +23,29 @@ tags:A defanged IP address replaces every period "."
with "[.]"
.
+
Example 1:
+Input: address = "1.1.1.1" + Output: "1[.]1[.]1[.]1" +
Example 2:
+Input: address = "255.100.50.0" + Output: "255[.]100[.]50[.]0" ++
+
Constraints:
address
is a valid IPv4 address.address
is a valid IPv4 address.A string is a valid parentheses string (denoted VPS) if and only if it consists of "("
and ")"
characters only, and:
AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.We can similarly define the nesting depth depth(S)
of any VPS S
as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.For example, ""
, "()()"
, and "()(()())"
are VPS's (with nesting depths 0, 1, and 2), and ")("
and "(()"
are not VPS's.
We may make the following moves:
'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.(Here, the only positions that exist on the board are positions with letters on them.)
@@ -40,19 +46,31 @@ tags:Return a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
+
Example 1:
+Input: target = "leet" + Output: "DDR!UURRR!!DDD!" +
Example 2:
+Input: target = "code" + Output: "RR!DDRR!UUL!R!" ++
+
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.1 <= target.length <= 100
target
consists only of English lowercase letters.Given a 2D grid
of 0
s and 1
s, return the number of elements in the largest square subgrid that has all 1
s on its border, or 0
if such a subgrid doesn't exist in the grid
.
+
Example 1:
+ Input: grid = [[1,1,1],[1,0,1],[1,1,1]] + Output: 9 +
Example 2:
+ Input: grid = [[1,1,0,0]] + Output: 1 +
+
Constraints:
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
-
请查询出所有浏览过自己文章的作者
+请查询出所有浏览过自己文章的作者。
-结果按照 id
升序排列。
结果按照作者的 id
升序排列。
查询结果的格式如下所示:
diff --git a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md index 5b959a1bb55b8..96da4eb86409c 100644 --- a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md +++ b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md @@ -7,6 +7,7 @@ source: 第 6 场双周赛 Q3 tags: - 数组 - 哈希表 + - 字符串 - 排序 --- diff --git a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md index 068e467a7a42c..11b798982680a 100644 --- a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md +++ b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md @@ -7,6 +7,7 @@ source: Biweekly Contest 6 Q3 tags: - Array - Hash Table + - String - Sorting --- diff --git a/solution/1100-1199/1153.String Transforms Into Another String/README.md b/solution/1100-1199/1153.String Transforms Into Another String/README.md index f2dfb0706cad4..1871225bf341a 100644 --- a/solution/1100-1199/1153.String Transforms Into Another String/README.md +++ b/solution/1100-1199/1153.String Transforms Into Another String/README.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1100-1199/1153.St rating: 1949 source: 第 6 场双周赛 Q4 tags: + - 图 - 哈希表 - 字符串 --- diff --git a/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md b/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md index 01c129fb6f316..d60d629f841a2 100644 --- a/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md +++ b/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1100-1199/1153.St rating: 1949 source: Biweekly Contest 6 Q4 tags: + - Graph - Hash Table - String --- diff --git a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md index 6b9897e53caa4..d39c633d50950 100644 --- a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md +++ b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md @@ -21,13 +21,11 @@ tags: -给你一份『词汇表』(字符串数组) words
和一张『字母表』(字符串) chars
。
给定一个字符串数组 words
和一个字符串 chars
。
假如你可以用 chars
中的『字母』(字符)拼写出 words
中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
如果字符串可以由 chars
中的字符组成(每个字符在 每个 words
中只能使用一次),则认为它是好的。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars
中的每个字母都只能用一次。
返回词汇表 words
中你掌握的所有单词的 长度之和。
返回 words
中所有好的字符串的长度之和。
@@ -56,7 +54,7 @@ tags:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
words[i]
和 chars
中都仅包含小写英文字母You are given an array of strings words
and a string chars
.
A string is good if it can be formed by characters from chars
(each character can only be used once).
A string is good if it can be formed by characters from chars
(each character can only be used once for each word in words
).
Return the sum of lengths of all good strings in words.
diff --git a/solution/1100-1199/1164.Product Price at a Given Date/README.md b/solution/1100-1199/1164.Product Price at a Given Date/README.md index 7f0478aa0b08d..c030fb7d15c63 100644 --- a/solution/1100-1199/1164.Product Price at a Given Date/README.md +++ b/solution/1100-1199/1164.Product Price at a Given Date/README.md @@ -29,9 +29,9 @@ tags: (product_id, change_date) 是此表的主键(具有唯一值的列组合)。 这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。 -+
一开始,所有产品价格都为 10。
-编写一个解决方案,找出在 2019-08-16
时全部产品的价格,假设所有产品在修改前的价格都是 10
。
编写一个解决方案,找出在 2019-08-16
。
以 任意顺序 返回结果表。
diff --git a/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md b/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md index 9e6ffa8caf273..0f8436fcb8040 100644 --- a/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md +++ b/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md @@ -29,13 +29,13 @@ tags: (product_id, change_date) is the primary key (combination of columns with unique values) of this table. Each row of this table indicates that the price of some product was changed to a new price at some date. -+
Initially, all products have price 10.
-Write a solution to find the prices of all products on 2019-08-16
. Assume the price of all products before any change is 10
.
Write a solution to find the prices of all products on the date 2019-08-16
.
Return the result table in any order.
-The result format is in the following example.
+The result format is in the following example.
Example 1:
diff --git a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md index d947861120f5a..b4e5e94f2f0f6 100644 --- a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md +++ b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md @@ -25,13 +25,17 @@ tags:Return the shortest distance between the given start
and destination
stops.
+
Example 1:
+ Input: distance = [1,2,3,4], start = 0, destination = 1 + Output: 1 + Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
@@ -41,9 +45,13 @@ tags:
+ Input: distance = [1,2,3,4], start = 0, destination = 2 + Output: 3 + Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3. +
@@ -53,19 +61,29 @@ tags:
+ Input: distance = [1,2,3,4], start = 0, destination = 3 + Output: 4 + Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4. +
+
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
给定一个链接 startUrl
和一个接口 HtmlParser
,请你实现一个网络爬虫,以实现爬取同 startUrl
拥有相同 主机名 的全部链接。
给定一个网址 startUrl
和一个接口 HtmlParser
,请你实现一个网络爬虫,以实现爬取同 startUrl
拥有相同 主机名 的全部链接。
该爬虫得到的全部链接可以 任何顺序 返回结果。
+该爬虫得到的全部网址可以 任何顺序 返回结果。
你的网络爬虫应当按照如下模式工作:
startUrl
开始爬取HtmlParser.getUrls(url)
来获得链接url
页面中的全部链接startUrl
开始爬取HtmlParser.getUrls(url)
来获得给定 url
网址中的全部链接startUrl
相同 的链接集合startUrl
相同 的链接集合如上所示的一个链接,其域名为 example.org
。简单起见,你可以假设所有的链接都采用 http协议 并没有指定 端口。例如,链接 http://leetcode.com/problems
和 http://leetcode.com/contest
是同一个域名下的,而链接 http://example.org/test
和 http://example.com/abc
是不在同一域名下的。
如上所示的一个网址,其域名为 example.org
。简单起见,你可以假设所有的网址都采用 http协议 并没有指定 端口。例如,网址 http://leetcode.com/problems
和 http://leetcode.com/contest
是同一个域名下的,而网址 http://example.org/test
和 http://example.com/abc
是不在同一域名下的。
HtmlParser
接口定义如下:
下面是两个实例,用以解释该问题的设计功能,对于自定义测试,你可以使用三个变量 urls
, edges
和 startUrl
。注意在代码实现中,你只可以访问 startUrl
,而 urls
和 edges
不可以在你的代码中被直接访问。
注意:将尾随斜线“/”的相同 URL 视为不同的 URL。例如,“http://news.yahoo.com” 和 “http://news.yahoo.com/” 是不同的域名。
+注意:将尾随斜线“/”的相同网址视为不同的网址。例如,“http://news.yahoo.com” 和 “http://news.yahoo.com/” 是不同的网址。
diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md index 57a0b48ed9325..f3d3a209aa212 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md @@ -23,35 +23,53 @@ tags:
Given 2 integers n
and start
. Your task is return any permutation p
of (0,1,2.....,2^n -1)
such that :
p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.+
Example 1:
+ Input: n = 2, start = 3 + Output: [3,2,0,1] + Explanation: The binary representation of the permutation is (11,10,00,01). + All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2] +
Example 2:
+ Input: n = 3, start = 2 + Output: [2,6,7,5,4,0,1,3] + Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011). +
+
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n
1 <= n <= 16
0 <= start < 2 ^ n
+
Example 1:
+ Input: num = 23 + Output: "1000" +
Example 2:
+ Input: num = 107 + Output: "101100" +
+
Constraints:
0 <= num <= 10^9
0 <= num <= 10^9
给你一些区域列表 regions
,每个列表的第一个区域都包含这个列表内所有其他区域。
给你一些区域列表 regions
,每个列表的第一个区域都 直接 包含这个列表内所有其他区域。
如果一个区域 x
直接包含区域 y
,并且区域 y
直接包含区域 z
,那么说区域 x
间接 包含区域 z
。请注意,区域 x
也 间接 包含所有在 y
中 间接 包含的区域。
很自然地,如果区域 x
包含区域 y
,那么区域 x
比区域 y
大。同时根据定义,区域 x
包含自身。
给定两个区域 region1
和 region2
,找到同时包含这两个区域的 最小 区域。
如果给定区域 r1
,r2
和 r3
,使得 r1
包含 r3
,那么数据保证 r2
不会包含 r3
。
数据同样保证最小区域一定存在。
diff --git a/solution/1200-1299/1257.Smallest Common Region/README_EN.md b/solution/1200-1299/1257.Smallest Common Region/README_EN.md index d5b52f58e36c7..2085a7c0a74a4 100644 --- a/solution/1200-1299/1257.Smallest Common Region/README_EN.md +++ b/solution/1200-1299/1257.Smallest Common Region/README_EN.md @@ -23,13 +23,13 @@ tags: -
You are given some lists of regions
where the first region of each list includes all other regions in that list.
You are given some lists of regions
where the first region of each list directly contains all other regions in that list.
Naturally, if a region x
contains another region y
then x
is bigger than y
. Also, by definition, a region x
contains itself.
If a region x
contains a region y
directly, and region y
contains region z
directly, then region x
is said to contain region z
indirectly. Note that region x
also indirectly contains all regions indirectly containd in y
.
Given two regions: region1
and region2
, return the smallest region that contains both of them.
Naturally, if a region x
contains (either directly or indirectly) another region y
, then x
is bigger than or equal to y
in size. Also, by definition, a region x
contains itself.
If you are given regions r1
, r2
, and r3
such that r1
includes r3
, it is guaranteed there is no r2
such that r2
includes r3
.
Given two regions: region1
and region2
, return the smallest region that contains both of them.
It is guaranteed the smallest region exists.
@@ -65,6 +65,7 @@ region2 = "New York"region1 != region2
regions[i][j]
, region1
, and region2
consist of English letters.给你一个整数数组 nums
,请你返回其中位数为 偶数 的数字的个数。
给你一个整数数组 nums
,请你返回其中包含 偶数 个数位的数字的个数。
@@ -131,6 +131,16 @@ function findNumbers(nums: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_numbers(nums: Vec
containedBoxes[i]
:整数,表示放在 box[i]
里的盒子所对应的下标。给你一个 initialBoxes
数组,表示你现在得到的盒子,你可以获得里面的糖果,也可以用盒子里的钥匙打开新的盒子,还可以继续探索从这个盒子里找到的其他盒子。
给你一个整数数组 initialBoxes
,包含你最初拥有的盒子。你可以拿走每个 已打开盒子 里的所有糖果,并且可以使用其中的钥匙去开启新的盒子,并且可以使用在其中发现的其他盒子。
请你按照上述规则,返回可以获得糖果的 最大数目 。
@@ -37,7 +37,8 @@ tags:示例 1:
-输入:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0] ++输入:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0] 输出:16 解释: 一开始你有盒子 0 。你将获得它里面的 7 个糖果和盒子 1 和 2。 @@ -48,7 +49,8 @@ tags:示例 2:
-输入:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0] ++输入:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0] 输出:6 解释: 你一开始拥有盒子 0 。打开它你可以找到盒子 1,2,3,4,5 和它们对应的钥匙。 @@ -57,19 +59,22 @@ tags:示例 3:
-输入:status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1] ++输入:status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1] 输出:1示例 4:
-输入:status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = [] ++输入:status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = [] 输出:0示例 5:
-输入:status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0] ++输入:status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0] 输出:7@@ -99,7 +104,24 @@ tags: -### 方法一:BFS +### 方法一:BFS + 哈希集合 + +题目给定一批盒子,每个盒子可能有状态(开/关)、糖果、钥匙、以及其他盒子。我们的目标是通过初始给定的一些盒子,尽可能多地打开更多盒子,并收集其中的糖果。可以通过获得钥匙来解锁新盒子,通过盒子中嵌套的盒子来获取更多资源。 + +我们采用 BFS 的方式模拟整个探索过程。 + +我们用一个队列 $q$ 表示当前可以访问的、**已经开启** 的盒子;用两个集合 $\textit{has}$ 和 $\textit{took}$ 分别记录**我们拥有的所有盒子**和**已经处理过的盒子**,防止重复。 + +初始时,将所有 $\textit{initialBoxes}$ 添加到 $\textit{has}$ 中,如果初始盒子状态为开启,立即加入队列 $\textit{q}$ 并累计糖果; + +然后进行 BFS,依次从 $\textit{q}$ 中取出盒子: + +- 获取盒子中的钥匙 $\textit{keys[box]}$,将能解锁的盒子加入队列; +- 收集盒子中包含的其他盒子 $\textit{containedBoxes[box]}$,如果状态是开启的且未处理过,则立即处理; + +每个盒子最多处理一次,糖果累计一次,最终返回总糖果数 $\textit{ans}$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是盒子的总数。 @@ -115,25 +137,31 @@ class Solution: containedBoxes: List[List[int]], initialBoxes: List[int], ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} - + q = deque() + has, took = set(initialBoxes), set() + ans = 0 + + for box in initialBoxes: + if status[box]: + q.append(box) + took.add(box) + ans += candies[box] while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) + box = q.popleft() + for k in keys[box]: + if not status[k]: + status[k] = 1 + if k in has and k not in took: + q.append(k) + took.add(k) + ans += candies[k] + + for b in containedBoxes[box]: + has.add(b) + if status[b] and b not in took: + q.append(b) + took.add(b) + ans += candies[b] return ans ``` @@ -143,35 +171,36 @@ class Solution: class Solution { public int maxCandies( int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; Dequeq = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); + Set has = new HashSet<>(); + Set took = new HashSet<>(); + int ans = 0; + for (int box : initialBoxes) { + has.add(box); + if (status[box] == 1) { + q.offer(box); + took.add(box); + ans += candies[box]; } } while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); + int box = q.poll(); + for (int k : keys[box]) { + if (status[k] == 0) { + status[k] = 1; + if (has.contains(k) && !took.contains(k)) { + q.offer(k); + took.add(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); + for (int b : containedBoxes[box]) { + has.add(b); + if (status[b] == 1 && !took.contains(b)) { + q.offer(b); + took.add(b); + ans += candies[b]; } } } @@ -185,40 +214,50 @@ class Solution { ```cpp class Solution { public: - int maxCandies(vector & status, vector & candies, vector >& keys, vector >& containedBoxes, vector & initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); + int maxCandies( + vector & status, + vector & candies, + vector >& keys, + vector >& containedBoxes, + vector & initialBoxes) { queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); + unordered_set has, took; + int ans = 0; + + for (int box : initialBoxes) { + has.insert(box); + if (status[box]) { + q.push(box); + took.insert(box); + ans += candies[box]; } } + while (!q.empty()) { - int i = q.front(); + int box = q.front(); q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); + + for (int k : keys[box]) { + if (!status[k]) { + status[k] = 1; + if (has.count(k) && !took.count(k)) { + q.push(k); + took.insert(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); + + for (int b : containedBoxes[box]) { + has.insert(b); + if (status[b] && !took.count(b)) { + q.push(b); + took.insert(b); + ans += candies[b]; } } } + return ans; } }; @@ -227,41 +266,147 @@ public: #### Go ```go -func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { - ans := 0 - n := len(status) - has := make([]bool, n) - took := make([]bool, n) - var q []int - for _, i := range initialBoxes { - has[i] = true - if status[i] == 1 { - ans += candies[i] - took[i] = true - q = append(q, i) +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) (ans int) { + q := []int{} + has := make(map[int]bool) + took := make(map[int]bool) + for _, box := range initialBoxes { + has[box] = true + if status[box] == 1 { + q = append(q, box) + took[box] = true + ans += candies[box] } } for len(q) > 0 { - i := q[0] + box := q[0] q = q[1:] - for _, k := range keys[i] { - status[k] = 1 - if has[k] && !took[k] { - ans += candies[k] - took[k] = true - q = append(q, k) + for _, k := range keys[box] { + if status[k] == 0 { + status[k] = 1 + if has[k] && !took[k] { + q = append(q, k) + took[k] = true + ans += candies[k] + } } } - for _, j := range containedBoxes[i] { - has[j] = true - if status[j] == 1 && !took[j] { - ans += candies[j] - took[j] = true - q = append(q, j) + for _, b := range containedBoxes[box] { + has[b] = true + if status[b] == 1 && !took[b] { + q = append(q, b) + took[b] = true + ans += candies[b] } } } - return ans + return +} +``` + +#### TypeScript + +```ts +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const q: number[] = []; + const has: Set = new Set(); + const took: Set = new Set(); + let ans = 0; + + for (const box of initialBoxes) { + has.add(box); + if (status[box] === 1) { + q.push(box); + took.add(box); + ans += candies[box]; + } + } + + while (q.length > 0) { + const box = q.pop()!; + + for (const k of keys[box]) { + if (status[k] === 0) { + status[k] = 1; + if (has.has(k) && !took.has(k)) { + q.push(k); + took.add(k); + ans += candies[k]; + } + } + } + + for (const b of containedBoxes[box]) { + has.add(b); + if (status[b] === 1 && !took.has(b)) { + q.push(b); + took.add(b); + ans += candies[b]; + } + } + } + + return ans; +} +``` + +#### Rust + +```rust +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn max_candies( + mut status: Vec , + candies: Vec , + keys: Vec >, + contained_boxes: Vec >, + initial_boxes: Vec , + ) -> i32 { + let mut q: VecDeque = VecDeque::new(); + let mut has: HashSet = HashSet::new(); + let mut took: HashSet = HashSet::new(); + let mut ans = 0; + + for &box_ in &initial_boxes { + has.insert(box_); + if status[box_ as usize] == 1 { + q.push_back(box_); + took.insert(box_); + ans += candies[box_ as usize]; + } + } + + while let Some(box_) = q.pop_front() { + for &k in &keys[box_ as usize] { + if status[k as usize] == 0 { + status[k as usize] = 1; + if has.contains(&k) && !took.contains(&k) { + q.push_back(k); + took.insert(k); + ans += candies[k as usize]; + } + } + } + + for &b in &contained_boxes[box_ as usize] { + has.insert(b); + if status[b as usize] == 1 && !took.contains(&b) { + q.push_back(b); + took.insert(b); + ans += candies[b as usize]; + } + } + } + + ans + } } ``` diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md index 206d86924e214..3e1c094f6f83d 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md @@ -79,7 +79,24 @@ The total number of candies will be 6. -### Solution 1 +### Solution 1: BFS + Hash Set + +The problem gives a set of boxes, each of which may have a state (open/closed), candies, keys, and other boxes inside. Our goal is to use the initially given boxes to open as many more boxes as possible and collect the candies inside. We can unlock new boxes by obtaining keys, and get more resources through boxes nested inside other boxes. + +We use BFS to simulate the entire exploration process. + +We use a queue $q$ to represent the currently accessible and **already opened** boxes; two sets, $\textit{has}$ and $\textit{took}$, are used to record **all boxes we own** and **boxes we have already processed**, to avoid duplicates. + +Initially, add all $\textit{initialBoxes}$ to $\textit{has}$. If an initial box is open, immediately add it to the queue $\textit{q}$ and accumulate its candies. + +Then perform BFS, taking boxes out of $\textit{q}$ one by one: + +- Obtain the keys in the box $\textit{keys[box]}$ and add any boxes that can be unlocked to the queue; +- Collect other boxes contained in the box $\textit{containedBoxes[box]}$. If a contained box is open and has not been processed, process it immediately; + +Each box is processed at most once, and candies are accumulated once. Finally, return the total number of candies $\textit{ans}$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the total number of boxes. @@ -95,25 +112,31 @@ class Solution: containedBoxes: List[List[int]], initialBoxes: List[int], ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} - + q = deque() + has, took = set(initialBoxes), set() + ans = 0 + + for box in initialBoxes: + if status[box]: + q.append(box) + took.add(box) + ans += candies[box] while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) + box = q.popleft() + for k in keys[box]: + if not status[k]: + status[k] = 1 + if k in has and k not in took: + q.append(k) + took.add(k) + ans += candies[k] + + for b in containedBoxes[box]: + has.add(b) + if status[b] and b not in took: + q.append(b) + took.add(b) + ans += candies[b] return ans ``` @@ -123,35 +146,36 @@ class Solution: class Solution { public int maxCandies( int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; Deque q = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); + Set has = new HashSet<>(); + Set took = new HashSet<>(); + int ans = 0; + for (int box : initialBoxes) { + has.add(box); + if (status[box] == 1) { + q.offer(box); + took.add(box); + ans += candies[box]; } } while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); + int box = q.poll(); + for (int k : keys[box]) { + if (status[k] == 0) { + status[k] = 1; + if (has.contains(k) && !took.contains(k)) { + q.offer(k); + took.add(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); + for (int b : containedBoxes[box]) { + has.add(b); + if (status[b] == 1 && !took.contains(b)) { + q.offer(b); + took.add(b); + ans += candies[b]; } } } @@ -165,40 +189,50 @@ class Solution { ```cpp class Solution { public: - int maxCandies(vector & status, vector & candies, vector >& keys, vector >& containedBoxes, vector & initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); + int maxCandies( + vector & status, + vector & candies, + vector >& keys, + vector >& containedBoxes, + vector & initialBoxes) { queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); + unordered_set has, took; + int ans = 0; + + for (int box : initialBoxes) { + has.insert(box); + if (status[box]) { + q.push(box); + took.insert(box); + ans += candies[box]; } } + while (!q.empty()) { - int i = q.front(); + int box = q.front(); q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); + + for (int k : keys[box]) { + if (!status[k]) { + status[k] = 1; + if (has.count(k) && !took.count(k)) { + q.push(k); + took.insert(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); + + for (int b : containedBoxes[box]) { + has.insert(b); + if (status[b] && !took.count(b)) { + q.push(b); + took.insert(b); + ans += candies[b]; } } } + return ans; } }; @@ -207,41 +241,147 @@ public: #### Go ```go -func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { - ans := 0 - n := len(status) - has := make([]bool, n) - took := make([]bool, n) - var q []int - for _, i := range initialBoxes { - has[i] = true - if status[i] == 1 { - ans += candies[i] - took[i] = true - q = append(q, i) +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) (ans int) { + q := []int{} + has := make(map[int]bool) + took := make(map[int]bool) + for _, box := range initialBoxes { + has[box] = true + if status[box] == 1 { + q = append(q, box) + took[box] = true + ans += candies[box] } } for len(q) > 0 { - i := q[0] + box := q[0] q = q[1:] - for _, k := range keys[i] { - status[k] = 1 - if has[k] && !took[k] { - ans += candies[k] - took[k] = true - q = append(q, k) + for _, k := range keys[box] { + if status[k] == 0 { + status[k] = 1 + if has[k] && !took[k] { + q = append(q, k) + took[k] = true + ans += candies[k] + } } } - for _, j := range containedBoxes[i] { - has[j] = true - if status[j] == 1 && !took[j] { - ans += candies[j] - took[j] = true - q = append(q, j) + for _, b := range containedBoxes[box] { + has[b] = true + if status[b] == 1 && !took[b] { + q = append(q, b) + took[b] = true + ans += candies[b] } } } - return ans + return +} +``` + +#### TypeScript + +```ts +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const q: number[] = []; + const has: Set = new Set(); + const took: Set = new Set(); + let ans = 0; + + for (const box of initialBoxes) { + has.add(box); + if (status[box] === 1) { + q.push(box); + took.add(box); + ans += candies[box]; + } + } + + while (q.length > 0) { + const box = q.pop()!; + + for (const k of keys[box]) { + if (status[k] === 0) { + status[k] = 1; + if (has.has(k) && !took.has(k)) { + q.push(k); + took.add(k); + ans += candies[k]; + } + } + } + + for (const b of containedBoxes[box]) { + has.add(b); + if (status[b] === 1 && !took.has(b)) { + q.push(b); + took.add(b); + ans += candies[b]; + } + } + } + + return ans; +} +``` + +#### Rust + +```rust +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn max_candies( + mut status: Vec , + candies: Vec , + keys: Vec >, + contained_boxes: Vec >, + initial_boxes: Vec , + ) -> i32 { + let mut q: VecDeque = VecDeque::new(); + let mut has: HashSet = HashSet::new(); + let mut took: HashSet = HashSet::new(); + let mut ans = 0; + + for &box_ in &initial_boxes { + has.insert(box_); + if status[box_ as usize] == 1 { + q.push_back(box_); + took.insert(box_); + ans += candies[box_ as usize]; + } + } + + while let Some(box_) = q.pop_front() { + for &k in &keys[box_ as usize] { + if status[k as usize] == 0 { + status[k as usize] = 1; + if has.contains(&k) && !took.contains(&k) { + q.push_back(k); + took.insert(k); + ans += candies[k as usize]; + } + } + } + + for &b in &contained_boxes[box_ as usize] { + has.insert(b); + if status[b as usize] == 1 && !took.contains(&b) { + q.push_back(b); + took.insert(b); + ans += candies[b as usize]; + } + } + } + + ans + } } ``` diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp index 7b85217a5a1f3..fffc87bc0c3df 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp @@ -1,39 +1,49 @@ class Solution { public: - int maxCandies(vector & status, vector & candies, vector >& keys, vector >& containedBoxes, vector & initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); + int maxCandies( + vector & status, + vector & candies, + vector >& keys, + vector >& containedBoxes, + vector & initialBoxes) { queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); + unordered_set has, took; + int ans = 0; + + for (int box : initialBoxes) { + has.insert(box); + if (status[box]) { + q.push(box); + took.insert(box); + ans += candies[box]; } } + while (!q.empty()) { - int i = q.front(); + int box = q.front(); q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); + + for (int k : keys[box]) { + if (!status[k]) { + status[k] = 1; + if (has.count(k) && !took.count(k)) { + q.push(k); + took.insert(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); + + for (int b : containedBoxes[box]) { + has.insert(b); + if (status[b] && !took.count(b)) { + q.push(b); + took.insert(b); + ans += candies[b]; } } } + return ans; } -}; \ No newline at end of file +}; diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go index 4ff69d070109e..610853ade8f02 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go @@ -1,36 +1,36 @@ -func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { - ans := 0 - n := len(status) - has := make([]bool, n) - took := make([]bool, n) - var q []int - for _, i := range initialBoxes { - has[i] = true - if status[i] == 1 { - ans += candies[i] - took[i] = true - q = append(q, i) +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) (ans int) { + q := []int{} + has := make(map[int]bool) + took := make(map[int]bool) + for _, box := range initialBoxes { + has[box] = true + if status[box] == 1 { + q = append(q, box) + took[box] = true + ans += candies[box] } } for len(q) > 0 { - i := q[0] + box := q[0] q = q[1:] - for _, k := range keys[i] { - status[k] = 1 - if has[k] && !took[k] { - ans += candies[k] - took[k] = true - q = append(q, k) + for _, k := range keys[box] { + if status[k] == 0 { + status[k] = 1 + if has[k] && !took[k] { + q = append(q, k) + took[k] = true + ans += candies[k] + } } } - for _, j := range containedBoxes[i] { - has[j] = true - if status[j] == 1 && !took[j] { - ans += candies[j] - took[j] = true - q = append(q, j) + for _, b := range containedBoxes[box] { + has[b] = true + if status[b] == 1 && !took[b] { + q = append(q, b) + took[b] = true + ans += candies[b] } } } - return ans -} \ No newline at end of file + return +} diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java index 3d9e243bfdfa3..d473b7305010c 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java @@ -1,38 +1,39 @@ class Solution { public int maxCandies( int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; Deque q = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); + Set has = new HashSet<>(); + Set took = new HashSet<>(); + int ans = 0; + for (int box : initialBoxes) { + has.add(box); + if (status[box] == 1) { + q.offer(box); + took.add(box); + ans += candies[box]; } } while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); + int box = q.poll(); + for (int k : keys[box]) { + if (status[k] == 0) { + status[k] = 1; + if (has.contains(k) && !took.contains(k)) { + q.offer(k); + took.add(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); + for (int b : containedBoxes[box]) { + has.add(b); + if (status[b] == 1 && !took.contains(b)) { + q.offer(b); + took.add(b); + ans += candies[b]; } } } return ans; } -} \ No newline at end of file +} diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py index fe996159a7a50..2aed0b52ec7ef 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py @@ -7,23 +7,29 @@ def maxCandies( containedBoxes: List[List[int]], initialBoxes: List[int], ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} + q = deque() + has, took = set(initialBoxes), set() + ans = 0 + for box in initialBoxes: + if status[box]: + q.append(box) + took.add(box) + ans += candies[box] while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) + box = q.popleft() + for k in keys[box]: + if not status[k]: + status[k] = 1 + if k in has and k not in took: + q.append(k) + took.add(k) + ans += candies[k] + + for b in containedBoxes[box]: + has.add(b) + if status[b] and b not in took: + q.append(b) + took.add(b) + ans += candies[b] return ans diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.rs b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.rs new file mode 100644 index 0000000000000..852f702b4d83e --- /dev/null +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.rs @@ -0,0 +1,49 @@ +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn max_candies( + mut status: Vec , + candies: Vec , + keys: Vec >, + contained_boxes: Vec >, + initial_boxes: Vec , + ) -> i32 { + let mut q: VecDeque = VecDeque::new(); + let mut has: HashSet = HashSet::new(); + let mut took: HashSet = HashSet::new(); + let mut ans = 0; + + for &box_ in &initial_boxes { + has.insert(box_); + if status[box_ as usize] == 1 { + q.push_back(box_); + took.insert(box_); + ans += candies[box_ as usize]; + } + } + + while let Some(box_) = q.pop_front() { + for &k in &keys[box_ as usize] { + if status[k as usize] == 0 { + status[k as usize] = 1; + if has.contains(&k) && !took.contains(&k) { + q.push_back(k); + took.insert(k); + ans += candies[k as usize]; + } + } + } + + for &b in &contained_boxes[box_ as usize] { + has.insert(b); + if status[b as usize] == 1 && !took.contains(&b) { + q.push_back(b); + took.insert(b); + ans += candies[b as usize]; + } + } + } + + ans + } +} diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.ts b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.ts new file mode 100644 index 0000000000000..4a6b7feaa674e --- /dev/null +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.ts @@ -0,0 +1,47 @@ +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const q: number[] = []; + const has: Set = new Set(); + const took: Set = new Set(); + let ans = 0; + + for (const box of initialBoxes) { + has.add(box); + if (status[box] === 1) { + q.push(box); + took.add(box); + ans += candies[box]; + } + } + + while (q.length > 0) { + const box = q.pop()!; + + for (const k of keys[box]) { + if (status[k] === 0) { + status[k] = 1; + if (has.has(k) && !took.has(k)) { + q.push(k); + took.add(k); + ans += candies[k]; + } + } + } + + for (const b of containedBoxes[box]) { + has.add(b); + if (status[b] === 1 && !took.has(b)) { + q.push(b); + took.add(b); + ans += candies[b]; + } + } + } + + return ans; +} diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md index e9ae14167981a..42f8aab8492d8 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md +++ b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md @@ -29,21 +29,35 @@ tags: In case there is no path, return
[0, 0]
.+
Example 1:
+Input: board = ["E23","2X2","12S"] + Output: [7,1] +Example 2:
+Input: board = ["E12","1X1","21S"] + Output: [4,2] +Example 3:
+Input: board = ["E11","XXX","11S"] + Output: [0,0] +++
Constraints:
-
diff --git a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md index 25cf3e136deec..5d94e91fb76df 100644 --- a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md +++ b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md @@ -19,39 +19,55 @@ tags:- + +
2 <= board.length == board[i].length <= 100
- +
2 <= board.length == board[i].length <= 100
Given 3 positives numbers
a
,b
andc
. Return the minimum flips required in some bits ofa
andb
to make (a
ORb
==c
). (bitwise OR operation).
+ Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.+
Example 1:
+ Input: a = 2, b = 6, c = 5 + Output: 3 + Explanation: After flips a = 1 , b = 4 , c = 5 such that (a
ORb
==c
)Example 2:
+ Input: a = 4, b = 2, c = 7 + Output: 1 +Example 3:
+ Input: a = 1, b = 2, c = 3 + Output: 0 ++
Constraints:
-
diff --git a/solution/1300-1399/1324.Print Words Vertically/README_EN.md b/solution/1300-1399/1324.Print Words Vertically/README_EN.md index e1542d061c72f..c86ec25b2c2cb 100644 --- a/solution/1300-1399/1324.Print Words Vertically/README_EN.md +++ b/solution/1300-1399/1324.Print Words Vertically/README_EN.md @@ -21,46 +21,71 @@ tags:- -
1 <= a <= 10^9
- -
1 <= b <= 10^9
- + +
1 <= c <= 10^9
- + +
1 <= a <= 10^9
- + +
1 <= b <= 10^9
- +
1 <= c <= 10^9
Given a string
s
. Return all the words vertically in the same order in which they appear ins
.
+ Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
+ Each word would be put on only one column and that in one column there will be only one word.+
Example 1:
+ Input: s = "HOW ARE YOU" + Output: ["HAY","ORO","WEU"] + Explanation: Each word is printed vertically. + "HAY" + "ORO" + "WEU" +Example 2:
+ Input: s = "TO BE OR NOT TO BE" + Output: ["TBONTB","OEROOE"," T"] + Explanation: Trailing spaces is not allowed. + "TBONTB" + "OEROOE" + " T" +Example 3:
+ Input: s = "CONTEST IS COMING" + Output: ["CIC","OSO","N M","T I","E N","S G","T"] ++
Constraints:
-
diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md index 20c633d1c9fe2..83f740df319b5 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md @@ -30,7 +30,7 @@ tags:- -
1 <= s.length <= 200
- -
s
contains only upper case English letters.- It's guaranteed that there is only one space between 2 words.
+ +- + +
1 <= s.length <= 200
- + +
s
contains only upper case English letters.- It's guaranteed that there is only one space between 2 words.
+示例 1:
-+
输入:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 @@ -46,7 +46,7 @@ tags:示例 2:
-+
输入:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 diff --git a/solution/1300-1399/1340.Jump Game V/README.md b/solution/1300-1399/1340.Jump Game V/README.md index 0660b49704759..b51d004488eaa 100644 --- a/solution/1300-1399/1340.Jump Game V/README.md +++ b/solution/1300-1399/1340.Jump Game V/README.md @@ -280,9 +280,7 @@ class Solution { public int maxJumps(int[] arr, int d) { int n = arr.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); int[] f = new int[n]; Arrays.fill(f, 1); diff --git a/solution/1300-1399/1340.Jump Game V/README_EN.md b/solution/1300-1399/1340.Jump Game V/README_EN.md index 96a1c9e3a29e9..d502c5e896373 100644 --- a/solution/1300-1399/1340.Jump Game V/README_EN.md +++ b/solution/1300-1399/1340.Jump Game V/README_EN.md @@ -251,9 +251,7 @@ class Solution { public int maxJumps(int[] arr, int d) { int n = arr.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); int[] f = new int[n]; Arrays.fill(f, 1); diff --git a/solution/1300-1399/1340.Jump Game V/Solution2.java b/solution/1300-1399/1340.Jump Game V/Solution2.java index 7eadbd4bb0a0a..9dd9b724cefe3 100644 --- a/solution/1300-1399/1340.Jump Game V/Solution2.java +++ b/solution/1300-1399/1340.Jump Game V/Solution2.java @@ -2,9 +2,7 @@ class Solution { public int maxJumps(int[] arr, int d) { int n = arr.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); int[] f = new int[n]; Arrays.fill(f, 1); diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md index 1cbd1775a10f1..350c5c527eb1d 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md @@ -68,13 +68,17 @@ tags: ### 方法一:哈希表 + 贪心 + 优先队列 -定义哈希表记录每个会议的开始和结束时间,其中键为会议开始时间,值为结束时间列表。 +我们用一个哈希表 $\textit{g}$ 记录每个会议的开始和结束时间。键为会议的开始时间,值为一个列表,包含所有在该开始时间开始的会议的结束时间。用两个变量 $\textit{l}$ 和 $\textit{r}$ 分别记录会议的最小开始时间和最大结束时间。 -枚举当前时间 $s$,找出所有开始时间等于当前时间的会议,将其结束时间加入优先队列(小根堆)中。同时,优先队列要移除所有结束时间小于当前时间的会议。 +对于从小到大每个在 $\textit{l}$ 到 $\textit{r}$ 的时间点 $s$,我们需要做以下操作: -然后从优先队列中取出结束时间最小的会议,即为当前时间可以参加的会议,累加答案数。如果优先队列为空,则说明当前时间没有可以参加的会议。 +1. 从优先队列中移除所有结束时间小于当前时间 $s$ 的会议。 +2. 将所有开始时间等于当前时间 $s$ 的会议的结束时间加入优先队列中。 +3. 如果优先队列不为空,则取出结束时间最小的会议,累加答案数,并从优先队列中移除该会议。 -时间复杂度 $O(m \times \log n)$,空间复杂度 $O(n)$。其中 $m$, $n$ 分别表示会议的最大结束时间,以及会议的数量。 +这样,我们可以确保在每个时间点 $s$,我们都能参加结束时间最早的会议,从而最大化参加的会议数。 + +时间复杂度 $O(M \times \log n)$,空间复杂度 $O(n)$,其中 $M$ 和 $n$ 分别为会议的最大结束时间和会议的数量。 @@ -83,22 +87,22 @@ tags: ```python class Solution: def maxEvents(self, events: List[List[int]]) -> int: - d = defaultdict(list) - i, j = inf, 0 + g = defaultdict(list) + l, r = inf, 0 for s, e in events: - d[s].append(e) - i = min(i, s) - j = max(j, e) - h = [] + g[s].append(e) + l = min(l, s) + r = max(r, e) + pq = [] ans = 0 - for s in range(i, j + 1): - while h and h[0] < s: - heappop(h) - for e in d[s]: - heappush(h, e) - if h: + for s in range(l, r + 1): + while pq and pq[0] < s: + heappop(pq) + for e in g[s]: + heappush(pq, e) + if pq: + heappop(pq) ans += 1 - heappop(h) return ans ``` @@ -107,26 +111,26 @@ class Solution: ```java class Solution { public int maxEvents(int[][] events) { - Mapdiff --git a/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md b/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md index 429cfe2142d4e..d7708d65d82ee 100644 --- a/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md +++ b/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md @@ -27,8 +27,11 @@ tags:> d = new HashMap<>(); - int i = Integer.MAX_VALUE, j = 0; - for (var v : events) { - int s = v[0], e = v[1]; - d.computeIfAbsent(s, k -> new ArrayList<>()).add(e); - i = Math.min(i, s); - j = Math.max(j, e); + Map > g = new HashMap<>(); + int l = Integer.MAX_VALUE, r = 0; + for (int[] event : events) { + int s = event[0], e = event[1]; + g.computeIfAbsent(s, k -> new ArrayList<>()).add(e); + l = Math.min(l, s); + r = Math.max(r, e); } - PriorityQueue q = new PriorityQueue<>(); + PriorityQueue pq = new PriorityQueue<>(); int ans = 0; - for (int s = i; s <= j; ++s) { - while (!q.isEmpty() && q.peek() < s) { - q.poll(); + for (int s = l; s <= r; s++) { + while (!pq.isEmpty() && pq.peek() < s) { + pq.poll(); } - for (int e : d.getOrDefault(s, Collections.emptyList())) { - q.offer(e); + for (int e : g.getOrDefault(s, List.of())) { + pq.offer(e); } - if (!q.isEmpty()) { - q.poll(); - ++ans; + if (!pq.isEmpty()) { + pq.poll(); + ans++; } } return ans; @@ -140,26 +144,26 @@ class Solution { class Solution { public: int maxEvents(vector >& events) { - unordered_map > d; - int i = INT_MAX, j = 0; - for (auto& v : events) { - int s = v[0], e = v[1]; - d[s].push_back(e); - i = min(i, s); - j = max(j, e); + unordered_map > g; + int l = INT_MAX, r = 0; + for (auto& event : events) { + int s = event[0], e = event[1]; + g[s].push_back(e); + l = min(l, s); + r = max(r, e); } - priority_queue , greater > q; + priority_queue , greater > pq; int ans = 0; - for (int s = i; s <= j; ++s) { - while (q.size() && q.top() < s) { - q.pop(); + for (int s = l; s <= r; ++s) { + while (!pq.empty() && pq.top() < s) { + pq.pop(); } - for (int e : d[s]) { - q.push(e); + for (int e : g[s]) { + pq.push(e); } - if (q.size()) { + if (!pq.empty()) { + pq.pop(); ++ans; - q.pop(); } } return ans; @@ -170,44 +174,123 @@ public: #### Go ```go -func maxEvents(events [][]int) int { - d := map[int][]int{} - i, j := math.MaxInt32, 0 - for _, v := range events { - s, e := v[0], v[1] - d[s] = append(d[s], e) - i = min(i, s) - j = max(j, e) +func maxEvents(events [][]int) (ans int) { + g := map[int][]int{} + l, r := math.MaxInt32, 0 + for _, event := range events { + s, e := event[0], event[1] + g[s] = append(g[s], e) + l = min(l, s) + r = max(r, e) } - q := hp{} - ans := 0 - for s := i; s <= j; s++ { - for q.Len() > 0 && q.IntSlice[0] < s { - heap.Pop(&q) + + pq := &hp{} + heap.Init(pq) + for s := l; s <= r; s++ { + for pq.Len() > 0 && pq.IntSlice[0] < s { + heap.Pop(pq) } - for _, e := range d[s] { - heap.Push(&q, e) + for _, e := range g[s] { + heap.Push(pq, e) } - if q.Len() > 0 { - heap.Pop(&q) + if pq.Len() > 0 { + heap.Pop(pq) ans++ } } - return ans + return } type hp struct{ sort.IntSlice } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { - a := h.IntSlice - v := a[len(a)-1] - h.IntSlice = a[:len(a)-1] + n := len(h.IntSlice) + v := h.IntSlice[n-1] + h.IntSlice = h.IntSlice[:n-1] return v } func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } ``` +#### TypeScript + +```ts +function maxEvents(events: number[][]): number { + const g: Map = new Map(); + let l = Infinity, + r = 0; + for (const [s, e] of events) { + if (!g.has(s)) g.set(s, []); + g.get(s)!.push(e); + l = Math.min(l, s); + r = Math.max(r, e); + } + + const pq = new MinPriorityQueue (); + let ans = 0; + for (let s = l; s <= r; s++) { + while (!pq.isEmpty() && pq.front() < s) { + pq.dequeue(); + } + for (const e of g.get(s) || []) { + pq.enqueue(e); + } + if (!pq.isEmpty()) { + pq.dequeue(); + ans++; + } + } + return ans; +} +``` + +#### Rust + +```rust +use std::collections::{BinaryHeap, HashMap}; +use std::cmp::Reverse; + +impl Solution { + pub fn max_events(events: Vec >) -> i32 { + let mut g: HashMap > = HashMap::new(); + let mut l = i32::MAX; + let mut r = 0; + + for event in events { + let s = event[0]; + let e = event[1]; + g.entry(s).or_default().push(e); + l = l.min(s); + r = r.max(e); + } + + let mut pq = BinaryHeap::new(); + let mut ans = 0; + + for s in l..=r { + while let Some(&Reverse(top)) = pq.peek() { + if top < s { + pq.pop(); + } else { + break; + } + } + if let Some(ends) = g.get(&s) { + for &e in ends { + pq.push(Reverse(e)); + } + } + if pq.pop().is_some() { + ans += 1; + } + } + + ans + } +} +``` + diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md index 42234ff46dddb..f24de3d125ff9 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md @@ -64,13 +64,17 @@ Attend the third event on day 3. ### Solution 1: Hash Table + Greedy + Priority Queue -Define a hash table to record the start and end times of each meeting, where the key is the start time of the meeting, and the value is a list of end times. +We use a hash table $\textit{g}$ to record the start and end times of each event. The key is the start time of the event, and the value is a list containing the end times of all events that start at that time. Two variables, $\textit{l}$ and $\textit{r}$, are used to record the minimum start time and the maximum end time among all events. -Enumerate the current time $s$, find all meetings that start at the current time, and add their end times to the priority queue (min heap). At the same time, the priority queue needs to remove all meetings that end before the current time. +For each time point $s$ from $\textit{l}$ to $\textit{r}$ in increasing order, we perform the following steps: -Then, take out the meeting with the smallest end time from the priority queue, which is the meeting that can be attended at the current time, and accumulate the answer count. If the priority queue is empty, it means that there are no meetings that can be attended at the current time. +1. Remove from the priority queue all events whose end time is less than the current time $s$. +2. Add the end times of all events that start at the current time $s$ to the priority queue. +3. If the priority queue is not empty, take out the event with the earliest end time, increment the answer count, and remove this event from the priority queue. -The time complexity is $O(m \times \log n)$, and the space complexity is $O(n)$. Where $m$ and $n$ represent the maximum end time of the meetings and the number of meetings, respectively. +In this way, we ensure that at each time point $s$, we always attend the event that ends the earliest, thus maximizing the number of events attended. + +The time complexity is $O(M \times \log n)$, and the space complexity is $O(n)$, where $M$ is the maximum end time and $n$ is the number of events. @@ -79,22 +83,22 @@ The time complexity is $O(m \times \log n)$, and the space complexity is $O(n)$. ```python class Solution: def maxEvents(self, events: List[List[int]]) -> int: - d = defaultdict(list) - i, j = inf, 0 + g = defaultdict(list) + l, r = inf, 0 for s, e in events: - d[s].append(e) - i = min(i, s) - j = max(j, e) - h = [] + g[s].append(e) + l = min(l, s) + r = max(r, e) + pq = [] ans = 0 - for s in range(i, j + 1): - while h and h[0] < s: - heappop(h) - for e in d[s]: - heappush(h, e) - if h: + for s in range(l, r + 1): + while pq and pq[0] < s: + heappop(pq) + for e in g[s]: + heappush(pq, e) + if pq: + heappop(pq) ans += 1 - heappop(h) return ans ``` @@ -103,26 +107,26 @@ class Solution: ```java class Solution { public int maxEvents(int[][] events) { - Map > d = new HashMap<>(); - int i = Integer.MAX_VALUE, j = 0; - for (var v : events) { - int s = v[0], e = v[1]; - d.computeIfAbsent(s, k -> new ArrayList<>()).add(e); - i = Math.min(i, s); - j = Math.max(j, e); + Map > g = new HashMap<>(); + int l = Integer.MAX_VALUE, r = 0; + for (int[] event : events) { + int s = event[0], e = event[1]; + g.computeIfAbsent(s, k -> new ArrayList<>()).add(e); + l = Math.min(l, s); + r = Math.max(r, e); } - PriorityQueue q = new PriorityQueue<>(); + PriorityQueue pq = new PriorityQueue<>(); int ans = 0; - for (int s = i; s <= j; ++s) { - while (!q.isEmpty() && q.peek() < s) { - q.poll(); + for (int s = l; s <= r; s++) { + while (!pq.isEmpty() && pq.peek() < s) { + pq.poll(); } - for (int e : d.getOrDefault(s, Collections.emptyList())) { - q.offer(e); + for (int e : g.getOrDefault(s, List.of())) { + pq.offer(e); } - if (!q.isEmpty()) { - q.poll(); - ++ans; + if (!pq.isEmpty()) { + pq.poll(); + ans++; } } return ans; @@ -136,26 +140,26 @@ class Solution { class Solution { public: int maxEvents(vector >& events) { - unordered_map > d; - int i = INT_MAX, j = 0; - for (auto& v : events) { - int s = v[0], e = v[1]; - d[s].push_back(e); - i = min(i, s); - j = max(j, e); + unordered_map > g; + int l = INT_MAX, r = 0; + for (auto& event : events) { + int s = event[0], e = event[1]; + g[s].push_back(e); + l = min(l, s); + r = max(r, e); } - priority_queue , greater > q; + priority_queue , greater > pq; int ans = 0; - for (int s = i; s <= j; ++s) { - while (q.size() && q.top() < s) { - q.pop(); + for (int s = l; s <= r; ++s) { + while (!pq.empty() && pq.top() < s) { + pq.pop(); } - for (int e : d[s]) { - q.push(e); + for (int e : g[s]) { + pq.push(e); } - if (q.size()) { + if (!pq.empty()) { + pq.pop(); ++ans; - q.pop(); } } return ans; @@ -166,44 +170,123 @@ public: #### Go ```go -func maxEvents(events [][]int) int { - d := map[int][]int{} - i, j := math.MaxInt32, 0 - for _, v := range events { - s, e := v[0], v[1] - d[s] = append(d[s], e) - i = min(i, s) - j = max(j, e) +func maxEvents(events [][]int) (ans int) { + g := map[int][]int{} + l, r := math.MaxInt32, 0 + for _, event := range events { + s, e := event[0], event[1] + g[s] = append(g[s], e) + l = min(l, s) + r = max(r, e) } - q := hp{} - ans := 0 - for s := i; s <= j; s++ { - for q.Len() > 0 && q.IntSlice[0] < s { - heap.Pop(&q) + + pq := &hp{} + heap.Init(pq) + for s := l; s <= r; s++ { + for pq.Len() > 0 && pq.IntSlice[0] < s { + heap.Pop(pq) } - for _, e := range d[s] { - heap.Push(&q, e) + for _, e := range g[s] { + heap.Push(pq, e) } - if q.Len() > 0 { - heap.Pop(&q) + if pq.Len() > 0 { + heap.Pop(pq) ans++ } } - return ans + return } type hp struct{ sort.IntSlice } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { - a := h.IntSlice - v := a[len(a)-1] - h.IntSlice = a[:len(a)-1] + n := len(h.IntSlice) + v := h.IntSlice[n-1] + h.IntSlice = h.IntSlice[:n-1] return v } func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } ``` +#### TypeScript + +```ts +function maxEvents(events: number[][]): number { + const g: Map = new Map(); + let l = Infinity, + r = 0; + for (const [s, e] of events) { + if (!g.has(s)) g.set(s, []); + g.get(s)!.push(e); + l = Math.min(l, s); + r = Math.max(r, e); + } + + const pq = new MinPriorityQueue (); + let ans = 0; + for (let s = l; s <= r; s++) { + while (!pq.isEmpty() && pq.front() < s) { + pq.dequeue(); + } + for (const e of g.get(s) || []) { + pq.enqueue(e); + } + if (!pq.isEmpty()) { + pq.dequeue(); + ans++; + } + } + return ans; +} +``` + +#### Rust + +```rust +use std::collections::{BinaryHeap, HashMap}; +use std::cmp::Reverse; + +impl Solution { + pub fn max_events(events: Vec >) -> i32 { + let mut g: HashMap > = HashMap::new(); + let mut l = i32::MAX; + let mut r = 0; + + for event in events { + let s = event[0]; + let e = event[1]; + g.entry(s).or_default().push(e); + l = l.min(s); + r = r.max(e); + } + + let mut pq = BinaryHeap::new(); + let mut ans = 0; + + for s in l..=r { + while let Some(&Reverse(top)) = pq.peek() { + if top < s { + pq.pop(); + } else { + break; + } + } + if let Some(ends) = g.get(&s) { + for &e in ends { + pq.push(Reverse(e)); + } + } + if pq.pop().is_some() { + ans += 1; + } + } + + ans + } +} +``` + diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.cpp b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.cpp index b606f12f54a94..bff232aed16a4 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.cpp +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.cpp @@ -1,28 +1,28 @@ class Solution { public: int maxEvents(vector >& events) { - unordered_map > d; - int i = INT_MAX, j = 0; - for (auto& v : events) { - int s = v[0], e = v[1]; - d[s].push_back(e); - i = min(i, s); - j = max(j, e); + unordered_map > g; + int l = INT_MAX, r = 0; + for (auto& event : events) { + int s = event[0], e = event[1]; + g[s].push_back(e); + l = min(l, s); + r = max(r, e); } - priority_queue , greater > q; + priority_queue , greater > pq; int ans = 0; - for (int s = i; s <= j; ++s) { - while (q.size() && q.top() < s) { - q.pop(); + for (int s = l; s <= r; ++s) { + while (!pq.empty() && pq.top() < s) { + pq.pop(); } - for (int e : d[s]) { - q.push(e); + for (int e : g[s]) { + pq.push(e); } - if (q.size()) { + if (!pq.empty()) { + pq.pop(); ++ans; - q.pop(); } } return ans; } -}; \ No newline at end of file +}; diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.go b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.go index df48690182d72..1b5722cd4a3a2 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.go +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.go @@ -1,36 +1,37 @@ -func maxEvents(events [][]int) int { - d := map[int][]int{} - i, j := math.MaxInt32, 0 - for _, v := range events { - s, e := v[0], v[1] - d[s] = append(d[s], e) - i = min(i, s) - j = max(j, e) +func maxEvents(events [][]int) (ans int) { + g := map[int][]int{} + l, r := math.MaxInt32, 0 + for _, event := range events { + s, e := event[0], event[1] + g[s] = append(g[s], e) + l = min(l, s) + r = max(r, e) } - q := hp{} - ans := 0 - for s := i; s <= j; s++ { - for q.Len() > 0 && q.IntSlice[0] < s { - heap.Pop(&q) + + pq := &hp{} + heap.Init(pq) + for s := l; s <= r; s++ { + for pq.Len() > 0 && pq.IntSlice[0] < s { + heap.Pop(pq) } - for _, e := range d[s] { - heap.Push(&q, e) + for _, e := range g[s] { + heap.Push(pq, e) } - if q.Len() > 0 { - heap.Pop(&q) + if pq.Len() > 0 { + heap.Pop(pq) ans++ } } - return ans + return } type hp struct{ sort.IntSlice } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { - a := h.IntSlice - v := a[len(a)-1] - h.IntSlice = a[:len(a)-1] + n := len(h.IntSlice) + v := h.IntSlice[n-1] + h.IntSlice = h.IntSlice[:n-1] return v } -func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } \ No newline at end of file +func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.java b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.java index 55ae438150200..f85ae216d53f4 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.java +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.java @@ -1,27 +1,27 @@ class Solution { public int maxEvents(int[][] events) { - Map > d = new HashMap<>(); - int i = Integer.MAX_VALUE, j = 0; - for (var v : events) { - int s = v[0], e = v[1]; - d.computeIfAbsent(s, k -> new ArrayList<>()).add(e); - i = Math.min(i, s); - j = Math.max(j, e); + Map > g = new HashMap<>(); + int l = Integer.MAX_VALUE, r = 0; + for (int[] event : events) { + int s = event[0], e = event[1]; + g.computeIfAbsent(s, k -> new ArrayList<>()).add(e); + l = Math.min(l, s); + r = Math.max(r, e); } - PriorityQueue q = new PriorityQueue<>(); + PriorityQueue pq = new PriorityQueue<>(); int ans = 0; - for (int s = i; s <= j; ++s) { - while (!q.isEmpty() && q.peek() < s) { - q.poll(); + for (int s = l; s <= r; s++) { + while (!pq.isEmpty() && pq.peek() < s) { + pq.poll(); } - for (int e : d.getOrDefault(s, Collections.emptyList())) { - q.offer(e); + for (int e : g.getOrDefault(s, List.of())) { + pq.offer(e); } - if (!q.isEmpty()) { - q.poll(); - ++ans; + if (!pq.isEmpty()) { + pq.poll(); + ans++; } } return ans; } -} \ No newline at end of file +} diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.py b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.py index c8f9fd352a5b7..0d32d73265ae6 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.py +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.py @@ -1,19 +1,19 @@ class Solution: def maxEvents(self, events: List[List[int]]) -> int: - d = defaultdict(list) - i, j = inf, 0 + g = defaultdict(list) + l, r = inf, 0 for s, e in events: - d[s].append(e) - i = min(i, s) - j = max(j, e) - h = [] + g[s].append(e) + l = min(l, s) + r = max(r, e) + pq = [] ans = 0 - for s in range(i, j + 1): - while h and h[0] < s: - heappop(h) - for e in d[s]: - heappush(h, e) - if h: + for s in range(l, r + 1): + while pq and pq[0] < s: + heappop(pq) + for e in g[s]: + heappush(pq, e) + if pq: + heappop(pq) ans += 1 - heappop(h) return ans diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.rs b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.rs new file mode 100644 index 0000000000000..8655f8f45b8c3 --- /dev/null +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.rs @@ -0,0 +1,41 @@ +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap}; + +impl Solution { + pub fn max_events(events: Vec >) -> i32 { + let mut g: HashMap > = HashMap::new(); + let mut l = i32::MAX; + let mut r = 0; + + for event in events { + let s = event[0]; + let e = event[1]; + g.entry(s).or_default().push(e); + l = l.min(s); + r = r.max(e); + } + + let mut pq = BinaryHeap::new(); + let mut ans = 0; + + for s in l..=r { + while let Some(&Reverse(top)) = pq.peek() { + if top < s { + pq.pop(); + } else { + break; + } + } + if let Some(ends) = g.get(&s) { + for &e in ends { + pq.push(Reverse(e)); + } + } + if pq.pop().is_some() { + ans += 1; + } + } + + ans + } +} diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.ts b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.ts new file mode 100644 index 0000000000000..fe09e3bbc62a7 --- /dev/null +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/Solution.ts @@ -0,0 +1,27 @@ +function maxEvents(events: number[][]): number { + const g: Map = new Map(); + let l = Infinity, + r = 0; + for (const [s, e] of events) { + if (!g.has(s)) g.set(s, []); + g.get(s)!.push(e); + l = Math.min(l, s); + r = Math.max(r, e); + } + + const pq = new MinPriorityQueue (); + let ans = 0; + for (let s = l; s <= r; s++) { + while (!pq.isEmpty() && pq.front() < s) { + pq.dequeue(); + } + for (const e of g.get(s) || []) { + pq.enqueue(e); + } + if (!pq.isEmpty()) { + pq.dequeue(); + ans++; + } + } + return ans; +} diff --git a/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md b/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md index 85728f8ff86c4..6ee738a4c99d0 100644 --- a/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md +++ b/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md @@ -18,7 +18,7 @@ tags: - You have a 1-indexed binary string of length
+n
where all the bits are0
initially. We will flip all the bits of this binary string (i.e., change them from0
to1
) one by one. You are given a 1-indexed integer arrayflips
whereflips[i]
indicates that the bit at indexi
will be flipped in theith
step.You have a 1-indexed binary string of length
n
where all the bits are0
initially. We will flip all the bits of this binary string (i.e., change them from0
to1
) one by one. You are given a 1-indexed integer arrayflips
whereflips[i]
indicates that the bit at indexflips[i]
will be flipped in theith
step.A binary string is prefix-aligned if, after the
diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md b/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md index ad8e3171ec677..e2aab03d4d2ff 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md @@ -81,9 +81,9 @@ tags: ### 方法一:计数 -我们可以用哈希表或数组 $cnt$ 统计 $arr$ 中每个数字出现的次数,然后遍历 $cnt$,找到满足 $cnt[x] = x$ 的最大的 $x$ 即可。如果没有这样的 $x$,则返回 $-1$。 +我们可以用哈希表或数组 $\textit{cnt}$ 统计 $\textit{arr}$ 中每个数字出现的次数,然后遍历 $\textit{cnt}$,找到满足 $\textit{cnt}[x] = x$ 的最大的 $x$ 即可。如果没有这样的 $x$,则返回 $-1$。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 $arr$ 的长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 $\textit{arr}$ 的长度。 @@ -93,11 +93,7 @@ tags: class Solution: def findLucky(self, arr: List[int]) -> int: cnt = Counter(arr) - ans = -1 - for x, v in cnt.items(): - if x == v and ans < x: - ans = x - return ans + return max((x for x, v in cnt.items() if x == v), default=-1) ``` #### Java @@ -105,17 +101,16 @@ class Solution: ```java class Solution { public int findLucky(int[] arr) { - int[] cnt = new int[510]; - for (int x : cnt) { + int[] cnt = new int[501]; + for (int x : arr) { ++cnt[x]; } - int ans = -1; - for (int x = 1; x < cnt.length; ++x) { - if (cnt[x] == x) { - ans = x; + for (int x = cnt.length - 1; x > 0; --x) { + if (x == cnt[x]) { + return x; } } - return ans; + return -1; } } ``` @@ -126,18 +121,16 @@ class Solution { class Solution { public: int findLucky(vectorith
step, all the bits in the inclusive range[1, i]
are ones and all the other bits are zeros.& arr) { - int cnt[510]; - memset(cnt, 0, sizeof(cnt)); + int cnt[501]{}; for (int x : arr) { ++cnt[x]; } - int ans = -1; - for (int x = 1; x < 510; ++x) { - if (cnt[x] == x) { - ans = x; + for (int x = 500; x; --x) { + if (x == cnt[x]) { + return x; } } - return ans; + return -1; } }; ``` @@ -146,17 +139,16 @@ public: ```go func findLucky(arr []int) int { - cnt := [510]int{} + cnt := [501]int{} for _, x := range arr { cnt[x]++ } - ans := -1 - for x := 1; x < len(cnt); x++ { - if cnt[x] == x { - ans = x + for x := len(cnt) - 1; x > 0; x-- { + if x == cnt[x] { + return x } } - return ans + return -1 } ``` @@ -164,17 +156,34 @@ func findLucky(arr []int) int { ```ts function findLucky(arr: number[]): number { - const cnt = Array(510).fill(0); + const cnt: number[] = Array(501).fill(0); for (const x of arr) { ++cnt[x]; } - let ans = -1; - for (let x = 1; x < cnt.length; ++x) { - if (cnt[x] === x) { - ans = x; + for (let x = cnt.length - 1; x; --x) { + if (x === cnt[x]) { + return x; } } - return ans; + return -1; +} +``` + +#### Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn find_lucky(arr: Vec ) -> i32 { + let mut cnt = HashMap::new(); + arr.iter().for_each(|&x| *cnt.entry(x).or_insert(0) += 1); + cnt.iter() + .filter(|(&x, &v)| x == v) + .map(|(&x, _)| x) + .max() + .unwrap_or(-1) + } } ``` @@ -187,17 +196,16 @@ class Solution { * @return Integer */ function findLucky($arr) { - $max = -1; - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$arr[$i]] += 1; + $cnt = array_fill(0, 501, 0); + foreach ($arr as $x) { + $cnt[$x]++; } - $keys = array_keys($hashtable); - for ($j = 0; $j < count($keys); $j++) { - if ($hashtable[$keys[$j]] == $keys[$j]) { - $max = max($max, $keys[$j]); + for ($x = 500; $x > 0; $x--) { + if ($cnt[$x] === $x) { + return $x; } } - return $max; + return -1; } } ``` diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md b/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md index 0150e92bf8adf..cf0c8ede706fc 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md @@ -65,9 +65,9 @@ tags: ### Solution 1: Counting -We can use a hash table or array $cnt$ to count the occurrences of each number in $arr$, then traverse $cnt$ to find the largest $x$ that satisfies $cnt[x] = x$. If there is no such $x$, return $-1$. +We can use a hash table or an array $\textit{cnt}$ to count the occurrences of each number in $\textit{arr}$. Then, we iterate through $\textit{cnt}$ to find the largest $x$ such that $\textit{cnt}[x] = x$. If there is no such $x$, return $-1$. -The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of $arr$. +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the $\textit{arr}$. @@ -77,11 +77,7 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is class Solution: def findLucky(self, arr: List[int]) -> int: cnt = Counter(arr) - ans = -1 - for x, v in cnt.items(): - if x == v and ans < x: - ans = x - return ans + return max((x for x, v in cnt.items() if x == v), default=-1) ``` #### Java @@ -89,17 +85,16 @@ class Solution: ```java class Solution { public int findLucky(int[] arr) { - int[] cnt = new int[510]; - for (int x : cnt) { + int[] cnt = new int[501]; + for (int x : arr) { ++cnt[x]; } - int ans = -1; - for (int x = 1; x < cnt.length; ++x) { - if (cnt[x] == x) { - ans = x; + for (int x = cnt.length - 1; x > 0; --x) { + if (x == cnt[x]) { + return x; } } - return ans; + return -1; } } ``` @@ -110,18 +105,16 @@ class Solution { class Solution { public: int findLucky(vector & arr) { - int cnt[510]; - memset(cnt, 0, sizeof(cnt)); + int cnt[501]{}; for (int x : arr) { ++cnt[x]; } - int ans = -1; - for (int x = 1; x < 510; ++x) { - if (cnt[x] == x) { - ans = x; + for (int x = 500; x; --x) { + if (x == cnt[x]) { + return x; } } - return ans; + return -1; } }; ``` @@ -130,17 +123,16 @@ public: ```go func findLucky(arr []int) int { - cnt := [510]int{} + cnt := [501]int{} for _, x := range arr { cnt[x]++ } - ans := -1 - for x := 1; x < len(cnt); x++ { - if cnt[x] == x { - ans = x + for x := len(cnt) - 1; x > 0; x-- { + if x == cnt[x] { + return x } } - return ans + return -1 } ``` @@ -148,17 +140,34 @@ func findLucky(arr []int) int { ```ts function findLucky(arr: number[]): number { - const cnt = Array(510).fill(0); + const cnt: number[] = Array(501).fill(0); for (const x of arr) { ++cnt[x]; } - let ans = -1; - for (let x = 1; x < cnt.length; ++x) { - if (cnt[x] === x) { - ans = x; + for (let x = cnt.length - 1; x; --x) { + if (x === cnt[x]) { + return x; } } - return ans; + return -1; +} +``` + +#### Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn find_lucky(arr: Vec ) -> i32 { + let mut cnt = HashMap::new(); + arr.iter().for_each(|&x| *cnt.entry(x).or_insert(0) += 1); + cnt.iter() + .filter(|(&x, &v)| x == v) + .map(|(&x, _)| x) + .max() + .unwrap_or(-1) + } } ``` @@ -171,17 +180,16 @@ class Solution { * @return Integer */ function findLucky($arr) { - $max = -1; - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$arr[$i]] += 1; + $cnt = array_fill(0, 501, 0); + foreach ($arr as $x) { + $cnt[$x]++; } - $keys = array_keys($hashtable); - for ($j = 0; $j < count($keys); $j++) { - if ($hashtable[$keys[$j]] == $keys[$j]) { - $max = max($max, $keys[$j]); + for ($x = 500; $x > 0; $x--) { + if ($cnt[$x] === $x) { + return $x; } } - return $max; + return -1; } } ``` diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.cpp b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.cpp index fc249af1dfb56..bd184b1b614af 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.cpp +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.cpp @@ -1,17 +1,15 @@ class Solution { public: int findLucky(vector & arr) { - int cnt[510]; - memset(cnt, 0, sizeof(cnt)); + int cnt[501]{}; for (int x : arr) { ++cnt[x]; } - int ans = -1; - for (int x = 1; x < 510; ++x) { - if (cnt[x] == x) { - ans = x; + for (int x = 500; x; --x) { + if (x == cnt[x]) { + return x; } } - return ans; + return -1; } }; \ No newline at end of file diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.go b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.go index c7cc0cf11c3d8..2065349fea7da 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.go +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.go @@ -1,13 +1,12 @@ func findLucky(arr []int) int { - cnt := [510]int{} + cnt := [501]int{} for _, x := range arr { cnt[x]++ } - ans := -1 - for x := 1; x < len(cnt); x++ { - if cnt[x] == x { - ans = x + for x := len(cnt) - 1; x > 0; x-- { + if x == cnt[x] { + return x } } - return ans + return -1 } \ No newline at end of file diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.java b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.java index b46b186230051..e032656eb678a 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.java +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.java @@ -1,15 +1,14 @@ class Solution { public int findLucky(int[] arr) { - int[] cnt = new int[510]; - for (int x : cnt) { + int[] cnt = new int[501]; + for (int x : arr) { ++cnt[x]; } - int ans = -1; - for (int x = 1; x < cnt.length; ++x) { - if (cnt[x] == x) { - ans = x; + for (int x = cnt.length - 1; x > 0; --x) { + if (x == cnt[x]) { + return x; } } - return ans; + return -1; } } \ No newline at end of file diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php index 978bf0079a7ce..d75690dce4b15 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.php @@ -4,16 +4,15 @@ class Solution { * @return Integer */ function findLucky($arr) { - $max = -1; - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$arr[$i]] += 1; + $cnt = array_fill(0, 501, 0); + foreach ($arr as $x) { + $cnt[$x]++; } - $keys = array_keys($hashtable); - for ($j = 0; $j < count($keys); $j++) { - if ($hashtable[$keys[$j]] == $keys[$j]) { - $max = max($max, $keys[$j]); + for ($x = 500; $x > 0; $x--) { + if ($cnt[$x] === $x) { + return $x; } } - return $max; + return -1; } -} +} \ No newline at end of file diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.py b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.py index 1c1d2594cc4e6..d374650ec8dab 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.py +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.py @@ -1,8 +1,4 @@ class Solution: def findLucky(self, arr: List[int]) -> int: cnt = Counter(arr) - ans = -1 - for x, v in cnt.items(): - if x == v and ans < x: - ans = x - return ans + return max((x for x, v in cnt.items() if x == v), default=-1) diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.rs b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.rs new file mode 100644 index 0000000000000..89dbef71a7a4d --- /dev/null +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.rs @@ -0,0 +1,13 @@ +use std::collections::HashMap; + +impl Solution { + pub fn find_lucky(arr: Vec ) -> i32 { + let mut cnt = HashMap::new(); + arr.iter().for_each(|&x| *cnt.entry(x).or_insert(0) += 1); + cnt.iter() + .filter(|(&x, &v)| x == v) + .map(|(&x, _)| x) + .max() + .unwrap_or(-1) + } +} diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.ts b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.ts index 2effea7d2bc38..719deeeba14a6 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.ts +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.ts @@ -1,13 +1,12 @@ function findLucky(arr: number[]): number { - const cnt = Array(510).fill(0); + const cnt: number[] = Array(501).fill(0); for (const x of arr) { ++cnt[x]; } - let ans = -1; - for (let x = 1; x < cnt.length; ++x) { - if (cnt[x] === x) { - ans = x; + for (let x = cnt.length - 1; x; --x) { + if (x === cnt[x]) { + return x; } } - return ans; + return -1; } diff --git a/solution/1300-1399/1399.Count Largest Group/README.md b/solution/1300-1399/1399.Count Largest Group/README.md index a851ee797e8ff..cb79924b11786 100644 --- a/solution/1300-1399/1399.Count Largest Group/README.md +++ b/solution/1300-1399/1399.Count Largest Group/README.md @@ -19,15 +19,18 @@ tags: - 给你一个整数
+n
。请你先求出从1
到n
的每个整数 10 进制表示下的数位和(每一位上的数字相加),然后把数位和相等的数字放到同一个组中。给定一个整数
-n
。请你统计每个组中的数字数目,并返回数字数目并列最多的组有多少个。
+我们需要根据数字的数位和将
+ +1
到n
的数字分组。例如,数字 14 和 5 属于 同一 组,而数字 13 和 3 属于 不同 组。返回最大组的数字数量,即元素数量 最多 的组。
示例 1:
-输入:n = 13 ++输入:n = 13 输出:4 解释:总共有 9 个组,将 1 到 13 按数位求和后这些组分别是: [1,10],[2,11],[3,12],[4,13],[5],[6],[7],[8],[9]。总共有 4 个组拥有的数字并列最多。 @@ -35,29 +38,18 @@ tags:示例 2:
-输入:n = 2 ++输入:n = 2 输出:2 解释:总共有 2 个大小为 1 的组 [1],[2]。-示例 3:
- -输入:n = 15 -输出:6 -- -示例 4:
- -输入:n = 24 -输出:5 --
提示:
-
diff --git a/solution/1300-1399/1399.Count Largest Group/README_EN.md b/solution/1300-1399/1399.Count Largest Group/README_EN.md index c30865d5c0206..e9f2881df2733 100644 --- a/solution/1300-1399/1399.Count Largest Group/README_EN.md +++ b/solution/1300-1399/1399.Count Largest Group/README_EN.md @@ -21,9 +21,9 @@ tags:- +
1 <= n <= 10^4
1 <= n <= 104
You are given an integer
-n
.Each number from
+1
ton
is grouped according to the sum of its digits.We need to group the numbers from
-1
ton
according to the sum of its digits. For example, the numbers 14 and 5 belong to the same group, whereas 13 and 3 belong to different groups.Return the number of groups that have the largest size.
+Return the number of groups that have the largest size, i.e. the maximum number of elements.
Example 1:
diff --git a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md index a073d83be65f2..8c4feaf13e131 100644 --- a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md +++ b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md @@ -7,6 +7,7 @@ source: 第 183 场周赛 Q2 tags: - 位运算 - 字符串 + - 模拟 --- diff --git a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md index 75593ef52632d..e8d9d6bf642fb 100644 --- a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md +++ b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md @@ -7,6 +7,7 @@ source: Weekly Contest 183 Q2 tags: - Bit Manipulation - String + - Simulation --- diff --git a/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md b/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md index a4a1d7cc7a00c..ab9f361afba34 100644 --- a/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md +++ b/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md @@ -93,7 +93,7 @@ Exam table: Explanation: For exam 1: Student 1 and 3 hold the lowest and high scores respectively. For exam 2: Student 1 hold both highest and lowest score. -For exam 3 and 4: Studnet 1 and 4 hold the lowest and high scores respectively. +For exam 3 and 4: Student 1 and 4 hold the lowest and high scores respectively. Student 2 and 5 have never got the highest or lowest in any of the exams. Since student 5 is not taking any exam, he is excluded from the result. So, we only return the information of Student 2. diff --git a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md index 809ec164c6da3..dd6bc86d1a53a 100644 --- a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md +++ b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md @@ -27,48 +27,77 @@ tags:Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
+
Example 1:
+ Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] + Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] + Explanation: + The displaying table looks like: + Table,Beef Burrito,Ceviche,Fried Chicken,Water + 3 ,0 ,2 ,1 ,0 + 5 ,0 ,1 ,0 ,1 + 10 ,1 ,0 ,0 ,0 + For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". + For the table 5: Carla orders "Water" and "Ceviche". + For the table 10: Corina orders "Beef Burrito". +Example 2:
+ Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]] + Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] + Explanation: + For the table 1: Adam and Brianna order "Canadian Waffles". + For the table 12: James, Ratesh and Amadeus order "Fried Chicken". +Example 3:
+ Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] + Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]] ++
Constraints:
-
diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md index f27f75f2fd31b..d8bc71a7ce113 100644 --- a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md @@ -19,24 +19,26 @@ tags: -- -
1 <= orders.length <= 5 * 10^4
- -
orders[i].length == 3
- -
1 <= customerNamei.length, foodItemi.length <= 20
- -
customerNamei
andfoodItemi
consist of lowercase and uppercase English letters and the space character.- + +
tableNumberi
is a valid integer between1
and500
.- + +
1 <= orders.length <= 5 * 10^4
- + +
orders[i].length == 3
- + +
1 <= customerNamei.length, foodItemi.length <= 20
- + +
customerNamei
andfoodItemi
consist of lowercase and uppercase English letters and the space character.- +
tableNumberi
is a valid integer between1
and500
.给你一个整数
+num
。你可以对它进行如下步骤恰好 两次 :给你一个整数
num
。你可以对它进行以下步骤共计 两次:
- 选择一个数字
x (0 <= x <= 9)
.- 选择另一个数字
y (0 <= y <= 9)
。数字y
可以等于x
。- 将
-num
中所有出现x
的数位都用y
替换。- 得到的新的整数 不能 有前导 0 ,得到的新整数也 不能 是 0 。
令两次对
num
的操作得到的结果分别为a
和b
。请你返回
+a
和b
的 最大差值 。注意,
+a
和b
必须不能 含有前导 0,并且 不为 0。
示例 1:
-输入:num = 555 ++输入:num = 555 输出:888 解释:第一次选择 x = 5 且 y = 9 ,并把得到的新数字保存在 a 中。 第二次选择 x = 5 且 y = 1 ,并把得到的新数字保存在 b 中。 @@ -45,7 +47,8 @@ tags:示例 2:
-输入:num = 9 ++输入:num = 9 输出:8 解释:第一次选择 x = 9 且 y = 9 ,并把得到的新数字保存在 a 中。 第二次选择 x = 9 且 y = 1 ,并把得到的新数字保存在 b 中。 @@ -54,19 +57,22 @@ tags:示例 3:
-输入:num = 123456 ++输入:num = 123456 输出:820000示例 4:
-输入:num = 10000 ++输入:num = 10000 输出:80000示例 5:
-输入:num = 9288 ++输入:num = 9288 输出:8700@@ -88,13 +94,13 @@ tags: 要想得到最大差值,那么我们应该拿到最大值与最小值,这样差值最大。 -因此,我们先从高到低枚举 $nums$ 每个位置上的数,如果数字不为 `9`,就将所有该数字替换为 `9`,得到最大整数 $a$。 +因此,我们先从高到低枚举 $\textit{nums}$ 每个位置上的数,如果数字不为 `9`,就将所有该数字替换为 `9`,得到最大整数 $a$。 -接下来,我们再从高到低枚举 `nums` 每个位置上的数,首位不能为 `0`,因此如果首位不为 `1`,我们将其替换为 `1`;如果非首位,且数字不与首位相同,我们将其替换为 `0`,得到最大整数 $b$。 +接下来,我们再从高到低枚举 $\textit{nums}$ 每个位置上的数,首位不能为 `0`,因此如果首位不为 `1`,我们将其替换为 `1`;如果非首位,且数字不与首位相同,我们将其替换为 `0`,得到最大整数 $b$。 答案为差值 $a - b$。 -时间复杂度 $O(\log num)$,空间复杂度 $O(\log num)$。其中 $num$ 为给定整数。 +时间复杂度 $O(\log \textit{num})$,空间复杂度 $O(\log \textit{num})$。其中 $\textit{nums}$ 为给定整数。 @@ -208,6 +214,65 @@ func maxDiff(num int) int { } ``` +#### TypeScript + +```ts +function maxDiff(num: number): number { + let a = num.toString(); + let b = a; + for (let i = 0; i < a.length; ++i) { + if (a[i] !== '9') { + a = a.split(a[i]).join('9'); + break; + } + } + if (b[0] !== '1') { + b = b.split(b[0]).join('1'); + } else { + for (let i = 1; i < b.length; ++i) { + if (b[i] !== '0' && b[i] !== '1') { + b = b.split(b[i]).join('0'); + break; + } + } + } + return +a - +b; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn max_diff(num: i32) -> i32 { + let a = num.to_string(); + let mut a = a.clone(); + let mut b = a.clone(); + + for c in a.chars() { + if c != '9' { + a = a.replace(c, "9"); + break; + } + } + + let chars: Vec= b.chars().collect(); + if chars[0] != '1' { + b = b.replace(chars[0], "1"); + } else { + for &c in &chars[1..] { + if c != '0' && c != '1' { + b = b.replace(c, "0"); + break; + } + } + } + + a.parse:: ().unwrap() - b.parse:: ().unwrap() + } +} +``` + diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md index 8b054be5c0d7b..2aad266c5b7ff 100644 --- a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md @@ -19,19 +19,20 @@ tags: - You are given an integer
+num
. You will apply the following steps exactly two times:You are given an integer
num
. You will apply the following steps tonum
two separate times:-
- Pick a digit
-x (0 <= x <= 9)
.- Pick another digit
+y (0 <= y <= 9)
. The digity
can be equal tox
.- Pick another digit
y (0 <= y <= 9)
. Notey
can be equal tox
.- Replace all the occurrences of
-x
in the decimal representation ofnum
byy
.- The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let
+a
andb
be the results of applying the operations tonum
the first and second times, respectively.Let
a
andb
be the two results from applying the operation tonum
independently.Return the max difference between
+a
andb
.Note that neither
+a
norb
may have any leading zeros, and must not be 0.
Example 1:
@@ -66,7 +67,17 @@ We have now a = 9 and b = 1 and max difference = 8 -### Solution 1 +### Solution 1: Greedy + +To obtain the maximum difference, we should take the maximum and minimum values, as this yields the largest difference. + +Therefore, we first enumerate each digit in $\textit{nums}$ from high to low. If a digit is not `9`, we replace all occurrences of that digit with `9` to obtain the maximum integer $a$. + +Next, we enumerate each digit in $\textit{nums}$ from high to low again. The first digit cannot be `0`, so if the first digit is not `1`, we replace it with `1`; for non-leading digits that are different from the first digit, we replace them with `0` to obtain the minimum integer $b$. + +The answer is the difference $a - b$. + +The time complexity is $O(\log \textit{num})$, and the space complexity is $O(\log \textit{num})$, where $\textit{nums}$ is the given integer. @@ -180,6 +191,65 @@ func maxDiff(num int) int { } ``` +#### TypeScript + +```ts +function maxDiff(num: number): number { + let a = num.toString(); + let b = a; + for (let i = 0; i < a.length; ++i) { + if (a[i] !== '9') { + a = a.split(a[i]).join('9'); + break; + } + } + if (b[0] !== '1') { + b = b.split(b[0]).join('1'); + } else { + for (let i = 1; i < b.length; ++i) { + if (b[i] !== '0' && b[i] !== '1') { + b = b.split(b[i]).join('0'); + break; + } + } + } + return +a - +b; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn max_diff(num: i32) -> i32 { + let a = num.to_string(); + let mut a = a.clone(); + let mut b = a.clone(); + + for c in a.chars() { + if c != '9' { + a = a.replace(c, "9"); + break; + } + } + + let chars: Vec= b.chars().collect(); + if chars[0] != '1' { + b = b.replace(chars[0], "1"); + } else { + for &c in &chars[1..] { + if c != '0' && c != '1' { + b = b.replace(c, "0"); + break; + } + } + } + + a.parse:: ().unwrap() - b.parse:: ().unwrap() + } +} +``` + diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.rs b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.rs new file mode 100644 index 0000000000000..17cbc4f0dd6bc --- /dev/null +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn max_diff(num: i32) -> i32 { + let a = num.to_string(); + let mut a = a.clone(); + let mut b = a.clone(); + + for c in a.chars() { + if c != '9' { + a = a.replace(c, "9"); + break; + } + } + + let chars: Vec = b.chars().collect(); + if chars[0] != '1' { + b = b.replace(chars[0], "1"); + } else { + for &c in &chars[1..] { + if c != '0' && c != '1' { + b = b.replace(c, "0"); + break; + } + } + } + + a.parse:: ().unwrap() - b.parse:: ().unwrap() + } +} diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.ts b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.ts new file mode 100644 index 0000000000000..b83ebad41364b --- /dev/null +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.ts @@ -0,0 +1,21 @@ +function maxDiff(num: number): number { + let a = num.toString(); + let b = a; + for (let i = 0; i < a.length; ++i) { + if (a[i] !== '9') { + a = a.split(a[i]).join('9'); + break; + } + } + if (b[0] !== '1') { + b = b.split(b[0]).join('1'); + } else { + for (let i = 1; i < b.length; ++i) { + if (b[i] !== '0' && b[i] !== '1') { + b = b.split(b[i]).join('0'); + break; + } + } + } + return +a - +b; +} diff --git a/solution/1400-1499/1441.Build an Array With Stack Operations/README.md b/solution/1400-1499/1441.Build an Array With Stack Operations/README.md index 40a72da78f311..e2a66d57660c2 100644 --- a/solution/1400-1499/1441.Build an Array With Stack Operations/README.md +++ b/solution/1400-1499/1441.Build an Array With Stack Operations/README.md @@ -20,19 +20,26 @@ tags: - 给你一个数组
+target
和一个整数n
。每次迭代,需要从list = { 1 , 2 , 3 ..., n }
中依次读取一个数字。给你一个数组
-target
和一个整数n
。请使用下述操作来构建目标数组
+target
:给你一个空栈和两种操作:
-
-- -
"Push"
:从list
中读取一个新元素, 并将其推入数组中。- -
"Pop"
:删除数组中的最后一个元素。- 如果目标数组构建完成,就停止读取更多元素。
+- +
"Push"
:将一个整数加到栈顶。"Pop"
:从栈顶删除一个整数。题目数据保证目标数组严格递增,并且只包含
+1
到n
之间的数字。同时给定一个范围
-[1, n]
中的整数流。请返回构建目标数组所用的操作序列。如果存在多个可行方案,返回任一即可。
+使用两个栈操作使栈中的数字(从底部到顶部)等于
+ +target
。你应该遵循以下规则:+
+ +- 如果整数流不为空,从流中选取下一个整数并将其推送到栈顶。
+- 如果栈不为空,弹出栈顶的整数。
+- 如果,在任何时刻,栈中的元素(从底部到顶部)等于
+target
,则不要从流中读取新的整数,也不要对栈进行更多操作。请返回遵循上述规则构建
target
所用的操作序列。如果存在多个合法答案,返回 任一 即可。@@ -41,10 +48,11 @@ tags:
输入:target = [1,3], n = 3 输出:["Push","Push","Pop","Push"] -解释: -读取 1 并自动推入数组 -> [1] -读取 2 并自动推入数组,然后删除它 -> [1] -读取 3 并自动推入数组 -> [1,3] +解释:一开始栈为空。最后一个元素是栈顶。 +从流中读取 1 并推入数组 -> [1] +从流中读取 2 并推入数组 -> [1,2] +从栈顶删除整数 -> [1] +从流中读取 3 并推入数组 -> [1,3]示例 2:
@@ -52,6 +60,10 @@ tags:输入:target = [1,2,3], n = 3 输出:["Push","Push","Push"] +解释:一开始栈为空。最后一个元素是栈顶。 +从流中读取 1 并推入数组 -> [1] +从流中读取 2 并推入数组 -> [1,2] +从流中读取 3 并推入数组 -> [1,2,3]示例 3:
@@ -59,7 +71,11 @@ tags:输入:target = [1,2], n = 4 输出:["Push","Push"] -解释:只需要读取前 2 个数字就可以停止。 +解释:一开始栈为空。最后一个元素是栈顶。 +从流中读取 1 并推入数组 -> [1] +从流中读取 2 并推入数组 -> [1,2] +由于栈(从底部到顶部)等于 target,我们停止栈操作。 +从流中读取整数 3 的答案不被接受。diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md index 75f9d52c74990..4a07c72b0b946 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md @@ -26,17 +26,25 @@ tags:
Return the number of good nodes in the binary tree.
+
Example 1:
+ Input: root = [3,1,4,3,null,1,5] + Output: 4 + Explanation: Nodes in blue are good. + Root Node (3) is always a good node. + Node 4 -> (3,4) is the maximum value in the path starting from the root. + Node 5 -> (3,4,5) is the maximum value in the path + Node 3 -> (3,1,3) is the maximum value in the path.Example 2:
@@ -44,23 +52,33 @@ Node 3 -> (3,1,3) is the maximum value in the path.
+ Input: root = [3,3,null,4,2] + Output: 3 + Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.Example 3:
+ Input: root = [1] + Output: 1 + Explanation: Root is considered as good.+
Constraints:
-
diff --git a/solution/1400-1499/1470.Shuffle the Array/README_EN.md b/solution/1400-1499/1470.Shuffle the Array/README_EN.md index 9246c35a92d80..8a806cd3fd73d 100644 --- a/solution/1400-1499/1470.Shuffle the Array/README_EN.md +++ b/solution/1400-1499/1470.Shuffle the Array/README_EN.md @@ -23,35 +23,51 @@ tags:- The number of nodes in the binary tree is in the range
-[1, 10^5]
.- Each node's value is between
+ +[-10^4, 10^4]
.- The number of nodes in the binary tree is in the range
+ +[1, 10^5]
.- Each node's value is between
+[-10^4, 10^4]
.Return the array in the form
[x1,y1,x2,y2,...,xn,yn]
.+
Example 1:
+ Input: nums = [2,5,1,3,4,7], n = 3 + Output: [2,3,5,4,1,7] + Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. +Example 2:
+ Input: nums = [1,2,3,4,4,3,2,1], n = 4 + Output: [1,4,2,3,3,2,4,1] +Example 3:
+ Input: nums = [1,1,2,2], n = 2 + Output: [1,2,1,2] ++
Constraints:
-
diff --git a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md index f02ab74dd4299..c96b41716e53e 100644 --- a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md +++ b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md @@ -85,9 +85,9 @@ tags: 我们可以使用哈希表 $d$ 记录前缀和最近一次出现的位置,初始时 $d[0]=0$。 -定义 $f[i]$ 表示前 $i$ 个元素中,长度和为 $target$ 的最短子数组的长度。初始时 $f[0]=inf$。 +定义 $f[i]$ 表示前 $i$ 个元素中,长度和为 $target$ 的最短子数组的长度。初始时 $f[0]= \infty$。 -遍历数组 `arr`,对于当前位置 $i$,计算前缀和 $s$,如果 $s-target$ 在哈希表中,记 $j=d[s-target]$,则 $f[i]=min(f[i],i-j)$,答案为 $ans=min(ans,f[j]+i-j)$。继续遍历下个位置。 +遍历数组 $\textit{arr}$,对于当前位置 $i$,计算前缀和 $s$,如果 $s - \textit{target}$ 在哈希表中,记 $j=d[s - \textit{target}]$,则 $f[i]=\min(f[i], i - j)$,答案为 $ans=\min(ans, f[j] + i - j)$。继续遍历下个位置。 最后,如果答案大于数组长度,则返回 $-1$,否则返回答案。 @@ -199,6 +199,33 @@ func minSumOfLengths(arr []int, target int) int { } ``` +#### TypeScript + +```ts +function minSumOfLengths(arr: number[], target: number): number { + const d = new Map- -
1 <= n <= 500
- -
nums.length == 2n
- + +
1 <= nums[i] <= 10^3
- + +
1 <= n <= 500
- + +
nums.length == 2n
- +
1 <= nums[i] <= 10^3
(); + d.set(0, 0); + let s = 0; + const n = arr.length; + const f: number[] = Array(n + 1); + const inf = 1 << 30; + f[0] = inf; + let ans = inf; + for (let i = 1; i <= n; ++i) { + const v = arr[i - 1]; + s += v; + f[i] = f[i - 1]; + if (d.has(s - target)) { + const j = d.get(s - target)!; + f[i] = Math.min(f[i], i - j); + ans = Math.min(ans, f[j] + i - j); + } + d.set(s, i); + } + return ans > n ? -1 : ans; +} +``` + diff --git a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md index 74b866b75256c..ab81135d97097 100644 --- a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md +++ b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md @@ -68,7 +68,17 @@ tags: -### Solution 1 +### Solution 1: Hash Table + Prefix Sum + Dynamic Programming + +We can use a hash table $d$ to record the most recent position where each prefix sum appears, with the initial value $d[0]=0$. + +Define $f[i]$ as the minimum length of a subarray with sum equal to $target$ among the first $i$ elements. Initially, $f[0]=\infty$. + +Iterate through the array $\textit{arr}$. For the current position $i$, calculate the prefix sum $s$. If $s - \textit{target}$ exists in the hash table, let $j = d[s - \textit{target}]$, then $f[i] = \min(f[i], i - j)$, and the answer is $ans = \min(ans, f[j] + i - j)$. Continue to the next position. + +Finally, if the answer is greater than the array length, return $-1$; otherwise, return the answer. + +The complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array. @@ -176,6 +186,33 @@ func minSumOfLengths(arr []int, target int) int { } ``` +#### TypeScript + +```ts +function minSumOfLengths(arr: number[], target: number): number { + const d = new Map (); + d.set(0, 0); + let s = 0; + const n = arr.length; + const f: number[] = Array(n + 1); + const inf = 1 << 30; + f[0] = inf; + let ans = inf; + for (let i = 1; i <= n; ++i) { + const v = arr[i - 1]; + s += v; + f[i] = f[i - 1]; + if (d.has(s - target)) { + const j = d.get(s - target)!; + f[i] = Math.min(f[i], i - j); + ans = Math.min(ans, f[j] + i - j); + } + d.set(s, i); + } + return ans > n ? -1 : ans; +} +``` + diff --git a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/Solution.ts b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/Solution.ts new file mode 100644 index 0000000000000..cb28fda619329 --- /dev/null +++ b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/Solution.ts @@ -0,0 +1,22 @@ +function minSumOfLengths(arr: number[], target: number): number { + const d = new Map (); + d.set(0, 0); + let s = 0; + const n = arr.length; + const f: number[] = Array(n + 1); + const inf = 1 << 30; + f[0] = inf; + let ans = inf; + for (let i = 1; i <= n; ++i) { + const v = arr[i - 1]; + s += v; + f[i] = f[i - 1]; + if (d.has(s - target)) { + const j = d.get(s - target)!; + f[i] = Math.min(f[i], i - j); + ans = Math.min(ans, f[j] + i - j); + } + d.set(s, i); + } + return ans > n ? -1 : ans; +} diff --git a/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md b/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md index 00dee15fada33..d367cf0458c18 100644 --- a/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md +++ b/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md @@ -25,31 +25,45 @@ tags: Given an array of integers
arr
and an integerk
. Find the least number of unique integers after removing exactlyk
elements.+
+
Example 1:
+ Input: arr = [5,5,4], k = 1 + Output: 1 + Explanation: Remove the single 4, only 5 is left. +Example 2:+ Input: arr = [4,3,1,1,3,3,2], k = 3 + Output: 2 + Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.+
Constraints:
-
diff --git a/solution/1400-1499/1487.Making File Names Unique/README_EN.md b/solution/1400-1499/1487.Making File Names Unique/README_EN.md index da002d0577b6c..776f0cd7a95ca 100644 --- a/solution/1400-1499/1487.Making File Names Unique/README_EN.md +++ b/solution/1400-1499/1487.Making File Names Unique/README_EN.md @@ -74,7 +74,21 @@ tags: -### Solution 1 +### Solution 1: Hash Table + +We can use a hash table $d$ to record the minimum available index for each folder name, where $d[name] = k$ means the minimum available index for the folder $name$ is $k$. Initially, $d$ is empty since there are no folders. + +Next, we iterate through the folder names array. For each file name $name$: + +- If $name$ is already in $d$, it means the folder $name$ already exists, and we need to find a new folder name. We can keep trying $name(k)$, where $k$ starts from $d[name]$, until we find a folder name $name(k)$ that does not exist in $d$. We add $name(k)$ to $d$, update $d[name]$ to $k + 1$, and then update $name$ to $name(k)$. +- If $name$ is not in $d$, we can directly add $name$ to $d$ and set $d[name]$ to $1$. +- Then, we add $name$ to the answer array and continue to the next file name. + +After traversing all file names, we obtain the answer array. + +> In the code implementation below, we directly modify the $names$ array without using an extra answer array. + +The complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is the sum of the lengths of all file names in the $names$ array. @@ -144,22 +158,22 @@ public: ```go func getFolderNames(names []string) []string { - d := map[string]int{} - for i, name := range names { - if k, ok := d[name]; ok { - for { - newName := fmt.Sprintf("%s(%d)", name, k) - if d[newName] == 0 { - d[name] = k + 1 - names[i] = newName - break - } - k++ - } - } - d[names[i]] = 1 - } - return names + d := map[string]int{} + for i, name := range names { + if k, ok := d[name]; ok { + for { + newName := fmt.Sprintf("%s(%d)", name, k) + if d[newName] == 0 { + d[name] = k + 1 + names[i] = newName + break + } + k++ + } + } + d[names[i]] = 1 + } + return names } ``` diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md index e6ace5471b0df..238ee9e8a551f 100644 --- a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md @@ -74,13 +74,13 @@ tags: -### 方法一:排序 + 枚举贡献 + 二分查找 +### 方法一:排序 + 二分查找 -由于题目中描述的是子序列,并且涉及到最小元素与最大元素的和,因此我们可以先对数组 `nums` 进行排序。 +由于题目中描述的是子序列,并且涉及到最小元素与最大元素的和,因此我们可以先对数组 $\textit{nums}$ 进行排序。 -然后我们枚举最小元素 $nums[i]$,对于每个 $nums[i]$,我们可以在 $nums[i + 1]$ 到 $nums[n - 1]$ 中找到最大元素 $nums[j]$,使得 $nums[i] + nums[j] \leq target$,此时满足条件的子序列数目为 $2^{j - i}$,其中 $2^{j - i}$ 表示从 $nums[i + 1]$ 到 $nums[j]$ 的所有子序列的数目。我们将所有的子序列数目累加即可。 +然后我们枚举最小元素 $\textit{nums}[i]$,对于每个 $\textit{nums}[i]$,我们可以在 $\textit{nums}[i + 1]$ 到 $\textit{nums}[n - 1]$ 中找到最大元素 $\textit{nums}[j]$,使得 $\textit{nums}[i] + \textit{nums}[j] \leq \textit{target}$,此时满足条件的子序列数目为 $2^{j - i}$,其中 $2^{j - i}$ 表示从 $\textit{nums}[i + 1]$ 到 $\textit{nums}[j]$ 的所有子序列的数目。我们将所有的子序列数目累加即可。 -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 @@ -118,10 +118,7 @@ class Solution { f[i] = (f[i - 1] * 2) % mod; } int ans = 0; - for (int i = 0; i < n; ++i) { - if (nums[i] * 2L > target) { - break; - } + for (int i = 0; i < n && nums[i] * 2 <= target; ++i) { int j = search(nums, target - nums[i], i + 1) - 1; ans = (ans + f[j - i]) % mod; } @@ -158,10 +155,7 @@ public: f[i] = (f[i - 1] * 2) % mod; } int ans = 0; - for (int i = 0; i < n; ++i) { - if (nums[i] * 2L > target) { - break; - } + for (int i = 0; i < n && nums[i] * 2 <= target; ++i) { int j = upper_bound(nums.begin() + i + 1, nums.end(), target - nums[i]) - nums.begin() - 1; ans = (ans + f[j - i]) % mod; } @@ -193,6 +187,77 @@ func numSubseq(nums []int, target int) (ans int) { } ``` +#### TypeScript + +```ts +function numSubseq(nums: number[], target: number): number { + nums.sort((a, b) => a - b); + const mod = 1e9 + 7; + const n = nums.length; + const f: number[] = Array(n + 1).fill(1); + for (let i = 1; i <= n; ++i) { + f[i] = (f[i - 1] * 2) % mod; + } + + let ans = 0; + for (let i = 0; i < n && nums[i] * 2 <= target; ++i) { + const j = search(nums, target - nums[i], i + 1) - 1; + if (j >= i) { + ans = (ans + f[j - i]) % mod; + } + } + return ans; +} + +function search(nums: number[], x: number, left: number): number { + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_subseq(mut nums: Vec- -
1 <= arr.length <= 10^5
- -
1 <= arr[i] <= 10^9
- + +
0 <= k <= arr.length
- + +
1 <= arr.length <= 10^5
- + +
1 <= arr[i] <= 10^9
- +
0 <= k <= arr.length
, target: i32) -> i32 { + nums.sort(); + const MOD: i32 = 1_000_000_007; + let n = nums.len(); + let mut f = vec![1; n + 1]; + for i in 1..=n { + f[i] = (f[i - 1] * 2) % MOD; + } + let mut ans = 0; + for i in 0..n { + if nums[i] * 2 > target { + break; + } + let mut l = i + 1; + let mut r = n; + while l < r { + let m = (l + r) / 2; + if nums[m] > target - nums[i] { + r = m; + } else { + l = m + 1; + } + } + let j = l - 1; + ans = (ans + f[j - i]) % MOD; + } + ans + } +} +``` + diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md index 82d339744f91b..9e42491529171 100644 --- a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md @@ -71,7 +71,13 @@ Number of valid subsequences (63 - 2 = 61). -### Solution 1 +### Solution 1: Sorting + Binary Search + +Since the problem is about subsequences and involves the sum of the minimum and maximum elements, we can first sort the array $\textit{nums}$. + +Then we enumerate the minimum element $\textit{nums}[i]$. For each $\textit{nums}[i]$, we can find the maximum element $\textit{nums}[j]$ in $\textit{nums}[i + 1]$ to $\textit{nums}[n - 1]$ such that $\textit{nums}[i] + \textit{nums}[j] \leq \textit{target}$. The number of valid subsequences in this case is $2^{j - i}$, where $2^{j - i}$ represents all possible subsequences from $\textit{nums}[i + 1]$ to $\textit{nums}[j]$. We sum up the counts of all such subsequences. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. @@ -109,10 +115,7 @@ class Solution { f[i] = (f[i - 1] * 2) % mod; } int ans = 0; - for (int i = 0; i < n; ++i) { - if (nums[i] * 2L > target) { - break; - } + for (int i = 0; i < n && nums[i] * 2 <= target; ++i) { int j = search(nums, target - nums[i], i + 1) - 1; ans = (ans + f[j - i]) % mod; } @@ -149,10 +152,7 @@ public: f[i] = (f[i - 1] * 2) % mod; } int ans = 0; - for (int i = 0; i < n; ++i) { - if (nums[i] * 2L > target) { - break; - } + for (int i = 0; i < n && nums[i] * 2 <= target; ++i) { int j = upper_bound(nums.begin() + i + 1, nums.end(), target - nums[i]) - nums.begin() - 1; ans = (ans + f[j - i]) % mod; } @@ -184,6 +184,77 @@ func numSubseq(nums []int, target int) (ans int) { } ``` +#### TypeScript + +```ts +function numSubseq(nums: number[], target: number): number { + nums.sort((a, b) => a - b); + const mod = 1e9 + 7; + const n = nums.length; + const f: number[] = Array(n + 1).fill(1); + for (let i = 1; i <= n; ++i) { + f[i] = (f[i - 1] * 2) % mod; + } + + let ans = 0; + for (let i = 0; i < n && nums[i] * 2 <= target; ++i) { + const j = search(nums, target - nums[i], i + 1) - 1; + if (j >= i) { + ans = (ans + f[j - i]) % mod; + } + } + return ans; +} + +function search(nums: number[], x: number, left: number): number { + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_subseq(mut nums: Vec , target: i32) -> i32 { + nums.sort(); + const MOD: i32 = 1_000_000_007; + let n = nums.len(); + let mut f = vec![1; n + 1]; + for i in 1..=n { + f[i] = (f[i - 1] * 2) % MOD; + } + let mut ans = 0; + for i in 0..n { + if nums[i] * 2 > target { + break; + } + let mut l = i + 1; + let mut r = n; + while l < r { + let m = (l + r) / 2; + if nums[m] > target - nums[i] { + r = m; + } else { + l = m + 1; + } + } + let j = l - 1; + ans = (ans + f[j - i]) % MOD; + } + ans + } +} +``` + diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.cpp b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.cpp index 4c4d4dc630bac..f599d59527261 100644 --- a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.cpp +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.cpp @@ -10,10 +10,7 @@ class Solution { f[i] = (f[i - 1] * 2) % mod; } int ans = 0; - for (int i = 0; i < n; ++i) { - if (nums[i] * 2L > target) { - break; - } + for (int i = 0; i < n && nums[i] * 2 <= target; ++i) { int j = upper_bound(nums.begin() + i + 1, nums.end(), target - nums[i]) - nums.begin() - 1; ans = (ans + f[j - i]) % mod; } diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.java b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.java index 73cd951a7968b..d5ceb81f59e9f 100644 --- a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.java +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.java @@ -9,10 +9,7 @@ public int numSubseq(int[] nums, int target) { f[i] = (f[i - 1] * 2) % mod; } int ans = 0; - for (int i = 0; i < n; ++i) { - if (nums[i] * 2L > target) { - break; - } + for (int i = 0; i < n && nums[i] * 2 <= target; ++i) { int j = search(nums, target - nums[i], i + 1) - 1; ans = (ans + f[j - i]) % mod; } diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.rs b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.rs new file mode 100644 index 0000000000000..7e07c8502443a --- /dev/null +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn num_subseq(mut nums: Vec , target: i32) -> i32 { + nums.sort(); + const MOD: i32 = 1_000_000_007; + let n = nums.len(); + let mut f = vec![1; n + 1]; + for i in 1..=n { + f[i] = (f[i - 1] * 2) % MOD; + } + let mut ans = 0; + for i in 0..n { + if nums[i] * 2 > target { + break; + } + let mut l = i + 1; + let mut r = n; + while l < r { + let m = (l + r) / 2; + if nums[m] > target - nums[i] { + r = m; + } else { + l = m + 1; + } + } + let j = l - 1; + ans = (ans + f[j - i]) % MOD; + } + ans + } +} diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.ts b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.ts new file mode 100644 index 0000000000000..e05c6d19d421c --- /dev/null +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.ts @@ -0,0 +1,31 @@ +function numSubseq(nums: number[], target: number): number { + nums.sort((a, b) => a - b); + const mod = 1e9 + 7; + const n = nums.length; + const f: number[] = Array(n + 1).fill(1); + for (let i = 1; i <= n; ++i) { + f[i] = (f[i - 1] * 2) % mod; + } + + let ans = 0; + for (let i = 0; i < n && nums[i] * 2 <= target; ++i) { + const j = search(nums, target - nums[i], i + 1) - 1; + if (j >= i) { + ans = (ans + f[j - i]) % mod; + } + } + return ans; +} + +function search(nums: number[], x: number, left: number): number { + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md index b1f8ff1c6fb74..0f0fdcafab556 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md @@ -8,6 +8,7 @@ tags: - 数组 - 双指针 - 二分查找 + - 前缀和 - 排序 --- diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md index 1081fe59befc3..4ab70b4d1fe26 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md @@ -8,6 +8,7 @@ tags: - Array - Two Pointers - Binary Search + - Prefix Sum - Sorting --- diff --git a/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md b/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md index ddda78859db1a..e69eb35820536 100644 --- a/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md +++ b/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md @@ -86,6 +86,8 @@ Users 表: ### 方法一:REGEXP 正则匹配 +我们可以使用正则表达式来匹配有效的电子邮件格式。正则表达式可以确保前缀名称符合要求,并且域名是固定的 `@leetcode.com`。 + #### MySQL @@ -94,7 +96,19 @@ Users 表: # Write your MySQL query statement below SELECT * FROM Users -WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode[.]com$'; +WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\\.com$' AND BINARY mail LIKE '%@leetcode.com'; +``` + +#### Pandas + +```python +import pandas as pd + + +def valid_emails(users: pd.DataFrame) -> pd.DataFrame: + pattern = r"^[A-Za-z][A-Za-z0-9_.-]*@leetcode\.com$" + mask = users["mail"].str.match(pattern, flags=0, na=False) + return users.loc[mask, ["user_id", "name", "mail"]] ``` diff --git a/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md b/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md index 8bf7f75cf573a..a4b7d76d920b6 100644 --- a/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md +++ b/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md @@ -83,7 +83,9 @@ The mail of user 7 starts with a period. -### Solution 1 +### Solution 1: REGEXP Pattern Matching + +We can use a regular expression to match valid email formats. The expression ensures that the username part meets the required rules and that the domain is fixed as `@leetcode.com`. @@ -93,7 +95,19 @@ The mail of user 7 starts with a period. # Write your MySQL query statement below SELECT * FROM Users -WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode[.]com$'; +WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\\.com$' AND BINARY mail LIKE '%@leetcode.com'; +``` + +#### Pandas + +```python +import pandas as pd + + +def valid_emails(users: pd.DataFrame) -> pd.DataFrame: + pattern = r"^[A-Za-z][A-Za-z0-9_.-]*@leetcode\.com$" + mask = users["mail"].str.match(pattern, flags=0, na=False) + return users.loc[mask, ["user_id", "name", "mail"]] ``` diff --git a/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.py b/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.py new file mode 100644 index 0000000000000..ef6a579e6fc9b --- /dev/null +++ b/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.py @@ -0,0 +1,7 @@ +import pandas as pd + + +def valid_emails(users: pd.DataFrame) -> pd.DataFrame: + pattern = r"^[A-Za-z][A-Za-z0-9_.-]*@leetcode\.com$" + mask = users["mail"].str.match(pattern, flags=0, na=False) + return users.loc[mask, ["user_id", "name", "mail"]] diff --git a/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.sql b/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.sql index a9ac512c1444e..b76bec68f8fbe 100644 --- a/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.sql +++ b/solution/1500-1599/1517.Find Users With Valid E-Mails/Solution.sql @@ -1,4 +1,4 @@ # Write your MySQL query statement below SELECT * FROM Users -WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode[.]com$'; +WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\\.com$' AND BINARY mail LIKE '%@leetcode.com'; diff --git a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md index d1eea923bf055..03cb439cf8dbc 100644 --- a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md +++ b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md @@ -21,25 +21,35 @@ tags: Given two non-negative integers
low
andhigh
. Return the count of odd numbers betweenlow
andhigh
(inclusive).+
Example 1:
+ Input: low = 3, high = 7 + Output: 3 + Explanation: The odd numbers between 3 and 7 are [3,5,7].Example 2:
+ Input: low = 8, high = 10 + Output: 1 + Explanation: The odd numbers between 8 and 10 are [9].+
Constraints:
-
diff --git a/solution/1500-1599/1534.Count Good Triplets/README_EN.md b/solution/1500-1599/1534.Count Good Triplets/README_EN.md index e1d64f2f7cc9b..5e8224082f55c 100644 --- a/solution/1500-1599/1534.Count Good Triplets/README_EN.md +++ b/solution/1500-1599/1534.Count Good Triplets/README_EN.md @@ -24,10 +24,15 @@ tags:- + +
0 <= low <= high <= 10^9
- +
0 <= low <= high <= 10^9
A triplet
(arr[i], arr[j], arr[k])
is good if the following conditions are true:-
- -
0 <= i < j < k < arr.length
- -
|arr[i] - arr[j]| <= a
- -
|arr[j] - arr[k]| <= b
- + +
|arr[i] - arr[k]| <= c
- + +
0 <= i < j < k < arr.length
- + +
|arr[i] - arr[j]| <= a
- + +
|arr[j] - arr[k]| <= b
- +
|arr[i] - arr[k]| <= c
Where
@@ -35,29 +40,43 @@ tags:|x|
denotes the absolute value ofx
.Return the number of good triplets.
+
Example 1:
+ Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 + Output: 4 + Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. +Example 2:
+ Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1 + Output: 0 + Explanation: No triplet satisfies all conditions. ++
Constraints:
-
diff --git a/solution/1500-1599/1563.Stone Game V/README.md b/solution/1500-1599/1563.Stone Game V/README.md index 7f64cdd5f56c9..097ba6421ccd9 100644 --- a/solution/1500-1599/1563.Stone Game V/README.md +++ b/solution/1500-1599/1563.Stone Game V/README.md @@ -33,7 +33,8 @@ tags:- -
3 <= arr.length <= 100
- -
0 <= arr[i] <= 1000
- + +
0 <= a, b, c <= 1000
- + +
3 <= arr.length <= 100
- + +
0 <= arr[i] <= 1000
- +
0 <= a, b, c <= 1000
示例 1:
-输入:stoneValue = [6,2,3,4,5,5] ++输入:stoneValue = [6,2,3,4,5,5] 输出:18 解释:在第一轮中,Alice 将行划分为 [6,2,3],[4,5,5] 。左行的值是 11 ,右行的值是 14 。Bob 丢弃了右行,Alice 的分数现在是 11 。 在第二轮中,Alice 将行分成 [6],[2,3] 。这一次 Bob 扔掉了左行,Alice 的分数变成了 16(11 + 5)。 @@ -42,13 +43,15 @@ tags:示例 2:
-输入:stoneValue = [7,7,7,7,7,7,7] ++输入:stoneValue = [7,7,7,7,7,7,7] 输出:28示例 3:
-输入:stoneValue = [4] ++输入:stoneValue = [4] 输出:0@@ -58,7 +61,7 @@ tags:diff --git a/solution/1500-1599/1563.Stone Game V/README_EN.md b/solution/1500-1599/1563.Stone Game V/README_EN.md index c5255f765cc1a..2968c599999aa 100644 --- a/solution/1500-1599/1563.Stone Game V/README_EN.md +++ b/solution/1500-1599/1563.Stone Game V/README_EN.md @@ -25,7 +25,7 @@ tags:
- -
1 <= stoneValue.length <= 500
- +
1 <= stoneValue[i] <= 10^6
1 <= stoneValue[i] <= 106
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.
-The game ends when there is only one stone remaining. Alice's is initially zero.
+The game ends when there is only one stone remaining. Alice's score is initially zero.
Return the maximum score that Alice can obtain.
diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md index 58a5aa233655e..a39d7dd0a4861 100644 --- a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md @@ -33,42 +33,63 @@ tags:Notice that the distance between the two cities is the number of edges in the path between them.
+
Example 1:
+ Input: n = 4, edges = [[1,2],[2,3],[2,4]] + Output: [3,4,0] + Explanation: + The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. + The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. + No subtree has two nodes where the max distance between them is 3. +Example 2:
+ Input: n = 2, edges = [[1,2]] + Output: [1] +Example 3:
+ Input: n = 3, edges = [[1,2],[2,3]] + Output: [2,1] ++
Constraints:
-
diff --git a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md index 637b3531cdded..86b831b8cd79f 100644 --- a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md +++ b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md @@ -26,14 +26,23 @@ tags:- -
2 <= n <= 15
- -
edges.length == n-1
- -
edges[i].length == 2
- -
1 <= ui, vi <= n
- All pairs
+ +(ui, vi)
are distinct.- + +
2 <= n <= 15
- + +
edges.length == n-1
- + +
edges[i].length == 2
- + +
1 <= ui, vi <= n
- All pairs
+(ui, vi)
are distinct.The
FontInfo
interface is defined as such:+ interface FontInfo { + // Returns the width of character ch on the screen using font size fontSize. + // O(1) per call + public int getWidth(int fontSize, char ch); + + // Returns the height of any character on the screen using font size fontSize. + // O(1) per call + public int getHeight(int fontSize); + }The calculated width of
@@ -43,45 +52,67 @@ interface FontInfo {text
for somefontSize
is the sum of everygetWidth(fontSize, text[i])
call for each0 <= i < text.length
(0-indexed). The calculated height oftext
for somefontSize
isgetHeight(fontSize)
. Note thattext
is displayed on a single line.It is also guaranteed that for any font size
fontSize
and any characterch
:-
- -
getHeight(fontSize) <= getHeight(fontSize+1)
- + +
getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
- + +
getHeight(fontSize) <= getHeight(fontSize+1)
- +
getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
Return the maximum font size you can use to display
text
on the screen. Iftext
cannot fit on the display with any font size, return-1
.+
Example 1:
+ Input: text = "helloworld", w = 80, h = 20, fonts = [6,8,10,12,14,16,18,24,36] + Output: 6 +Example 2:
+ Input: text = "leetcode", w = 1000, h = 50, fonts = [1,2,4] + Output: 4 +Example 3:
+ Input: text = "easyquestion", w = 100, h = 100, fonts = [10,15,20,25] + Output: -1 ++
Constraints:
-
diff --git a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md index b5a4c41d13436..107929af544fa 100644 --- a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md +++ b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md @@ -23,9 +23,13 @@ tags:- -
1 <= text.length <= 50000
- -
text
contains only lowercase English letters.- -
1 <= w <= 107
- -
1 <= h <= 104
- -
1 <= fonts.length <= 105
- -
1 <= fonts[i] <= 105
- + +
fonts
is sorted in ascending order and does not contain duplicates.- + +
1 <= text.length <= 50000
- + +
text
contains only lowercase English letters.- + +
1 <= w <= 107
- + +
1 <= h <= 104
- + +
1 <= fonts.length <= 105
- + +
1 <= fonts[i] <= 105
- +
fonts
is sorted in ascending order and does not contain duplicates.Each node has three attributes:
-
- -
coefficient
: an integer representing the number multiplier of the term. The coefficient of the term9x4
is9
.- -
power
: an integer representing the exponent. The power of the term9x4
is4
.- + +
next
: a pointer to the next node in the list, ornull
if it is the last node of the list.- + +
coefficient
: an integer representing the number multiplier of the term. The coefficient of the term9x4
is9
.- + +
power
: an integer representing the exponent. The power of the term9x4
is4
.- +
next
: a pointer to the next node in the list, ornull
if it is the last node of the list.For example, the polynomial
@@ -41,41 +45,61 @@ tags:5x3 + 4x - 7
is represented by the polynomial linked list illustrated below:The input/output format is as a list of
n
nodes, where each node is represented as its[coefficient, power]
. For example, the polynomial5x3 + 4x - 7
would be represented as:[[5,3],[4,1],[-7,0]]
.+
Example 1:
+ Input: poly1 = [[1,1]], poly2 = [[1,0]] + Output: [[1,1],[1,0]] + Explanation: poly1 = x. poly2 = 1. The sum is x + 1. +Example 2:
+ Input: poly1 = [[2,2],[4,1],[3,0]], poly2 = [[3,2],[-4,1],[-1,0]] + Output: [[5,2],[2,0]] + Explanation: poly1 = 2x2 + 4x + 3. poly2 = 3x2 - 4x - 1. The sum is 5x2 + 2. Notice that we omit the "0x" term. +Example 3:
+ Input: poly1 = [[1,2]], poly2 = [[-1,2]] + Output: [] + Explanation: The sum is 0. We return an empty list. ++
Constraints:
-
diff --git a/solution/1600-1699/1645.Hopper Company Queries II/README.md b/solution/1600-1699/1645.Hopper Company Queries II/README.md index 6c8f6c4717934..7d6973ef7fbae 100644 --- a/solution/1600-1699/1645.Hopper Company Queries II/README.md +++ b/solution/1600-1699/1645.Hopper Company Queries II/README.md @@ -151,16 +151,16 @@ ride_id 是该表具有唯一值的列。 解释: 截至 1 月底 --> 2 个活跃的驾驶员 (10, 8),无被接受的行程。百分比是0%。 截至 2 月底 --> 3 个活跃的驾驶员 (10, 8, 5),无被接受的行程。百分比是0%。 -截至 3 月底 --> 4 个活跃的驾驶员 (10, 8, 5, 7),1 个被接受的行程 (10)。百分比是 (1 / 4) * 100 = 25%。 +截至 3 月底 --> 4 个活跃的驾驶员 (10, 8, 5, 7),1 个被驾驶员 (10) 接受的行程。百分比是 (1 / 4) * 100 = 25%。 截至 4 月底 --> 4 个活跃的驾驶员 (10, 8, 5, 7),无被接受的行程。百分比是 0%。 截至 5 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),无被接受的行程。百分比是 0%。 -截至 6 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),1 个被接受的行程 (10)。 百分比是 (1 / 5) * 100 = 20%。 -截至 7 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),1 个被接受的行程 (8)。百分比是 (1 / 5) * 100 = 20%。 -截至 8 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),1 个被接受的行程 (7)。百分比是 (1 / 5) * 100 = 20%。 +截至 6 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),1 个被驾驶员 (10) 接受的行程。 百分比是 (1 / 5) * 100 = 20%。 +截至 7 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),1 个被驾驶员 (8) 接受的行程。百分比是 (1 / 5) * 100 = 20%。 +截至 8 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),1 个被驾驶员 (7) 接受的行程。百分比是 (1 / 5) * 100 = 20%。 截至 9 月底 --> 5 个活跃的驾驶员 (10, 8, 5, 7, 4),无被接受的行程。百分比是 0%。 截至 10 月底 --> 6 个活跃的驾驶员 (10, 8, 5, 7, 4, 1) 无被接受的行程。百分比是 0%。 -截至 11 月底 --> 6 个活跃的驾驶员 (10, 8, 5, 7, 4, 1),2 个被接受的行程 (1, 7)。百分比是 (2 / 6) * 100 = 33.33%。 -截至 12 月底 --> 6 个活跃的驾驶员 (10, 8, 5, 7, 4, 1),1 个被接受的行程 (4)。百分比是 (1 / 6) * 100 = 16.67%。 +截至 11 月底 --> 6 个活跃的驾驶员 (10, 8, 5, 7, 4, 1),2 个被不同驾驶员 (1, 7) 接受的行程。百分比是 (2 / 6) * 100 = 33.33%。 +截至 12 月底 --> 6 个活跃的驾驶员 (10, 8, 5, 7, 4, 1),1 个被驾驶员 (4) 接受的行程。百分比是 (1 / 6) * 100 = 16.67%。- -
0 <= n <= 104
- -
-109 <= PolyNode.coefficient <= 109
- -
PolyNode.coefficient != 0
- -
0 <= PolyNode.power <= 109
- + +
PolyNode.power > PolyNode.next.power
- + +
0 <= n <= 104
- + +
-109 <= PolyNode.coefficient <= 109
- + +
PolyNode.coefficient != 0
- + +
0 <= PolyNode.power <= 109
- +
PolyNode.power > PolyNode.next.power
Given an integer array
instructions
, you are asked to create a sorted array from the elements ininstructions
. You start with an empty containernums
. For each element from left to right ininstructions
, insert it intonums
. The cost of each insertion is the minimum of the following:-
- The number of elements currently in
-nums
that are strictly less thaninstructions[i]
.- The number of elements currently in
+ +nums
that are strictly greater thaninstructions[i]
.- The number of elements currently in
+ +nums
that are strictly less thaninstructions[i]
.- The number of elements currently in
+nums
that are strictly greater thaninstructions[i]
.For example, if inserting element
@@ -36,57 +39,95 @@ tags:3
intonums = [1,2,3,5]
, the cost of insertion ismin(2, 1)
(elements1
and2
are less than3
, element5
is greater than3
) andnums
will become[1,2,3,3,5]
.Return the total cost to insert all elements from
instructions
intonums
. Since the answer may be large, return it modulo109 + 7
+
Example 1:
+ Input: instructions = [1,5,6,2] + Output: 1 + Explanation: Begin with nums = []. + Insert 1 with cost min(0, 0) = 0, now nums = [1]. + Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. + Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. + Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. + The total cost is 0 + 0 + 0 + 1 = 1.Example 2:
+ Input: instructions = [1,2,3,6,5,4] + Output: 3 + Explanation: Begin with nums = []. + Insert 1 with cost min(0, 0) = 0, now nums = [1]. + Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. + Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. + Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. + Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. + Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. + The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. +Example 3:
+ Input: instructions = [1,3,3,3,2,4,2,1,2] + Output: 4 + Explanation: Begin with nums = []. + Insert 1 with cost min(0, 0) = 0, now nums = [1]. + Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. + Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. + Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. + Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. + Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. + Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. + Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. + Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. + The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4. ++
Constraints:
-
diff --git a/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md b/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md index 4a5e058ed554d..4c4926392dd0d 100644 --- a/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md +++ b/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md @@ -29,22 +29,31 @@ tags:- -
1 <= instructions.length <= 105
- + +
1 <= instructions[i] <= 105
- + +
1 <= instructions.length <= 105
- +
1 <= instructions[i] <= 105
The test input is read as 3 lines:
-
- -
TreeNode root
- -
int fromNode
(not available tocorrectBinaryTree
)- + +
int toNode
(not available tocorrectBinaryTree
)- + +
TreeNode root
- + +
int fromNode
(not available tocorrectBinaryTree
)- +
int toNode
(not available tocorrectBinaryTree
)After the binary tree rooted at
root
is parsed, theTreeNode
with value offromNode
will have its right child pointer pointing to theTreeNode
with a value oftoNode
. Then,root
is passed tocorrectBinaryTree
.+
Example 1:
+ Input: root = [1,2,3], fromNode = 2, toNode = 3 + Output: [1,null,3] + Explanation: The node with value 2 is invalid, so remove it. +Example 2:
@@ -52,22 +61,35 @@ tags:
+ Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4 + Output: [8,3,1,null,null,9,4,null,null,5,6] + Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2. ++
Constraints:
-
diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md index 26dcf2fea57a6..7d844099664f8 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md @@ -156,9 +156,7 @@ class Solution { Arrays.sort(nums); int n = queries.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); int[] ans = new int[n]; Trie trie = new Trie(); diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md index 48b6e43efcc4e..5bfcb9d83a61c 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md @@ -156,9 +156,7 @@ class Solution { Arrays.sort(nums); int n = queries.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); int[] ans = new int[n]; Trie trie = new Trie(); diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java index ddaca27459a9d..7eff272997151 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.java @@ -35,9 +35,7 @@ public int[] maximizeXor(int[] nums, int[][] queries) { Arrays.sort(nums); int n = queries.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> queries[i][1] - queries[j][1]); int[] ans = new int[n]; Trie trie = new Trie(); diff --git a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md index cbb623295007f..34f00129f2a96 100644 --- a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md +++ b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md @@ -27,30 +27,45 @@ tags:- The number of nodes in the tree is in the range
-[3, 104]
.- -
-109 <= Node.val <= 109
- All
-Node.val
are unique.- -
fromNode != toNode
- -
fromNode
andtoNode
will exist in the tree and will be on the same depth.- -
toNode
is to the right offromNode
.- + +
fromNode.right
isnull
in the initial tree from the test data.- The number of nodes in the tree is in the range
+ +[3, 104]
.- + +
-109 <= Node.val <= 109
- All
+ +Node.val
are unique.- + +
fromNode != toNode
- + +
fromNode
andtoNode
will exist in the tree and will be on the same depth.- + +
toNode
is to the right offromNode
.- +
fromNode.right
isnull
in the initial tree from the test data.Return the number of rectangles that can make a square with a side length of
maxLen
.+
Example 1:
+ Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] + Output: 3 + Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5]. + The largest possible square is of length 5, and you can get it out of 3 rectangles. +Example 2:
+ Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] + Output: 3 ++
Constraints:
-
diff --git a/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md b/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md index a96cde7d700f3..2ae33ffa3a49c 100644 --- a/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md +++ b/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md @@ -22,26 +22,37 @@ tags:- -
1 <= rectangles.length <= 1000
- -
rectangles[i].length == 2
- -
1 <= li, wi <= 109
- + +
li != wi
- + +
1 <= rectangles.length <= 1000
- + +
rectangles[i].length == 2
- + +
1 <= li, wi <= 109
- +
li != wi
Return the maximum possible subarray sum after exactly one operation. The subarray must be non-empty.
+
Example 1:
+ Input: nums = [2,-1,-4,-3] + Output: 17 + Explanation: You can perform the operation on index 2 (0-indexed) to make nums = [2,-1,16,-3]. Now, the maximum subarray sum is 2 + -1 + 16 = 17.Example 2:
+ Input: nums = [1,-1,1,1,-1,-1,1] + Output: 4 + Explanation: You can perform the operation on index 1 (0-indexed) to make nums = [1,1,1,1,-1,-1,1]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4.+
Constraints:
-
diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md index 97bd26ee00b3a..6b6997b781b93 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md @@ -76,21 +76,21 @@ tags: ### 方法一:记忆化搜索 + 二分查找 -我们先将会议按照开始时间从小到大排序,然后设计一个函数 $dfs(i, k)$ 表示从第 $i$ 个会议开始,最多参加 $k$ 个会议的最大价值和。答案即为 $dfs(0, k)$。 +我们先将会议按照开始时间从小到大排序,然后设计一个函数 $\text{dfs}(i, k)$ 表示从第 $i$ 个会议开始,最多参加 $k$ 个会议的最大价值和。答案即为 $\text{dfs}(0, k)$。 -函数 $dfs(i, k)$ 的计算过程如下: +函数 $\text{dfs}(i, k)$ 的计算过程如下: -对于第 $i$ 个会议,我们可以选择参加或者不参加。如果不参加,那么最大价值和就是 $dfs(i + 1, k)$,如果参加,我们可以通过二分查找,找到第一个开始时间大于第 $i$ 个会议结束时间的会议,记为 $j$,那么最大价值和就是 $dfs(j, k - 1) + value[i]$。取二者的较大值即可。即: +如果不参加第 $i$ 个会议,那么最大价值和就是 $\text{dfs}(i + 1, k)$;如果参加第 $i$ 个会议,我们可以通过二分查找,找到第一个开始时间大于第 $i$ 个会议结束时间的会议,记为 $j$,那么最大价值和就是 $\text{dfs}(j, k - 1) + \text{value}[i]$。取二者的较大值即可。即: $$ -dfs(i, k) = \max(dfs(i + 1, k), dfs(j, k - 1) + value[i]) +\text{dfs}(i, k) = \max(\text{dfs}(i + 1, k), \text{dfs}(j, k - 1) + \text{value}[i]) $$ 其中 $j$ 为第一个开始时间大于第 $i$ 个会议结束时间的会议,可以通过二分查找得到。 -由于函数 $dfs(i, k)$ 的计算过程中,会调用 $dfs(i + 1, k)$ 和 $dfs(j, k - 1)$,因此我们可以使用记忆化搜索,将计算过的值保存下来,避免重复计算。 +由于函数 $\text{dfs}(i, k)$ 的计算过程中,会调用 $\text{dfs}(i + 1, k)$ 和 $\text{dfs}(j, k - 1)$,因此我们可以使用记忆化搜索,将计算过的值保存下来,避免重复计算。 -时间复杂度 $O(n\times \log n + n\times k)$,其中 $n$ 为会议数量。 +时间复杂度 $O(n \times \log n + n \times k)$,空间复杂度 $O(n \times k)$,其中 $n$ 为会议数量。 @@ -163,23 +163,29 @@ class Solution { class Solution { public: int maxValue(vector- -
1 <= nums.length <= 105
- + +
-104 <= nums[i] <= 104
- + +
1 <= nums.length <= 105
- +
-104 <= nums[i] <= 104
>& events, int k) { - sort(events.begin(), events.end()); + ranges::sort(events); int n = events.size(); int f[n][k + 1]; memset(f, 0, sizeof(f)); - function dfs = [&](int i, int k) -> int { + auto dfs = [&](this auto&& dfs, int i, int k) -> int { if (i >= n || k <= 0) { return 0; } if (f[i][k] > 0) { return f[i][k]; } + int ed = events[i][1], val = events[i][2]; vector t = {ed}; - int p = upper_bound(events.begin() + i + 1, events.end(), t, [](const auto& a, const auto& b) { return a[0] < b[0]; }) - events.begin(); + + int p = upper_bound(events.begin() + i + 1, events.end(), t, + [](const auto& a, const auto& b) { return a[0] < b[0]; }) + - events.begin(); + f[i][k] = max(dfs(i + 1, k), dfs(p, k - 1) + val); return f[i][k]; }; + return dfs(0, k); } }; @@ -216,30 +222,79 @@ func maxValue(events [][]int, k int) int { ```ts function maxValue(events: number[][], k: number): number { - events.sort((a, b) => a[1] - b[1]); + events.sort((a, b) => a[0] - b[0]); const n = events.length; - const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); - const search = (x: number, hi: number): number => { - let l = 0; - let r = hi; - while (l < r) { - const mid = (l + r) >> 1; - if (events[mid][1] >= x) { - r = mid; + const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(0)); + + const dfs = (i: number, k: number): number => { + if (i >= n || k <= 0) { + return 0; + } + if (f[i][k] > 0) { + return f[i][k]; + } + + const ed = events[i][1], + val = events[i][2]; + + let left = i + 1, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (events[mid][0] > ed) { + right = mid; } else { - l = mid + 1; + left = mid + 1; } } - return l; + const p = left; + + f[i][k] = Math.max(dfs(i + 1, k), dfs(p, k - 1) + val); + return f[i][k]; }; - for (let i = 1; i <= n; ++i) { - const [st, _, val] = events[i - 1]; - const p = search(st, i - 1); - for (let j = 1; j <= k; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + + return dfs(0, k); +} +``` + +#### Rust + +```rust +impl Solution { + pub fn max_value(mut events: Vec >, k: i32) -> i32 { + events.sort_by_key(|e| e[0]); + let n = events.len(); + let mut f = vec![vec![0; (k + 1) as usize]; n]; + + fn dfs(i: usize, k: i32, events: &Vec >, f: &mut Vec >, n: usize) -> i32 { + if i >= n || k <= 0 { + return 0; + } + if f[i][k as usize] != 0 { + return f[i][k as usize]; + } + let j = search(events, events[i][1], i + 1, n); + let ans = dfs(i + 1, k, events, f, n).max(dfs(j, k - 1, events, f, n) + events[i][2]); + f[i][k as usize] = ans; + ans } + + fn search(events: &Vec >, x: i32, lo: usize, n: usize) -> usize { + let mut l = lo; + let mut r = n; + while l < r { + let mid = (l + r) / 2; + if events[mid][0] > x { + r = mid; + } else { + l = mid + 1; + } + } + l + } + + dfs(0, k, &events, &mut f, n) } - return f[n][k]; } ``` @@ -255,15 +310,15 @@ function maxValue(events: number[][], k: number): number { 先将会议排序,这次我们按照结束时间从小到大排序。然后定义 $f[i][j]$ 表示前 $i$ 个会议中,最多参加 $j$ 个会议的最大价值和。答案即为 $f[n][k]$。 -对于第 $i$ 个会议,我们可以选择参加或者不参加。如果不参加,那么最大价值和就是 $f[i][j]$,如果参加,我们可以通过二分查找,找到最后一个结束时间小于第 $i$ 个会议开始时间的会议,记为 $h$,那么最大价值和就是 $f[h+1][j - 1] + value[i]$。取二者的较大值即可。即: +对于第 $i$ 个会议,我们可以选择参加或者不参加。如果不参加,那么最大价值和就是 $f[i][j]$,如果参加,我们可以通过二分查找,找到最后一个结束时间小于第 $i$ 个会议开始时间的会议,记为 $h$,那么最大价值和就是 $f[h + 1][j - 1] + \text{value}[i]$。取二者的较大值即可。即: $$ -f[i+1][j] = \max(f[i][j], f[h+1][j - 1] + value[i]) +f[i + 1][j] = \max(f[i][j], f[h + 1][j - 1] + \text{value}[i]) $$ 其中 $h$ 为最后一个结束时间小于第 $i$ 个会议开始时间的会议,可以通过二分查找得到。 -时间复杂度 $O(n\times \log n + n\times k)$,其中 $n$ 为会议数量。 +时间复杂度 $O(n \times \log n + n \times k)$,空间复杂度 $O(n \times k)$,其中 $n$ 为会议数量。 相似题目: @@ -364,6 +419,74 @@ func maxValue(events [][]int, k int) int { } ``` +#### TypeScript + +```ts +function maxValue(events: number[][], k: number): number { + events.sort((a, b) => a[1] - b[1]); + const n = events.length; + const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); + const search = (x: number, hi: number): number => { + let l = 0; + let r = hi; + while (l < r) { + const mid = (l + r) >> 1; + if (events[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (let i = 1; i <= n; ++i) { + const [st, _, val] = events[i - 1]; + const p = search(st, i - 1); + for (let j = 1; j <= k; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn max_value(mut events: Vec >, k: i32) -> i32 { + events.sort_by_key(|e| e[1]); + let n = events.len(); + let mut f = vec![vec![0; (k + 1) as usize]; n + 1]; + + for i in 1..=n { + let st = events[i - 1][0]; + let val = events[i - 1][2]; + let p = search(&events, st, i - 1); + for j in 1..=k as usize { + f[i][j] = f[i - 1][j].max(f[p][j - 1] + val); + } + } + + f[n][k as usize] + } +} + +fn search(events: &Vec >, x: i32, hi: usize) -> usize { + let mut l = 0; + let mut r = hi; + while l < r { + let mid = (l + r) / 2; + if events[mid][1] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l +} +``` + diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md index a8a515dca126a..6f87bd6062aad 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md @@ -72,7 +72,23 @@ Notice that you cannot attend any other event as they overlap, and that you do < -### Solution 1 +### Solution 1: Memoization + Binary Search + +First, we sort the events by their start time in ascending order. Then, we define a function $\text{dfs}(i, k)$, which represents the maximum total value achievable by attending at most $k$ events starting from the $i$-th event. The answer is $\text{dfs}(0, k)$. + +The calculation process of the function $\text{dfs}(i, k)$ is as follows: + +If we do not attend the $i$-th event, the maximum value is $\text{dfs}(i + 1, k)$. If we attend the $i$-th event, we can use binary search to find the first event whose start time is greater than the end time of the $i$-th event, denoted as $j$. Then, the maximum value is $\text{dfs}(j, k - 1) + \text{value}[i]$. We take the maximum of the two options: + +$$ +\text{dfs}(i, k) = \max(\text{dfs}(i + 1, k), \text{dfs}(j, k - 1) + \text{value}[i]) +$$ + +Here, $j$ is the index of the first event whose start time is greater than the end time of the $i$-th event, which can be found using binary search. + +Since the calculation of $\text{dfs}(i, k)$ involves calls to $\text{dfs}(i + 1, k)$ and $\text{dfs}(j, k - 1)$, we can use memoization to store the computed values and avoid redundant calculations. + +The time complexity is $O(n \times \log n + n \times k)$, and the space complexity is $O(n \times k)$, where $n$ is the number of events. @@ -145,23 +161,29 @@ class Solution { class Solution { public: int maxValue(vector >& events, int k) { - sort(events.begin(), events.end()); + ranges::sort(events); int n = events.size(); int f[n][k + 1]; memset(f, 0, sizeof(f)); - function dfs = [&](int i, int k) -> int { + auto dfs = [&](this auto&& dfs, int i, int k) -> int { if (i >= n || k <= 0) { return 0; } if (f[i][k] > 0) { return f[i][k]; } + int ed = events[i][1], val = events[i][2]; vector t = {ed}; - int p = upper_bound(events.begin() + i + 1, events.end(), t, [](const auto& a, const auto& b) { return a[0] < b[0]; }) - events.begin(); + + int p = upper_bound(events.begin() + i + 1, events.end(), t, + [](const auto& a, const auto& b) { return a[0] < b[0]; }) + - events.begin(); + f[i][k] = max(dfs(i + 1, k), dfs(p, k - 1) + val); return f[i][k]; }; + return dfs(0, k); } }; @@ -198,30 +220,79 @@ func maxValue(events [][]int, k int) int { ```ts function maxValue(events: number[][], k: number): number { - events.sort((a, b) => a[1] - b[1]); + events.sort((a, b) => a[0] - b[0]); const n = events.length; - const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); - const search = (x: number, hi: number): number => { - let l = 0; - let r = hi; - while (l < r) { - const mid = (l + r) >> 1; - if (events[mid][1] >= x) { - r = mid; + const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(0)); + + const dfs = (i: number, k: number): number => { + if (i >= n || k <= 0) { + return 0; + } + if (f[i][k] > 0) { + return f[i][k]; + } + + const ed = events[i][1], + val = events[i][2]; + + let left = i + 1, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (events[mid][0] > ed) { + right = mid; } else { - l = mid + 1; + left = mid + 1; } } - return l; + const p = left; + + f[i][k] = Math.max(dfs(i + 1, k), dfs(p, k - 1) + val); + return f[i][k]; }; - for (let i = 1; i <= n; ++i) { - const [st, _, val] = events[i - 1]; - const p = search(st, i - 1); - for (let j = 1; j <= k; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + + return dfs(0, k); +} +``` + +#### Rust + +```rust +impl Solution { + pub fn max_value(mut events: Vec >, k: i32) -> i32 { + events.sort_by_key(|e| e[0]); + let n = events.len(); + let mut f = vec![vec![0; (k + 1) as usize]; n]; + + fn dfs(i: usize, k: i32, events: &Vec >, f: &mut Vec >, n: usize) -> i32 { + if i >= n || k <= 0 { + return 0; + } + if f[i][k as usize] != 0 { + return f[i][k as usize]; + } + let j = search(events, events[i][1], i + 1, n); + let ans = dfs(i + 1, k, events, f, n).max(dfs(j, k - 1, events, f, n) + events[i][2]); + f[i][k as usize] = ans; + ans + } + + fn search(events: &Vec >, x: i32, lo: usize, n: usize) -> usize { + let mut l = lo; + let mut r = n; + while l < r { + let mid = (l + r) / 2; + if events[mid][0] > x { + r = mid; + } else { + l = mid + 1; + } + } + l } + + dfs(0, k, &events, &mut f, n) } - return f[n][k]; } ``` @@ -231,7 +302,26 @@ function maxValue(events: number[][], k: number): number { -### Solution 2 +### Solution 2: Dynamic Programming + Binary Search + +We can convert the memoization approach in Solution 1 to dynamic programming. + +First, sort the events, this time by end time in ascending order. Then define $f[i][j]$ as the maximum total value by attending at most $j$ events among the first $i$ events. The answer is $f[n][k]$. + +For the $i$-th event, we can choose to attend it or not. If we do not attend, the maximum value is $f[i][j]$. If we attend, we can use binary search to find the last event whose end time is less than the start time of the $i$-th event, denoted as $h$. Then the maximum value is $f[h + 1][j - 1] + \text{value}[i]$. We take the maximum of the two options: + +$$ +f[i + 1][j] = \max(f[i][j], f[h + 1][j - 1] + \text{value}[i]) +$$ + +Here, $h$ is the last event whose end time is less than the start time of the $i$-th event, which can be found by binary search. + +The time complexity is $O(n \times \log n + n \times k)$, and the space complexity is $O(n \times k)$, where $n$ is the number of events. + +Related problems: + +- [1235. Maximum Profit in Job Scheduling](https://github.com/doocs/leetcode/blob/main/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README_EN.md) +- [2008. Maximum Earnings From Taxi](https://github.com/doocs/leetcode/blob/main/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README_EN.md) @@ -327,6 +417,74 @@ func maxValue(events [][]int, k int) int { } ``` +#### TypeScript + +```ts +function maxValue(events: number[][], k: number): number { + events.sort((a, b) => a[1] - b[1]); + const n = events.length; + const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); + const search = (x: number, hi: number): number => { + let l = 0; + let r = hi; + while (l < r) { + const mid = (l + r) >> 1; + if (events[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (let i = 1; i <= n; ++i) { + const [st, _, val] = events[i - 1]; + const p = search(st, i - 1); + for (let j = 1; j <= k; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn max_value(mut events: Vec >, k: i32) -> i32 { + events.sort_by_key(|e| e[1]); + let n = events.len(); + let mut f = vec![vec![0; (k + 1) as usize]; n + 1]; + + for i in 1..=n { + let st = events[i - 1][0]; + let val = events[i - 1][2]; + let p = search(&events, st, i - 1); + for j in 1..=k as usize { + f[i][j] = f[i - 1][j].max(f[p][j - 1] + val); + } + } + + f[n][k as usize] + } +} + +fn search(events: &Vec >, x: i32, hi: usize) -> usize { + let mut l = 0; + let mut r = hi; + while l < r { + let mid = (l + r) / 2; + if events[mid][1] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l +} +``` + diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp index 42e112883fae4..c854e716cef7b 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.cpp @@ -1,23 +1,29 @@ class Solution { public: int maxValue(vector >& events, int k) { - sort(events.begin(), events.end()); + ranges::sort(events); int n = events.size(); int f[n][k + 1]; memset(f, 0, sizeof(f)); - function dfs = [&](int i, int k) -> int { + auto dfs = [&](this auto&& dfs, int i, int k) -> int { if (i >= n || k <= 0) { return 0; } if (f[i][k] > 0) { return f[i][k]; } + int ed = events[i][1], val = events[i][2]; vector t = {ed}; - int p = upper_bound(events.begin() + i + 1, events.end(), t, [](const auto& a, const auto& b) { return a[0] < b[0]; }) - events.begin(); + + int p = upper_bound(events.begin() + i + 1, events.end(), t, + [](const auto& a, const auto& b) { return a[0] < b[0]; }) + - events.begin(); + f[i][k] = max(dfs(i + 1, k), dfs(p, k - 1) + val); return f[i][k]; }; + return dfs(0, k); } -}; \ No newline at end of file +}; diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.rs b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.rs new file mode 100644 index 0000000000000..d5a8276d68778 --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn max_value(mut events: Vec >, k: i32) -> i32 { + events.sort_by_key(|e| e[0]); + let n = events.len(); + let mut f = vec![vec![0; (k + 1) as usize]; n]; + + fn dfs(i: usize, k: i32, events: &Vec >, f: &mut Vec >, n: usize) -> i32 { + if i >= n || k <= 0 { + return 0; + } + if f[i][k as usize] != 0 { + return f[i][k as usize]; + } + let j = search(events, events[i][1], i + 1, n); + let ans = dfs(i + 1, k, events, f, n).max(dfs(j, k - 1, events, f, n) + events[i][2]); + f[i][k as usize] = ans; + ans + } + + fn search(events: &Vec >, x: i32, lo: usize, n: usize) -> usize { + let mut l = lo; + let mut r = n; + while l < r { + let mid = (l + r) / 2; + if events[mid][0] > x { + r = mid; + } else { + l = mid + 1; + } + } + l + } + + dfs(0, k, &events, &mut f, n) + } +} diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.ts b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.ts index c370b2cb5e927..169bcdab7d110 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.ts +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution.ts @@ -1,26 +1,34 @@ function maxValue(events: number[][], k: number): number { - events.sort((a, b) => a[1] - b[1]); + events.sort((a, b) => a[0] - b[0]); const n = events.length; - const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); - const search = (x: number, hi: number): number => { - let l = 0; - let r = hi; - while (l < r) { - const mid = (l + r) >> 1; - if (events[mid][1] >= x) { - r = mid; + const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(0)); + + const dfs = (i: number, k: number): number => { + if (i >= n || k <= 0) { + return 0; + } + if (f[i][k] > 0) { + return f[i][k]; + } + + const ed = events[i][1], + val = events[i][2]; + + let left = i + 1, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (events[mid][0] > ed) { + right = mid; } else { - l = mid + 1; + left = mid + 1; } } - return l; + const p = left; + + f[i][k] = Math.max(dfs(i + 1, k), dfs(p, k - 1) + val); + return f[i][k]; }; - for (let i = 1; i <= n; ++i) { - const [st, _, val] = events[i - 1]; - const p = search(st, i - 1); - for (let j = 1; j <= k; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); - } - } - return f[n][k]; + + return dfs(0, k); } diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.rs b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.rs new file mode 100644 index 0000000000000..c908d6ad6baba --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn max_value(mut events: Vec >, k: i32) -> i32 { + events.sort_by_key(|e| e[1]); + let n = events.len(); + let mut f = vec![vec![0; (k + 1) as usize]; n + 1]; + + for i in 1..=n { + let st = events[i - 1][0]; + let val = events[i - 1][2]; + let p = search(&events, st, i - 1); + for j in 1..=k as usize { + f[i][j] = f[i - 1][j].max(f[p][j - 1] + val); + } + } + + f[n][k as usize] + } +} + +fn search(events: &Vec >, x: i32, hi: usize) -> usize { + let mut l = 0; + let mut r = hi; + while l < r { + let mid = (l + r) / 2; + if events[mid][1] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l +} diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.ts b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.ts new file mode 100644 index 0000000000000..c370b2cb5e927 --- /dev/null +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/Solution2.ts @@ -0,0 +1,26 @@ +function maxValue(events: number[][], k: number): number { + events.sort((a, b) => a[1] - b[1]); + const n = events.length; + const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); + const search = (x: number, hi: number): number => { + let l = 0; + let r = hi; + while (l < r) { + const mid = (l + r) >> 1; + if (events[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + for (let i = 1; i <= n; ++i) { + const [st, _, val] = events[i - 1]; + const p = search(st, i - 1); + for (let j = 1; j <= k; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; +} diff --git a/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md b/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md index 28ec43946435a..23f19bc99a475 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md +++ b/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md @@ -24,45 +24,71 @@ tags: Return the merged string.
+
Example 1:
+ Input: word1 = "abc", word2 = "pqr" + Output: "apbqcr" + Explanation: The merged string will be merged as so: + word1: a b c + word2: p q r + merged: a p b q c r +Example 2:
+ Input: word1 = "ab", word2 = "pqrs" + Output: "apbqrs" + Explanation: Notice that as word2 is longer, "rs" is appended to the end. + word1: a b + word2: p q r s + merged: a p b q r s +Example 3:
+ Input: word1 = "abcd", word2 = "pq" + Output: "apbqcd" + Explanation: Notice that as word1 is longer, "cd" is appended to the end. + word1: a b c d + word2: p q + merged: a p b q c d ++
Constraints:
-
diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md index 3c74cd0136b01..965915a1bbd8b 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md @@ -5,8 +5,9 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1700-1799/1778.Sh tags: - 深度优先搜索 - 广度优先搜索 - - 图 + - 数组 - 交互 + - 矩阵 --- diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md index f902059a7f622..2a059dda5f5f5 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md @@ -5,8 +5,9 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1700-1799/1778.Sh tags: - Depth-First Search - Breadth-First Search - - Graph + - Array - Interactive + - Matrix --- diff --git a/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md b/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md index 8060248067a33..08179c3e044b3 100644 --- a/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md +++ b/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md @@ -24,8 +24,11 @@ tags:- -
1 <= word1.length, word2.length <= 100
- + +
word1
andword2
consist of lowercase English letters.- + +
1 <= word1.length, word2.length <= 100
- +
word1
andword2
consist of lowercase English letters.A garden is valid if it meets these conditions:
-
- The garden has at least two flowers.
-- The first and the last flower of the garden have the same beauty value.
+ +- The garden has at least two flowers.
+ +- The first and the last flower of the garden have the same beauty value.
+As the appointed gardener, you have the ability to remove any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden valid. The beauty of the garden is the sum of the beauty of all the remaining flowers.
@@ -33,36 +36,53 @@ tags:Return the maximum possible beauty of some valid garden after you have removed any (possibly none) flowers.
+
Example 1:
+ Input: flowers = [1,2,3,1,2] + Output: 8 + Explanation: You can produce the valid garden [2,3,1,2] to have a total beauty of 2 + 3 + 1 + 2 = 8.Example 2:
+ Input: flowers = [100,1,1,-3,1] + Output: 3 + Explanation: You can produce the valid garden [1,1,1] to have a total beauty of 1 + 1 + 1 = 3. +Example 3:
+ Input: flowers = [-1,-2,0,-1] + Output: -2 + Explanation: You can produce the valid garden [-1,-1] to have a total beauty of -1 + -1 = -2. ++
Constraints:
-
diff --git a/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md b/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md index 858710a6203f7..fb8b1f0df8967 100644 --- a/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md +++ b/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md @@ -23,8 +23,11 @@ tags:- -
2 <= flowers.length <= 105
- -
-104 <= flowers[i] <= 104
- It is possible to create a valid garden by removing some (possibly none) flowers.
+ +- + +
2 <= flowers.length <= 105
- + +
-104 <= flowers[i] <= 104
- It is possible to create a valid garden by removing some (possibly none) flowers.
+You are given a 2D integer array
orders
, where eachorders[i] = [pricei, amounti, orderTypei]
denotes thatamounti
orders have been placed of typeorderTypei
at the pricepricei
. TheorderTypei
is:-
- -
0
if it is a batch ofbuy
orders, or- + +
1
if it is a batch ofsell
orders.- + +
0
if it is a batch ofbuy
orders, or- +
1
if it is a batch ofsell
orders.Note that
@@ -32,47 +35,79 @@ tags:orders[i]
represents a batch ofamounti
independent orders with the same price and order type. All orders represented byorders[i]
will be placed before all orders represented byorders[i+1]
for all validi
.There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
-
- If the order is a
-buy
order, you look at thesell
order with the smallest price in the backlog. If thatsell
order's price is smaller than or equal to the currentbuy
order's price, they will match and be executed, and thatsell
order will be removed from the backlog. Else, thebuy
order is added to the backlog.- Vice versa, if the order is a
+ +sell
order, you look at thebuy
order with the largest price in the backlog. If thatbuy
order's price is larger than or equal to the currentsell
order's price, they will match and be executed, and thatbuy
order will be removed from the backlog. Else, thesell
order is added to the backlog.- If the order is a
+ +buy
order, you look at thesell
order with the smallest price in the backlog. If thatsell
order's price is smaller than or equal to the currentbuy
order's price, they will match and be executed, and thatsell
order will be removed from the backlog. Else, thebuy
order is added to the backlog.- Vice versa, if the order is a
+sell
order, you look at thebuy
order with the largest price in the backlog. If thatbuy
order's price is larger than or equal to the currentsell
order's price, they will match and be executed, and thatbuy
order will be removed from the backlog. Else, thesell
order is added to the backlog.Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo
109 + 7
.+
Example 1:
++
+ Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]] + Output: 6 + Explanation: Here is what happens with the orders: + - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. + - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. + - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. + - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. + Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6. +Example 2:
++
+ Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]] + Output: 999999984 + Explanation: Here is what happens with the orders: + - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. + - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. + - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. + - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. + Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7). ++
Constraints:
-
diff --git a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md index 3902264817560..79459f61da135 100644 --- a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md +++ b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md @@ -6,6 +6,7 @@ rating: 1929 source: 第 233 场周赛 Q3 tags: - 贪心 + - 数学 - 二分查找 --- diff --git a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md index 4370d39827873..3bd85a7016599 100644 --- a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md +++ b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md @@ -6,6 +6,7 @@ rating: 1929 source: Weekly Contest 233 Q3 tags: - Greedy + - Math - Binary Search --- diff --git a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md index 71d734e8f7114..b2f0cba2a3268 100644 --- a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md +++ b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md @@ -25,42 +25,69 @@ tags:- -
1 <= orders.length <= 105
- -
orders[i].length == 3
- -
1 <= pricei, amounti <= 109
- + +
orderTypei
is either0
or1
.- + +
1 <= orders.length <= 105
- + +
orders[i].length == 3
- + +
1 <= pricei, amounti <= 109
- +
orderTypei
is either0
or1
.A nice pair is a pair
(i, j)
where0 <= i < j < nums.length
andlow <= (nums[i] XOR nums[j]) <= high
.+
Example 1:
+ Input: nums = [1,4,2,7], low = 2, high = 6 + Output: 6 + Explanation: All nice pairs (i, j) are as follows: + - (0, 1): nums[0] XOR nums[1] = 5 + - (0, 2): nums[0] XOR nums[2] = 3 + - (0, 3): nums[0] XOR nums[3] = 6 + - (1, 2): nums[1] XOR nums[2] = 6 + - (1, 3): nums[1] XOR nums[3] = 3 + - (2, 3): nums[2] XOR nums[3] = 5 +Example 2:
+ Input: nums = [9,8,4,2,1], low = 5, high = 14 + Output: 8 + Explanation: All nice pairs (i, j) are as follows: + - (0, 2): nums[0] XOR nums[2] = 13 + - (0, 3): nums[0] XOR nums[3] = 11 + - (0, 4): nums[0] XOR nums[4] = 8 + - (1, 2): nums[1] XOR nums[2] = 12 + - (1, 3): nums[1] XOR nums[3] = 10 + - (1, 4): nums[1] XOR nums[4] = 9 + - (2, 3): nums[2] XOR nums[3] = 6 + - (2, 4): nums[2] XOR nums[4] = 5+
Constraints:
-
diff --git a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md index 043890fcacd1a..d114a92da494e 100644 --- a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md +++ b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md @@ -23,8 +23,11 @@ tags:- -
1 <= nums.length <= 2 * 104
- -
1 <= nums[i] <= 2 * 104
- + +
1 <= low <= high <= 2 * 104
- + +
1 <= nums.length <= 2 * 104
- + +
1 <= nums[i] <= 2 * 104
- +
1 <= low <= high <= 2 * 104
You are given a positive integer
primeFactors
. You are asked to construct a positive integern
that satisfies the following conditions:+
- The number of prime factors of
+n
(not necessarily distinct) is at mostprimeFactors
.- The number of nice divisors of
+n
is maximized. Note that a divisor ofn
is nice if it is divisible by every prime factor ofn
. For example, ifn = 12
, then its prime factors are[2,2,3]
, then6
and12
are nice divisors, while3
and4
are not.Return the number of nice divisors of
@@ -32,28 +35,41 @@ tags:n
. Since that number can be too large, return it modulo109 + 7
.Note that a prime number is a natural number greater than
1
that is not a product of two smaller natural numbers. The prime factors of a numbern
is a list of prime numbers such that their product equalsn
.+
Example 1:
+ Input: primeFactors = 5 + Output: 6 + Explanation: 200 is a valid value of n. + It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200]. + There is not other value of n that has at most 5 prime factors and more nice divisors. +Example 2:
+ Input: primeFactors = 8 + Output: 18 ++
Constraints:
-
diff --git a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md index 9e5976bfed137..5c371ef72ca08 100644 --- a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md +++ b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md @@ -6,7 +6,10 @@ tags: - 深度优先搜索 - 广度优先搜索 - 图 + - 数组 - 交互 + - 矩阵 + - 最短路 - 堆(优先队列) --- diff --git a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md index 61b3da16627c3..93d8f617e6e53 100644 --- a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md +++ b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md @@ -6,7 +6,10 @@ tags: - Depth-First Search - Breadth-First Search - Graph + - Array - Interactive + - Matrix + - Shortest Path - Heap (Priority Queue) --- diff --git a/solution/1800-1899/1825.Finding MK Average/README_EN.md b/solution/1800-1899/1825.Finding MK Average/README_EN.md index 47e210d29904b..e8e3c2ad1e56c 100644 --- a/solution/1800-1899/1825.Finding MK Average/README_EN.md +++ b/solution/1800-1899/1825.Finding MK Average/README_EN.md @@ -72,7 +72,7 @@ obj.calculateMKAverage(); // The last 3 elements are [5,5,5].- + +
1 <= primeFactors <= 109
- +
1 <= primeFactors <= 109
diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md index af4a7cf20dd88..979e584e8350d 100644 --- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md +++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md @@ -22,7 +22,9 @@ tags:
- -
3 <= m <= 105
- +
1 <= k*2 < m
1 < k*2 < m
1 <= num <= 105
- At most
105
calls will be made toaddElement
andcalculateMKAverage
.You are given an integer array
nums
(0-indexed). In one operation, you can choose an element of the array and increment it by1
.-
- For example, if
+ +nums = [1,2,3]
, you can choose to incrementnums[1]
to makenums = [1,3,3]
.- For example, if
+nums = [1,2,3]
, you can choose to incrementnums[1]
to makenums = [1,3,3]
.Return the minimum number of operations needed to make
@@ -30,37 +32,55 @@ tags:nums
strictly increasing.An array
nums
is strictly increasing ifnums[i] < nums[i+1]
for all0 <= i < nums.length - 1
. An array of length1
is trivially strictly increasing.+
Example 1:
+ Input: nums = [1,1,1] + Output: 3 + Explanation: You can do the following operations: + 1) Increment nums[2], so nums becomes [1,1,2]. + 2) Increment nums[1], so nums becomes [1,2,2]. + 3) Increment nums[2], so nums becomes [1,2,3]. +Example 2:
+ Input: nums = [1,5,2,4,1] + Output: 14 +Example 3:
+ Input: nums = [8] + Output: 0 ++
Constraints:
-
diff --git a/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md b/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md index 22fb099044ee4..e1c623dee2b31 100644 --- a/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md +++ b/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md @@ -22,36 +22,59 @@ tags:- -
1 <= nums.length <= 5000
- + +
1 <= nums[i] <= 104
- + +
1 <= nums.length <= 5000
- +
1 <= nums[i] <= 104
Return the linked list after the deletions.
+
Example 1:
++
+ Input: head = [1,2,3,2] + Output: [1,3] + Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3]. +Example 2:
++
+ Input: head = [2,1,1,2] + Output: [] + Explanation: 2 and 1 both appear twice. All the elements should be deleted. +Example 3:
++
+ Input: head = [3,2,2,1,3,2,4] + Output: [1,4] + Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4]. ++
Constraints:
-
diff --git a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md index 2a5ef80e5fc38..a4e2bda1312cc 100644 --- a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md +++ b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md @@ -7,6 +7,7 @@ source: 第 239 场周赛 Q2 tags: - 字符串 - 回溯 + - 枚举 --- diff --git a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md index 30dc658f3ac31..0b1f91ba8ca84 100644 --- a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md +++ b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md @@ -7,6 +7,7 @@ source: Weekly Contest 239 Q2 tags: - String - Backtracking + - Enumeration --- diff --git a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md index d252ef7e74def..3ea5956074c18 100644 --- a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md +++ b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md @@ -23,35 +23,37 @@ tags: -- The number of nodes in the list is in the range
-[1, 105]
- + +
1 <= Node.val <= 105
- The number of nodes in the list is in the range
+ +[1, 105]
- +
1 <= Node.val <= 105
给你一个 有向图 ,它含有
+n
个节点和m
条边。节点编号从0
到n - 1
。给你一个 有向图 ,它含有
-n
个节点和m
条边。节点编号从0
到n - 1
。给你一个字符串
+colors
,其中colors[i]
是小写英文字母,表示图中第i
个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组edges
,其中edges[j] = [aj, bj]
表示从节点aj
到节点bj
有一条 有向边 。给你一个字符串
-colors
,其中colors[i]
是小写英文字母,表示图中第i
个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组edges
,其中edges[j] = [aj, bj]
表示从节点aj
到节点bj
有一条 有向边 。图中一条有效 路径 是一个点序列
+x1 -> x2 -> x3 -> ... -> xk
,对于所有1 <= i < k
,从xi
到xi+1
在图中有一条有向边。路径的 颜色值 是路径中 出现次数最多 颜色的节点数目。图中一条有效 路径 是一个点序列
-x1 -> x2 -> x3 -> ... -> xk
,对于所有1 <= i < k
,从xi
到xi+1
在图中有一条有向边。路径的 颜色值 是路径中 出现次数最多 颜色的节点数目。请你返回给定图中有效路径里面的 最大颜色值 。如果图中含有环,请返回
+-1
。请你返回给定图中有效路径里面的 最大颜色值 。如果图中含有环,请返回
--1
。+
示例 1:
-+
-
输入:colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]] ++输入:colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]] 输出:3 -解释:路径 0 -> 2 -> 3 -> 4 含有 3 个颜色为"a" 的节点(上图中的红色节点)。
+解释:路径 0 -> 2 -> 3 -> 4 含有 3 个颜色为 "a" 的节点(上图中的红色节点)。示例 2:
-+
-
输入:colors = "a", edges = [[0,0]] ++输入:colors = "a", edges = [[0,0]] 输出:-1 解释:从 0 到 0 有一个环。-+
提示:
@@ -60,8 +62,8 @@ tags:m == edges.length
1 <= n <= 105
- 0 <= m <= 105
- colors
只含有小写英文字母。+ 0 <= aj, bj < n
+ colors
只含有小写英文字母。@@ -72,9 +74,17 @@ tags: ### 方法一:拓扑排序 + 动态规划 -求出每个点的入度,进行拓扑排序。每个点维护一个长度为 $26$ 的数组,记录每个字母从任意起点到当前点的出现次数。 +求出每个点的入度,进行拓扑排序。 -时间复杂度 $O(n+m)$,空间复杂度 $O(n+m)$。 +定义一个二维数组 $dp$,其中 $dp[i][j]$ 表示从起点到 $i$ 点,颜色为 $j$ 的节点数目。 + +从 $i$ 点出发,遍历所有出边 $i \to j$,更新 $dp[j][k] = \max(dp[j][k], dp[i][k] + (c == k))$,其中 $c$ 是 $j$ 点的颜色。 + +答案为数组 $dp$ 中的最大值。 + +如果图中有环,则无法遍历完所有点,返回 $-1$。 + +时间复杂度 $O((n + m) \times |\Sigma|)$,空间复杂度 $O(m + n \times |\Sigma)$。其中 $|\Sigma|$ 是字母表大小,这里为 $26$,而且 $n$ 和 $m$ 分别是节点数和边数。 @@ -252,6 +262,48 @@ func largestPathValue(colors string, edges [][]int) int { } ``` +#### TypeScript + +```ts +function largestPathValue(colors: string, edges: number[][]): number { + const n = colors.length; + const indeg = Array(n).fill(0); + const g: Map 0 <= aj, bj < n
= new Map(); + for (const [a, b] of edges) { + if (!g.has(a)) g.set(a, []); + g.get(a)!.push(b); + indeg[b]++; + } + const q: number[] = []; + const dp: number[][] = Array.from({ length: n }, () => Array(26).fill(0)); + for (let i = 0; i < n; i++) { + if (indeg[i] === 0) { + q.push(i); + const c = colors.charCodeAt(i) - 97; + dp[i][c]++; + } + } + let cnt = 0; + let ans = 1; + while (q.length) { + const i = q.pop()!; + cnt++; + if (g.has(i)) { + for (const j of g.get(i)!) { + indeg[j]--; + if (indeg[j] === 0) q.push(j); + const c = colors.charCodeAt(j) - 97; + for (let k = 0; k < 26; k++) { + dp[j][k] = Math.max(dp[j][k], dp[i][k] + (c === k ? 1 : 0)); + ans = Math.max(ans, dp[j][k]); + } + } + } + } + return cnt < n ? -1 : ans; +} +``` + diff --git a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md index 0aba7a5ebe9a4..aa11cbdf08694 100644 --- a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md +++ b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md @@ -70,7 +70,19 @@ tags: -### Solution 1 +### Solution 1: Topological Sort + Dynamic Programming + +Calculate the in-degree of each node and perform a topological sort. + +Define a 2D array $dp$, where $dp[i][j]$ represents the number of nodes with color $j$ on the path from the start node to node $i$. + +From node $i$, traverse all outgoing edges $i \to j$, and update $dp[j][k] = \max(dp[j][k], dp[i][k] + (c == k))$, where $c$ is the color of node $j$. + +The answer is the maximum value in the $dp$ array. + +If there is a cycle in the graph, it is impossible to visit all nodes, so return $-1$. + +The time complexity is $O((n + m) \times |\Sigma|)$, and the space complexity is $O(m + n \times |\Sigma|)$. Here, $|\Sigma|$ is the size of the alphabet (26 in this case), and $n$ and $m$ are the number of nodes and edges, respectively. @@ -248,6 +260,48 @@ func largestPathValue(colors string, edges [][]int) int { } ``` +#### TypeScript + +```ts +function largestPathValue(colors: string, edges: number[][]): number { + const n = colors.length; + const indeg = Array(n).fill(0); + const g: Map = new Map(); + for (const [a, b] of edges) { + if (!g.has(a)) g.set(a, []); + g.get(a)!.push(b); + indeg[b]++; + } + const q: number[] = []; + const dp: number[][] = Array.from({ length: n }, () => Array(26).fill(0)); + for (let i = 0; i < n; i++) { + if (indeg[i] === 0) { + q.push(i); + const c = colors.charCodeAt(i) - 97; + dp[i][c]++; + } + } + let cnt = 0; + let ans = 1; + while (q.length) { + const i = q.pop()!; + cnt++; + if (g.has(i)) { + for (const j of g.get(i)!) { + indeg[j]--; + if (indeg[j] === 0) q.push(j); + const c = colors.charCodeAt(j) - 97; + for (let k = 0; k < 26; k++) { + dp[j][k] = Math.max(dp[j][k], dp[i][k] + (c === k ? 1 : 0)); + ans = Math.max(ans, dp[j][k]); + } + } + } + } + return cnt < n ? -1 : ans; +} +``` + diff --git a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/Solution.ts b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/Solution.ts new file mode 100644 index 0000000000000..510a1a7de751d --- /dev/null +++ b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/Solution.ts @@ -0,0 +1,37 @@ +function largestPathValue(colors: string, edges: number[][]): number { + const n = colors.length; + const indeg = Array(n).fill(0); + const g: Map = new Map(); + for (const [a, b] of edges) { + if (!g.has(a)) g.set(a, []); + g.get(a)!.push(b); + indeg[b]++; + } + const q: number[] = []; + const dp: number[][] = Array.from({ length: n }, () => Array(26).fill(0)); + for (let i = 0; i < n; i++) { + if (indeg[i] === 0) { + q.push(i); + const c = colors.charCodeAt(i) - 97; + dp[i][c]++; + } + } + let cnt = 0; + let ans = 1; + while (q.length) { + const i = q.pop()!; + cnt++; + if (g.has(i)) { + for (const j of g.get(i)!) { + indeg[j]--; + if (indeg[j] === 0) q.push(j); + const c = colors.charCodeAt(j) - 97; + for (let k = 0; k < 26; k++) { + dp[j][k] = Math.max(dp[j][k], dp[i][k] + (c === k ? 1 : 0)); + ans = Math.max(ans, dp[j][k]); + } + } + } + } + return cnt < n ? -1 : ans; +} diff --git a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md index 80dc383ff6383..ac3ed046196a6 100644 --- a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md +++ b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md @@ -273,6 +273,52 @@ class FindSumPairs { */ ``` +#### Rust + +```rust +use std::collections::HashMap; + +struct FindSumPairs { + nums1: Vec , + nums2: Vec , + cnt: HashMap , +} + +impl FindSumPairs { + fn new(nums1: Vec , nums2: Vec ) -> Self { + let mut cnt = HashMap::new(); + for &x in &nums2 { + *cnt.entry(x).or_insert(0) += 1; + } + Self { nums1, nums2, cnt } + } + + fn add(&mut self, index: i32, val: i32) { + let i = index as usize; + let old_val = self.nums2[i]; + *self.cnt.entry(old_val).or_insert(0) -= 1; + if self.cnt[&old_val] == 0 { + self.cnt.remove(&old_val); + } + + self.nums2[i] += val; + let new_val = self.nums2[i]; + *self.cnt.entry(new_val).or_insert(0) += 1; + } + + fn count(&self, tot: i32) -> i32 { + let mut ans = 0; + for &x in &self.nums1 { + let target = tot - x; + if let Some(&c) = self.cnt.get(&target) { + ans += c; + } + } + ans + } +} +``` + #### JavaScript ```js diff --git a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md index 37f4847d8a54f..d232604af2812 100644 --- a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md +++ b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md @@ -271,6 +271,52 @@ class FindSumPairs { */ ``` +#### Rust + +```rust +use std::collections::HashMap; + +struct FindSumPairs { + nums1: Vec , + nums2: Vec , + cnt: HashMap , +} + +impl FindSumPairs { + fn new(nums1: Vec , nums2: Vec ) -> Self { + let mut cnt = HashMap::new(); + for &x in &nums2 { + *cnt.entry(x).or_insert(0) += 1; + } + Self { nums1, nums2, cnt } + } + + fn add(&mut self, index: i32, val: i32) { + let i = index as usize; + let old_val = self.nums2[i]; + *self.cnt.entry(old_val).or_insert(0) -= 1; + if self.cnt[&old_val] == 0 { + self.cnt.remove(&old_val); + } + + self.nums2[i] += val; + let new_val = self.nums2[i]; + *self.cnt.entry(new_val).or_insert(0) += 1; + } + + fn count(&self, tot: i32) -> i32 { + let mut ans = 0; + for &x in &self.nums1 { + let target = tot - x; + if let Some(&c) = self.cnt.get(&target) { + ans += c; + } + } + ans + } +} +``` + #### JavaScript ```js diff --git a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/Solution.rs b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/Solution.rs new file mode 100644 index 0000000000000..336e1c5147d81 --- /dev/null +++ b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/Solution.rs @@ -0,0 +1,41 @@ +use std::collections::HashMap; + +struct FindSumPairs { + nums1: Vec , + nums2: Vec , + cnt: HashMap , +} + +impl FindSumPairs { + fn new(nums1: Vec , nums2: Vec ) -> Self { + let mut cnt = HashMap::new(); + for &x in &nums2 { + *cnt.entry(x).or_insert(0) += 1; + } + Self { nums1, nums2, cnt } + } + + fn add(&mut self, index: i32, val: i32) { + let i = index as usize; + let old_val = self.nums2[i]; + *self.cnt.entry(old_val).or_insert(0) -= 1; + if self.cnt[&old_val] == 0 { + self.cnt.remove(&old_val); + } + + self.nums2[i] += val; + let new_val = self.nums2[i]; + *self.cnt.entry(new_val).or_insert(0) += 1; + } + + fn count(&self, tot: i32) -> i32 { + let mut ans = 0; + for &x in &self.nums1 { + let target = tot - x; + if let Some(&c) = self.cnt.get(&target) { + ans += c; + } + } + ans + } +} diff --git a/solution/1800-1899/1872.Stone Game VIII/README_EN.md b/solution/1800-1899/1872.Stone Game VIII/README_EN.md index fc84b32817c0f..db273764cb33b 100644 --- a/solution/1800-1899/1872.Stone Game VIII/README_EN.md +++ b/solution/1800-1899/1872.Stone Game VIII/README_EN.md @@ -27,9 +27,13 @@ tags: There are
n
stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:-
- Choose an integer
-x > 1
, and remove the leftmostx
stones from the row.- Add the sum of the removed stones' values to the player's score.
-- Place a new stone, whose value is equal to that sum, on the left side of the row.
+ +- Choose an integer
+ +x > 1
, and remove the leftmostx
stones from the row.- Add the sum of the removed stones' values to the player's score.
+ +- Place a new stone, whose value is equal to that sum, on the left side of the row.
+The game stops when only one stone is left in the row.
@@ -39,48 +43,77 @@ tags:Given an integer array
stones
of lengthn
wherestones[i]
represents the value of theith
stone from the left, return the score difference between Alice and Bob if they both play optimally.+
Example 1:
+ Input: stones = [-1,2,-3,4,-5] + Output: 5 + Explanation: + - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of + value 2 on the left. stones = [2,-5]. + - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on + the left. stones = [-3]. + The difference between their scores is 2 - (-3) = 5. +Example 2:
+ Input: stones = [7,-6,5,10,5,-2,-6] + Output: 13 + Explanation: + - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a + stone of value 13 on the left. stones = [13]. + The difference between their scores is 13 - 0 = 13. +Example 3:
+ Input: stones = [-10,-12] + Output: -22 + Explanation: + - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her + score and places a stone of value -22 on the left. stones = [-22]. + The difference between their scores is (-22) - 0 = -22. ++
Constraints:
-
diff --git a/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md b/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md index a072d1144acd3..f4db46805a1ca 100644 --- a/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md +++ b/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md @@ -21,35 +21,51 @@ tags:- -
n == stones.length
- -
2 <= n <= 105
- + +
-104 <= stones[i] <= 104
- + +
n == stones.length
- + +
2 <= n <= 105
- +
-104 <= stones[i] <= 104
The product sum of two equal-length arrays
a
andb
is equal to the sum ofa[i] * b[i]
for all0 <= i < a.length
(0-indexed).-
- For example, if
+ +a = [1,2,3,4]
andb = [5,2,3,1]
, the product sum would be1*5 + 2*2 + 3*3 + 4*1 = 22
.- For example, if
+a = [1,2,3,4]
andb = [5,2,3,1]
, the product sum would be1*5 + 2*2 + 3*3 + 4*1 = 22
.Given two arrays
nums1
andnums2
of lengthn
, return the minimum product sum if you are allowed to rearrange the order of the elements innums1
.+
Example 1:
+ Input: nums1 = [5,3,4,2], nums2 = [4,2,2,5] + Output: 40 + Explanation: We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40. +Example 2:
+ Input: nums1 = [2,1,4,5,7], nums2 = [3,2,4,8,6] + Output: 65 + Explanation: We can rearrange nums1 to become [5,7,4,1,2]. The product sum of [5,7,4,1,2] and [3,2,4,8,6] is 5*3 + 7*2 + 4*4 + 1*8 + 2*6 = 65. ++
Constraints:
-
diff --git a/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md b/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md index 929c483956728..4e50827246f87 100644 --- a/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md +++ b/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md @@ -24,45 +24,67 @@ tags:- -
n == nums1.length == nums2.length
- -
1 <= n <= 105
- + +
1 <= nums1[i], nums2[i] <= 100
- + +
n == nums1.length == nums2.length
- + +
1 <= n <= 105
- +
1 <= nums1[i], nums2[i] <= 100
The pair sum of a pair
(a,b)
is equal toa + b
. The maximum pair sum is the largest pair sum in a list of pairs.-
- For example, if we have pairs
+ +(1,5)
,(2,3)
, and(4,4)
, the maximum pair sum would bemax(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.- For example, if we have pairs
+(1,5)
,(2,3)
, and(4,4)
, the maximum pair sum would bemax(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.Given an array
nums
of even lengthn
, pair up the elements ofnums
inton / 2
pairs such that:-
- Each element of
-nums
is in exactly one pair, and- The maximum pair sum is minimized.
+ +- Each element of
+ +nums
is in exactly one pair, and- The maximum pair sum is minimized.
+Return the minimized maximum pair sum after optimally pairing up the elements.
+
Example 1:
+ Input: nums = [3,5,2,3] + Output: 7 + Explanation: The elements can be paired up into pairs (3,3) and (5,2). + The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. +Example 2:
+ Input: nums = [3,5,4,2,4,6] + Output: 8 + Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). + The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. ++
Constraints:
-
diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md index c73838c80a6a1..c7b158ba3e198 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md @@ -5,7 +5,6 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1800-1899/1888.Mi rating: 2005 source: 第 244 场周赛 Q3 tags: - - 贪心 - 字符串 - 动态规划 - 滑动窗口 diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md index 109f3d859b16b..01a894432fd6a 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md @@ -5,7 +5,6 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1800-1899/1888.Mi rating: 2005 source: Weekly Contest 244 Q3 tags: - - Greedy - String - Dynamic Programming - Sliding Window diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md index ecc7532e55269..76cda62341188 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md @@ -22,47 +22,67 @@ tags:- -
n == nums.length
- -
2 <= n <= 105
- -
n
is even.- + +
1 <= nums[i] <= 105
- + +
n == nums.length
- + +
2 <= n <= 105
- + +
n
is even.- +
1 <= nums[i] <= 105
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
-
- For example, the alternating sum of
+ +[4,2,5,3]
is(4 + 5) - (2 + 3) = 4
.- For example, the alternating sum of
+[4,2,5,3]
is(4 + 5) - (2 + 3) = 4
.Given an array
nums
, return the maximum alternating sum of any subsequence ofnums
(after reindexing the elements of the subsequence).+
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example,
[2,7,4]
is a subsequence of[4,2,3,7,2,1,4]
(the underlined elements), while[2,4,2]
is not.+
Example 1:
+ Input: nums = [4,2,5,3] + Output: 7 + Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. +Example 2:
+ Input: nums = [5,6,7,8] + Output: 8 + Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. +Example 3:
+ Input: nums = [6,2,1,2,4,5] + Output: 10 + Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10. ++
Constraints:
-
diff --git a/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md b/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md index de2987a86b5c6..806f7cb640d4f 100644 --- a/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md +++ b/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md @@ -22,7 +22,9 @@ tags:- -
1 <= nums.length <= 105
- + +
1 <= nums[i] <= 105
- + +
1 <= nums.length <= 105
- +
1 <= nums[i] <= 105
The product difference between two pairs
(a, b)
and(c, d)
is defined as(a * b) - (c * d)
.-
- For example, the product difference between
+ +(5, 6)
and(2, 7)
is(5 * 6) - (2 * 7) = 16
.- For example, the product difference between
+(5, 6)
and(2, 7)
is(5 * 6) - (2 * 7) = 16
.Given an integer array
@@ -30,30 +32,45 @@ tags:nums
, choose four distinct indicesw
,x
,y
, andz
such that the product difference between pairs(nums[w], nums[x])
and(nums[y], nums[z])
is maximized.Return the maximum such product difference.
+
Example 1:
+ Input: nums = [5,6,2,7,4] + Output: 34 + Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). + The product difference is (6 * 7) - (2 * 4) = 34. +Example 2:
+ Input: nums = [4,2,5,9,7,4,8] + Output: 64 + Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). + The product difference is (9 * 8) - (2 * 4) = 64. ++
Constraints:
-
diff --git a/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md b/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md index fae78135d2d47..2b5a5d14a34c7 100644 --- a/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md +++ b/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md @@ -27,37 +27,59 @@ tags:- -
4 <= nums.length <= 104
- + +
1 <= nums[i] <= 104
- + +
4 <= nums.length <= 104
- +
1 <= nums[i] <= 104
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
++
Return the matrix after applying
k
cyclic rotations to it.+
Example 1:
++
+ Input: grid = [[40,10],[30,20]], k = 1 + Output: [[10,20],[40,30]] + Explanation: The figures above represent the grid at every state. +Example 2:
+![]()
![]()
+ Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2 + Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]] + Explanation: The figures above represent the grid at every state. ++
Constraints:
-
diff --git a/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md b/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md index 1db1ec7914388..e6048268f5cc4 100644 --- a/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md +++ b/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md @@ -24,7 +24,9 @@ tags:- -
m == grid.length
- -
n == grid[i].length
- -
2 <= m, n <= 50
- Both
-m
andn
are even integers.- -
1 <= grid[i][j] <= 5000
- + +
1 <= k <= 109
- + +
m == grid.length
- + +
n == grid[i].length
- + +
2 <= m, n <= 50
- Both
+ +m
andn
are even integers.- + +
1 <= grid[i][j] <= 5000
- +
1 <= k <= 109
A wonderful string is a string where at most one letter appears an odd number of times.
-
- For example,
+ +"ccjjc"
and"abab"
are wonderful, but"ab"
is not.- For example,
+"ccjjc"
and"abab"
are wonderful, but"ab"
is not.Given a string
@@ -32,51 +34,83 @@ tags:word
that consists of the first ten lowercase English letters ('a'
through'j'
), return the number of wonderful non-empty substrings inword
. If the same substring appears multiple times inword
, then count each occurrence separately.A substring is a contiguous sequence of characters in a string.
+
Example 1:
+ Input: word = "aba" + Output: 4 + Explanation: The four wonderful substrings are underlined below: + - "aba" -> "a" + - "aba" -> "b" + - "aba" -> "a" + - "aba" -> "aba" +Example 2:
+ Input: word = "aabb" + Output: 9 + Explanation: The nine wonderful substrings are underlined below: + - "aabb" -> "a" + - "aabb" -> "aa" + - "aabb" -> "aab" + - "aabb" -> "aabb" + - "aabb" -> "a" + - "aabb" -> "abb" + - "aabb" -> "b" + - "aabb" -> "bb" + - "aabb" -> "b" +Example 3:
+ Input: word = "he" + Output: 2 + Explanation: The two wonderful substrings are underlined below: + - "he" -> "h" + - "he" -> "e" ++
Constraints:
-
diff --git a/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md b/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md index 08e8d9fb13bfc..f306ec994eb05 100644 --- a/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md +++ b/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md @@ -30,39 +30,65 @@ tags:- -
1 <= word.length <= 105
- + +
word
consists of lowercase English letters from'a'
to'j'
.- + +
1 <= word.length <= 105
- +
word
consists of lowercase English letters from'a'
to'j'
.Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo
109 + 7
.+
Example 1:
++
+ Input: prevRoom = [-1,0,1] + Output: 1 + Explanation: There is only one way to build the additional rooms: 0 → 1 → 2 +Example 2:
+
+ Input: prevRoom = [-1,0,0,1,2] + Output: 6 + Explanation: + The 6 ways are: + 0 → 1 → 3 → 2 → 4 + 0 → 2 → 4 → 1 → 3 + 0 → 1 → 2 → 3 → 4 + 0 → 1 → 2 → 4 → 3 + 0 → 2 → 1 → 3 → 4 + 0 → 2 → 1 → 4 → 3 ++
Constraints:
-
diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md index df6292514f73a..de6ec8f6b68bf 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md @@ -23,14 +23,14 @@ tags:- -
n == prevRoom.length
- -
2 <= n <= 105
- -
prevRoom[0] == -1
- -
0 <= prevRoom[i] < n
for all1 <= i < n
- Every room is reachable from room
+ +0
once all the rooms are built.- + +
n == prevRoom.length
- + +
2 <= n <= 105
- + +
prevRoom[0] == -1
- + +
0 <= prevRoom[i] < n
for all1 <= i < n
- Every room is reachable from room
+0
once all the rooms are built.给你一个整数数组
piles
,数组 下标从 0 开始 ,其中piles[i]
表示第i
堆石子中的石子数量。另给你一个整数k
,请你执行下述操作 恰好k
次:-
- 选出任一石子堆
+piles[i]
,并从中 移除floor(piles[i] / 2)
颗石子。- 选出任一石子堆
piles[i]
,并从中 移除ceil(piles[i] / 2)
颗石子。注意:你可以对 同一堆 石子多次执行此操作。
返回执行
-k
次操作后,剩下石子的 最小 总数。+
floor(x)
为 小于 或 等于x
的 最大 整数。(即,对x
向下取整)。
ceil(x)
为 大于 或 等于x
的 最小 整数。(即,对x
向上取整)。diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md index 3bec84a9ba286..cc0e8df44b0fe 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md @@ -23,14 +23,14 @@ tags:
You are given a 0-indexed integer array
piles
, wherepiles[i]
represents the number of stones in theith
pile, and an integerk
. You should apply the following operation exactlyk
times:-
- Choose any
+piles[i]
and removefloor(piles[i] / 2)
stones from it.- Choose any
piles[i]
and removeceil(piles[i] / 2)
stones from it.Notice that you can apply the operation on the same pile more than once.
Return the minimum possible total number of stones remaining after applying the
-k
operations.+
floor(x)
is the greatest integer that is smaller than or equal tox
(i.e., roundsx
down).
ceil(x)
is the smallest integer that is greater than or equal tox
(i.e., roundsx
up).
Example 1:
diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md index c8fc041d37caf..b0f9dae5ce44a 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md @@ -178,6 +178,39 @@ func minOperations(nums []int) int { } ``` +#### TypeScript + +```ts +function minOperations(nums: number[]): number { + const n = nums.length; + nums.sort((a, b) => a - b); + let m = 1; + for (let i = 1; i < n; ++i) { + if (nums[i] !== nums[i - 1]) { + nums[m++] = nums[i]; + } + } + let ans = n; + for (let i = 0; i < m; ++i) { + const j = search(nums, nums[i] + n - 1, i, m); + ans = Math.min(ans, n - (j - i)); + } + return ans; +} + +function search(nums: number[], x: number, left: number, right: number): number { + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} +``` + #### Rust ```rust @@ -310,6 +343,60 @@ func minOperations(nums []int) int { } ``` +#### TypeScript + +```ts +function minOperations(nums: number[]): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let m = 1; + for (let i = 1; i < n; i++) { + if (nums[i] !== nums[i - 1]) { + nums[m] = nums[i]; + m++; + } + } + let ans = n; + for (let i = 0, j = 0; i < m; i++) { + while (j < m && nums[j] - nums[i] <= n - 1) { + j++; + } + ans = Math.min(ans, n - (j - i)); + } + return ans; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn min_operations(mut nums: Vec) -> i32 { + nums.sort(); + let n = nums.len(); + if n == 0 { + return 0; + } + let mut m = 1usize; + for i in 1..n { + if nums[i] != nums[i - 1] { + nums[m] = nums[i]; + m += 1; + } + } + let mut ans = n as i32; + let mut j = 0usize; + for i in 0..m { + while j < m && nums[j] - nums[i] <= n as i32 - 1 { + j += 1; + } + ans = ans.min(n as i32 - (j as i32 - i as i32)); + } + ans + } +} +``` + diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md index 788d6ea6ba7e6..f5664b07a7068 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md @@ -179,6 +179,39 @@ func minOperations(nums []int) int { } ``` +#### TypeScript + +```ts +function minOperations(nums: number[]): number { + const n = nums.length; + nums.sort((a, b) => a - b); + let m = 1; + for (let i = 1; i < n; ++i) { + if (nums[i] !== nums[i - 1]) { + nums[m++] = nums[i]; + } + } + let ans = n; + for (let i = 0; i < m; ++i) { + const j = search(nums, nums[i] + n - 1, i, m); + ans = Math.min(ans, n - (j - i)); + } + return ans; +} + +function search(nums: number[], x: number, left: number, right: number): number { + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} +``` + #### Rust ```rust @@ -311,6 +344,60 @@ func minOperations(nums []int) int { } ``` +#### TypeScript + +```ts +function minOperations(nums: number[]): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let m = 1; + for (let i = 1; i < n; i++) { + if (nums[i] !== nums[i - 1]) { + nums[m] = nums[i]; + m++; + } + } + let ans = n; + for (let i = 0, j = 0; i < m; i++) { + while (j < m && nums[j] - nums[i] <= n - 1) { + j++; + } + ans = Math.min(ans, n - (j - i)); + } + return ans; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn min_operations(mut nums: Vec ) -> i32 { + nums.sort(); + let n = nums.len(); + if n == 0 { + return 0; + } + let mut m = 1usize; + for i in 1..n { + if nums[i] != nums[i - 1] { + nums[m] = nums[i]; + m += 1; + } + } + let mut ans = n as i32; + let mut j = 0usize; + for i in 0..m { + while j < m && nums[j] - nums[i] <= n as i32 - 1 { + j += 1; + } + ans = ans.min(n as i32 - (j as i32 - i as i32)); + } + ans + } +} +``` + diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.ts b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.ts new file mode 100644 index 0000000000000..0829466ba3075 --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution.ts @@ -0,0 +1,28 @@ +function minOperations(nums: number[]): number { + const n = nums.length; + nums.sort((a, b) => a - b); + let m = 1; + for (let i = 1; i < n; ++i) { + if (nums[i] !== nums[i - 1]) { + nums[m++] = nums[i]; + } + } + let ans = n; + for (let i = 0; i < m; ++i) { + const j = search(nums, nums[i] + n - 1, i, m); + ans = Math.min(ans, n - (j - i)); + } + return ans; +} + +function search(nums: number[], x: number, left: number, right: number): number { + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.rs b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.rs new file mode 100644 index 0000000000000..78a3c9db5b4b5 --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn min_operations(mut nums: Vec ) -> i32 { + nums.sort(); + let n = nums.len(); + if n == 0 { + return 0; + } + let mut m = 1usize; + for i in 1..n { + if nums[i] != nums[i - 1] { + nums[m] = nums[i]; + m += 1; + } + } + let mut ans = n as i32; + let mut j = 0usize; + for i in 0..m { + while j < m && nums[j] - nums[i] <= n as i32 - 1 { + j += 1; + } + ans = ans.min(n as i32 - (j as i32 - i as i32)); + } + ans + } +} diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.ts b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.ts new file mode 100644 index 0000000000000..0e37720e6bebf --- /dev/null +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.ts @@ -0,0 +1,19 @@ +function minOperations(nums: number[]): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let m = 1; + for (let i = 1; i < n; i++) { + if (nums[i] !== nums[i - 1]) { + nums[m] = nums[i]; + m++; + } + } + let ans = n; + for (let i = 0, j = 0; i < m; i++) { + while (j < m && nums[j] - nums[i] <= n - 1) { + j++; + } + ans = Math.min(ans, n - (j - i)); + } + return ans; +} diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md index 971cc3b505454..d81ae7e9f1c02 100644 --- a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md @@ -70,7 +70,7 @@ tags: @@ -80,32 +80,250 @@ tags: -### 方法一 +### 方法一:BFS + +我们可以先统计字符串中每个字符出现的次数,然后将出现次数大于等于 $k$ 的字符按从小到大的顺序存入一个列表 $\textit{cs}$ 中。接下来,我们可以使用 BFS 来枚举所有可能的子序列。 + +我们定义一个队列 $\textit{q}$,初始时将空字符串放入队列中。然后,我们从队列中取出一个字符串 $\textit{cur}$,并尝试将每个字符 $c \in \textit{cs}$ 添加到 $\textit{cur}$ 的末尾,形成一个新的字符串 $\textit{nxt}$。如果 $\textit{nxt}$ 是一个重复 $k$ 次的子序列,我们就将其加入到答案中,并将 $\textit{nxt}$ 放入队列中继续处理。 + +我们需要一个辅助函数 $\textit{check(t, k)}$ 来判断字符串 $\textit{t}$ 是否是字符串 $s$ 的一个重复 $k$ 次的子序列。具体地,我们可以使用两个指针来遍历字符串 $s$ 和 $\textit{t}$,如果在遍历过程中能够找到 $\textit{t}$ 的所有字符,并且能够重复 $k$ 次,那么就返回 $\textit{true}$,否则返回 $\textit{false}$。 #### Python3 ```python - +class Solution: + def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: + def check(t: str, k: int) -> bool: + i = 0 + for c in s: + if c == t[i]: + i += 1 + if i == len(t): + k -= 1 + if k == 0: + return True + i = 0 + return False + + cnt = Counter(s) + cs = [c for c in ascii_lowercase if cnt[c] >= k] + q = deque([""]) + ans = "" + while q: + cur = q.popleft() + for c in cs: + nxt = cur + c + if check(nxt, k): + ans = nxt + q.append(nxt) + return ans ``` #### Java ```java - +class Solution { + private char[] s; + + public String longestSubsequenceRepeatedK(String s, int k) { + this.s = s.toCharArray(); + int[] cnt = new int[26]; + for (char c : this.s) { + cnt[c - 'a']++; + } + + List
n == s.length
- -
2 <= k <= 2000
- +
2 <= n < k * 8
2 <= n < min(2001, k * 8)
s
由小写英文字母组成cs = new ArrayList<>(); + for (char c = 'a'; c <= 'z'; ++c) { + if (cnt[c - 'a'] >= k) { + cs.add(c); + } + } + Deque q = new ArrayDeque<>(); + q.offer(""); + String ans = ""; + while (!q.isEmpty()) { + String cur = q.poll(); + for (char c : cs) { + String nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.offer(nxt); + } + } + } + return ans; + } + + private boolean check(String t, int k) { + int i = 0; + for (char c : s) { + if (c == t.charAt(i)) { + i++; + if (i == t.length()) { + if (--k == 0) { + return true; + } + i = 0; + } + } + } + return false; + } +} ``` #### C++ ```cpp - +class Solution { +public: + string longestSubsequenceRepeatedK(string s, int k) { + auto check = [&](const string& t, int k) -> bool { + int i = 0; + for (char c : s) { + if (c == t[i]) { + i++; + if (i == t.size()) { + if (--k == 0) { + return true; + } + i = 0; + } + } + } + return false; + }; + int cnt[26] = {}; + for (char c : s) { + cnt[c - 'a']++; + } + + vector cs; + for (char c = 'a'; c <= 'z'; ++c) { + if (cnt[c - 'a'] >= k) { + cs.push_back(c); + } + } + + queue q; + q.push(""); + string ans; + while (!q.empty()) { + string cur = q.front(); + q.pop(); + for (char c : cs) { + string nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.push(nxt); + } + } + } + return ans; + } +}; ``` #### Go ```go +func longestSubsequenceRepeatedK(s string, k int) string { + check := func(t string, k int) bool { + i := 0 + for _, c := range s { + if byte(c) == t[i] { + i++ + if i == len(t) { + k-- + if k == 0 { + return true + } + i = 0 + } + } + } + return false + } + + cnt := [26]int{} + for i := 0; i < len(s); i++ { + cnt[s[i]-'a']++ + } + + cs := []byte{} + for c := byte('a'); c <= 'z'; c++ { + if cnt[c-'a'] >= k { + cs = append(cs, c) + } + } + + q := []string{""} + ans := "" + for len(q) > 0 { + cur := q[0] + q = q[1:] + for _, c := range cs { + nxt := cur + string(c) + if check(nxt, k) { + ans = nxt + q = append(q, nxt) + } + } + } + return ans +} +``` +#### TypeScript + +```ts +function longestSubsequenceRepeatedK(s: string, k: number): string { + const check = (t: string, k: number): boolean => { + let i = 0; + for (const c of s) { + if (c === t[i]) { + i++; + if (i === t.length) { + k--; + if (k === 0) { + return true; + } + i = 0; + } + } + } + return false; + }; + + const cnt = new Array(26).fill(0); + for (const c of s) { + cnt[c.charCodeAt(0) - 97]++; + } + + const cs: string[] = []; + for (let i = 0; i < 26; ++i) { + if (cnt[i] >= k) { + cs.push(String.fromCharCode(97 + i)); + } + } + + const q: string[] = ['']; + let ans = ''; + while (q.length > 0) { + const cur = q.shift()!; + for (const c of cs) { + const nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.push(nxt); + } + } + } + + return ans; +} ``` diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md index 31b8034b543c5..d7fd6b3fa7708 100644 --- a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md @@ -65,8 +65,8 @@ tags: @@ -76,32 +76,250 @@ tags: -### Solution 1 +### Solution 1: BFS + +We can first count the occurrences of each character in the string, and then store the characters that appear at least $k$ times in a list $\textit{cs}$ in ascending order. Next, we can use BFS to enumerate all possible subsequences. + +We define a queue $\textit{q}$, initially putting the empty string into the queue. Then, we take out a string $\textit{cur}$ from the queue and try to append each character $c \in \textit{cs}$ to the end of $\textit{cur}$ to form a new string $\textit{nxt}$. If $\textit{nxt}$ is a subsequence that can be repeated $k$ times, we add it to the answer and put $\textit{nxt}$ back into the queue for further processing. + +We need an auxiliary function $\textit{check(t, k)}$ to determine whether the string $\textit{t}$ is a repeated $k$ times subsequence of string $s$. Specifically, we can use two pointers to traverse $s$ and $\textit{t}$. If we can find all characters of $\textit{t}$ in $s$ and repeat this process $k$ times, then return $\textit{true}$; otherwise, return $\textit{false}$. #### Python3 ```python - +class Solution: + def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: + def check(t: str, k: int) -> bool: + i = 0 + for c in s: + if c == t[i]: + i += 1 + if i == len(t): + k -= 1 + if k == 0: + return True + i = 0 + return False + + cnt = Counter(s) + cs = [c for c in ascii_lowercase if cnt[c] >= k] + q = deque([""]) + ans = "" + while q: + cur = q.popleft() + for c in cs: + nxt = cur + c + if check(nxt, k): + ans = nxt + q.append(nxt) + return ans ``` #### Java ```java - +class Solution { + private char[] s; + + public String longestSubsequenceRepeatedK(String s, int k) { + this.s = s.toCharArray(); + int[] cnt = new int[26]; + for (char c : this.s) { + cnt[c - 'a']++; + } + + List
- -
n == s.length
- -
2 <= n, k <= 2000
- +
2 <= n < k * 8
- +
2 <= k <= 2000
2 <= n < min(2001, k * 8)
s
consists of lowercase English letters.cs = new ArrayList<>(); + for (char c = 'a'; c <= 'z'; ++c) { + if (cnt[c - 'a'] >= k) { + cs.add(c); + } + } + Deque q = new ArrayDeque<>(); + q.offer(""); + String ans = ""; + while (!q.isEmpty()) { + String cur = q.poll(); + for (char c : cs) { + String nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.offer(nxt); + } + } + } + return ans; + } + + private boolean check(String t, int k) { + int i = 0; + for (char c : s) { + if (c == t.charAt(i)) { + i++; + if (i == t.length()) { + if (--k == 0) { + return true; + } + i = 0; + } + } + } + return false; + } +} ``` #### C++ ```cpp - +class Solution { +public: + string longestSubsequenceRepeatedK(string s, int k) { + auto check = [&](const string& t, int k) -> bool { + int i = 0; + for (char c : s) { + if (c == t[i]) { + i++; + if (i == t.size()) { + if (--k == 0) { + return true; + } + i = 0; + } + } + } + return false; + }; + int cnt[26] = {}; + for (char c : s) { + cnt[c - 'a']++; + } + + vector cs; + for (char c = 'a'; c <= 'z'; ++c) { + if (cnt[c - 'a'] >= k) { + cs.push_back(c); + } + } + + queue q; + q.push(""); + string ans; + while (!q.empty()) { + string cur = q.front(); + q.pop(); + for (char c : cs) { + string nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.push(nxt); + } + } + } + return ans; + } +}; ``` #### Go ```go +func longestSubsequenceRepeatedK(s string, k int) string { + check := func(t string, k int) bool { + i := 0 + for _, c := range s { + if byte(c) == t[i] { + i++ + if i == len(t) { + k-- + if k == 0 { + return true + } + i = 0 + } + } + } + return false + } + + cnt := [26]int{} + for i := 0; i < len(s); i++ { + cnt[s[i]-'a']++ + } + + cs := []byte{} + for c := byte('a'); c <= 'z'; c++ { + if cnt[c-'a'] >= k { + cs = append(cs, c) + } + } + + q := []string{""} + ans := "" + for len(q) > 0 { + cur := q[0] + q = q[1:] + for _, c := range cs { + nxt := cur + string(c) + if check(nxt, k) { + ans = nxt + q = append(q, nxt) + } + } + } + return ans +} +``` +#### TypeScript + +```ts +function longestSubsequenceRepeatedK(s: string, k: number): string { + const check = (t: string, k: number): boolean => { + let i = 0; + for (const c of s) { + if (c === t[i]) { + i++; + if (i === t.length) { + k--; + if (k === 0) { + return true; + } + i = 0; + } + } + } + return false; + }; + + const cnt = new Array(26).fill(0); + for (const c of s) { + cnt[c.charCodeAt(0) - 97]++; + } + + const cs: string[] = []; + for (let i = 0; i < 26; ++i) { + if (cnt[i] >= k) { + cs.push(String.fromCharCode(97 + i)); + } + } + + const q: string[] = ['']; + let ans = ''; + while (q.length > 0) { + const cur = q.shift()!; + for (const c of cs) { + const nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.push(nxt); + } + } + } + + return ans; +} ``` diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.cpp b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.cpp new file mode 100644 index 0000000000000..8a7ad8569e9ca --- /dev/null +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + string longestSubsequenceRepeatedK(string s, int k) { + auto check = [&](const string& t, int k) -> bool { + int i = 0; + for (char c : s) { + if (c == t[i]) { + i++; + if (i == t.size()) { + if (--k == 0) { + return true; + } + i = 0; + } + } + } + return false; + }; + int cnt[26] = {}; + for (char c : s) { + cnt[c - 'a']++; + } + + vector cs; + for (char c = 'a'; c <= 'z'; ++c) { + if (cnt[c - 'a'] >= k) { + cs.push_back(c); + } + } + + queue q; + q.push(""); + string ans; + while (!q.empty()) { + string cur = q.front(); + q.pop(); + for (char c : cs) { + string nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.push(nxt); + } + } + } + return ans; + } +}; diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.go b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.go new file mode 100644 index 0000000000000..9aebe716c2c08 --- /dev/null +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.go @@ -0,0 +1,45 @@ +func longestSubsequenceRepeatedK(s string, k int) string { + check := func(t string, k int) bool { + i := 0 + for _, c := range s { + if byte(c) == t[i] { + i++ + if i == len(t) { + k-- + if k == 0 { + return true + } + i = 0 + } + } + } + return false + } + + cnt := [26]int{} + for i := 0; i < len(s); i++ { + cnt[s[i]-'a']++ + } + + cs := []byte{} + for c := byte('a'); c <= 'z'; c++ { + if cnt[c-'a'] >= k { + cs = append(cs, c) + } + } + + q := []string{""} + ans := "" + for len(q) > 0 { + cur := q[0] + q = q[1:] + for _, c := range cs { + nxt := cur + string(c) + if check(nxt, k) { + ans = nxt + q = append(q, nxt) + } + } + } + return ans +} diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.java b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.java new file mode 100644 index 0000000000000..11573eda7c6ee --- /dev/null +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.java @@ -0,0 +1,48 @@ +class Solution { + private char[] s; + + public String longestSubsequenceRepeatedK(String s, int k) { + this.s = s.toCharArray(); + int[] cnt = new int[26]; + for (char c : this.s) { + cnt[c - 'a']++; + } + + List cs = new ArrayList<>(); + for (char c = 'a'; c <= 'z'; ++c) { + if (cnt[c - 'a'] >= k) { + cs.add(c); + } + } + Deque q = new ArrayDeque<>(); + q.offer(""); + String ans = ""; + while (!q.isEmpty()) { + String cur = q.poll(); + for (char c : cs) { + String nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.offer(nxt); + } + } + } + return ans; + } + + private boolean check(String t, int k) { + int i = 0; + for (char c : s) { + if (c == t.charAt(i)) { + i++; + if (i == t.length()) { + if (--k == 0) { + return true; + } + i = 0; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.py b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.py new file mode 100644 index 0000000000000..fdb26b136fcb3 --- /dev/null +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.py @@ -0,0 +1,26 @@ +class Solution: + def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: + def check(t: str, k: int) -> bool: + i = 0 + for c in s: + if c == t[i]: + i += 1 + if i == len(t): + k -= 1 + if k == 0: + return True + i = 0 + return False + + cnt = Counter(s) + cs = [c for c in ascii_lowercase if cnt[c] >= k] + q = deque([""]) + ans = "" + while q: + cur = q.popleft() + for c in cs: + nxt = cur + c + if check(nxt, k): + ans = nxt + q.append(nxt) + return ans diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.ts b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.ts new file mode 100644 index 0000000000000..1c93ee58da115 --- /dev/null +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.ts @@ -0,0 +1,45 @@ +function longestSubsequenceRepeatedK(s: string, k: number): string { + const check = (t: string, k: number): boolean => { + let i = 0; + for (const c of s) { + if (c === t[i]) { + i++; + if (i === t.length) { + k--; + if (k === 0) { + return true; + } + i = 0; + } + } + } + return false; + }; + + const cnt = new Array(26).fill(0); + for (const c of s) { + cnt[c.charCodeAt(0) - 97]++; + } + + const cs: string[] = []; + for (let i = 0; i < 26; ++i) { + if (cnt[i] >= k) { + cs.push(String.fromCharCode(97 + i)); + } + } + + const q: string[] = ['']; + let ans = ''; + while (q.length > 0) { + const cur = q.shift()!; + for (const c of cs) { + const nxt = cur + c; + if (check(nxt, k)) { + ans = nxt; + q.push(nxt); + } + } + } + + return ans; +} diff --git a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md index 689849e6061c0..cddb788d2dafe 100644 --- a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md +++ b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md @@ -293,6 +293,128 @@ func abs(x int) int { } ``` +#### TypeScript + +```ts +function kthSmallestProduct(nums1: number[], nums2: number[], k: number): number { + const m = nums1.length; + const n = nums2.length; + + const a = BigInt(Math.max(Math.abs(nums1[0]), Math.abs(nums1[m - 1]))); + const b = BigInt(Math.max(Math.abs(nums2[0]), Math.abs(nums2[n - 1]))); + + let l = -a * b; + let r = a * b; + + const count = (p: bigint): bigint => { + let cnt = 0n; + for (const x of nums1) { + const bx = BigInt(x); + if (bx > 0n) { + let l = 0, + r = n; + while (l < r) { + const mid = (l + r) >> 1; + const prod = bx * BigInt(nums2[mid]); + if (prod > p) { + r = mid; + } else { + l = mid + 1; + } + } + cnt += BigInt(l); + } else if (bx < 0n) { + let l = 0, + r = n; + while (l < r) { + const mid = (l + r) >> 1; + const prod = bx * BigInt(nums2[mid]); + if (prod <= p) { + r = mid; + } else { + l = mid + 1; + } + } + cnt += BigInt(n - l); + } else if (p >= 0n) { + cnt += BigInt(n); + } + } + return cnt; + }; + + while (l < r) { + const mid = (l + r) >> 1n; + if (count(mid) >= BigInt(k)) { + r = mid; + } else { + l = mid + 1n; + } + } + + return Number(l); +} +``` + +#### Rust + +```rust +impl Solution { + pub fn kth_smallest_product(nums1: Vec , nums2: Vec , k: i64) -> i64 { + let m = nums1.len(); + let n = nums2.len(); + let a = nums1[0].abs().max(nums1[m - 1].abs()) as i64; + let b = nums2[0].abs().max(nums2[n - 1].abs()) as i64; + let mut l = -a * b; + let mut r = a * b; + + let count = |p: i64| -> i64 { + let mut cnt = 0i64; + for &x in &nums1 { + if x > 0 { + let mut left = 0; + let mut right = n; + while left < right { + let mid = (left + right) / 2; + if (x as i64) * (nums2[mid] as i64) > p { + right = mid; + } else { + left = mid + 1; + } + } + cnt += left as i64; + } else if x < 0 { + let mut left = 0; + let mut right = n; + while left < right { + let mid = (left + right) / 2; + if (x as i64) * (nums2[mid] as i64) <= p { + right = mid; + } else { + left = mid + 1; + } + } + cnt += (n - left) as i64; + } else if p >= 0 { + cnt += n as i64; + } + } + cnt + }; + + while l < r { + let mid = l + (r - l) / 2; + if count(mid) >= k { + r = mid; + } else { + l = mid + 1; + } + } + l + } +} +``` + diff --git a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md index 3f8742d1afed5..37e3102aa44e6 100644 --- a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md +++ b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md @@ -294,6 +294,128 @@ func abs(x int) int { } ``` +#### TypeScript + +```ts +function kthSmallestProduct(nums1: number[], nums2: number[], k: number): number { + const m = nums1.length; + const n = nums2.length; + + const a = BigInt(Math.max(Math.abs(nums1[0]), Math.abs(nums1[m - 1]))); + const b = BigInt(Math.max(Math.abs(nums2[0]), Math.abs(nums2[n - 1]))); + + let l = -a * b; + let r = a * b; + + const count = (p: bigint): bigint => { + let cnt = 0n; + for (const x of nums1) { + const bx = BigInt(x); + if (bx > 0n) { + let l = 0, + r = n; + while (l < r) { + const mid = (l + r) >> 1; + const prod = bx * BigInt(nums2[mid]); + if (prod > p) { + r = mid; + } else { + l = mid + 1; + } + } + cnt += BigInt(l); + } else if (bx < 0n) { + let l = 0, + r = n; + while (l < r) { + const mid = (l + r) >> 1; + const prod = bx * BigInt(nums2[mid]); + if (prod <= p) { + r = mid; + } else { + l = mid + 1; + } + } + cnt += BigInt(n - l); + } else if (p >= 0n) { + cnt += BigInt(n); + } + } + return cnt; + }; + + while (l < r) { + const mid = (l + r) >> 1n; + if (count(mid) >= BigInt(k)) { + r = mid; + } else { + l = mid + 1n; + } + } + + return Number(l); +} +``` + +#### Rust + +```rust +impl Solution { + pub fn kth_smallest_product(nums1: Vec , nums2: Vec , k: i64) -> i64 { + let m = nums1.len(); + let n = nums2.len(); + let a = nums1[0].abs().max(nums1[m - 1].abs()) as i64; + let b = nums2[0].abs().max(nums2[n - 1].abs()) as i64; + let mut l = -a * b; + let mut r = a * b; + + let count = |p: i64| -> i64 { + let mut cnt = 0i64; + for &x in &nums1 { + if x > 0 { + let mut left = 0; + let mut right = n; + while left < right { + let mid = (left + right) / 2; + if (x as i64) * (nums2[mid] as i64) > p { + right = mid; + } else { + left = mid + 1; + } + } + cnt += left as i64; + } else if x < 0 { + let mut left = 0; + let mut right = n; + while left < right { + let mid = (left + right) / 2; + if (x as i64) * (nums2[mid] as i64) <= p { + right = mid; + } else { + left = mid + 1; + } + } + cnt += (n - left) as i64; + } else if p >= 0 { + cnt += n as i64; + } + } + cnt + }; + + while l < r { + let mid = l + (r - l) / 2; + if count(mid) >= k { + r = mid; + } else { + l = mid + 1; + } + } + l + } +} +``` + diff --git a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.rs b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.rs new file mode 100644 index 0000000000000..0d312303d1ef8 --- /dev/null +++ b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.rs @@ -0,0 +1,54 @@ +impl Solution { + pub fn kth_smallest_product(nums1: Vec , nums2: Vec , k: i64) -> i64 { + let m = nums1.len(); + let n = nums2.len(); + let a = nums1[0].abs().max(nums1[m - 1].abs()) as i64; + let b = nums2[0].abs().max(nums2[n - 1].abs()) as i64; + let mut l = -a * b; + let mut r = a * b; + + let count = |p: i64| -> i64 { + let mut cnt = 0i64; + for &x in &nums1 { + if x > 0 { + let mut left = 0; + let mut right = n; + while left < right { + let mid = (left + right) / 2; + if (x as i64) * (nums2[mid] as i64) > p { + right = mid; + } else { + left = mid + 1; + } + } + cnt += left as i64; + } else if x < 0 { + let mut left = 0; + let mut right = n; + while left < right { + let mid = (left + right) / 2; + if (x as i64) * (nums2[mid] as i64) <= p { + right = mid; + } else { + left = mid + 1; + } + } + cnt += (n - left) as i64; + } else if p >= 0 { + cnt += n as i64; + } + } + cnt + }; + + while l < r { + let mid = l + (r - l) / 2; + if count(mid) >= k { + r = mid; + } else { + l = mid + 1; + } + } + l + } +} diff --git a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.ts b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.ts new file mode 100644 index 0000000000000..2c56305617880 --- /dev/null +++ b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.ts @@ -0,0 +1,58 @@ +function kthSmallestProduct(nums1: number[], nums2: number[], k: number): number { + const m = nums1.length; + const n = nums2.length; + + const a = BigInt(Math.max(Math.abs(nums1[0]), Math.abs(nums1[m - 1]))); + const b = BigInt(Math.max(Math.abs(nums2[0]), Math.abs(nums2[n - 1]))); + + let l = -a * b; + let r = a * b; + + const count = (p: bigint): bigint => { + let cnt = 0n; + for (const x of nums1) { + const bx = BigInt(x); + if (bx > 0n) { + let l = 0, + r = n; + while (l < r) { + const mid = (l + r) >> 1; + const prod = bx * BigInt(nums2[mid]); + if (prod > p) { + r = mid; + } else { + l = mid + 1; + } + } + cnt += BigInt(l); + } else if (bx < 0n) { + let l = 0, + r = n; + while (l < r) { + const mid = (l + r) >> 1; + const prod = bx * BigInt(nums2[mid]); + if (prod <= p) { + r = mid; + } else { + l = mid + 1; + } + } + cnt += BigInt(n - l); + } else if (p >= 0n) { + cnt += BigInt(n); + } + } + return cnt; + }; + + while (l < r) { + const mid = (l + r) >> 1n; + if (count(mid) >= BigInt(k)) { + r = mid; + } else { + l = mid + 1n; + } + } + + return Number(l); +} diff --git a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md index 76f800e3ea397..442978c9c6cdf 100644 --- a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md +++ b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md @@ -8,6 +8,7 @@ tags: - 贪心 - 队列 - 数组 + - 双指针 - 二分查找 - 排序 - 单调队列 @@ -296,6 +297,69 @@ func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int { } ``` +#### TypeScript + +```ts +function maxTaskAssign( + tasks: number[], + workers: number[], + pills: number, + strength: number, +): number { + tasks.sort((a, b) => a - b); + workers.sort((a, b) => a - b); + + const n = tasks.length; + const m = workers.length; + + const check = (x: number): boolean => { + const dq = new Array (x); + let head = 0; + let tail = 0; + const empty = () => head === tail; + const pushBack = (val: number) => { + dq[tail++] = val; + }; + const popFront = () => { + head++; + }; + const popBack = () => { + tail--; + }; + const front = () => dq[head]; + + let i = 0; + let p = pills; + + for (let j = m - x; j < m; j++) { + while (i < x && tasks[i] <= workers[j] + strength) { + pushBack(tasks[i]); + i++; + } + + if (empty()) return false; + + if (front() <= workers[j]) { + popFront(); + } else { + if (p === 0) return false; + p--; + popBack(); + } + } + return true; + }; + + let [left, right] = [0, Math.min(n, m)]; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (check(mid)) left = mid; + else right = mid - 1; + } + return left; +} +``` + diff --git a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md index 390eb0fc9ef37..bb51ca6eb9c3a 100644 --- a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md +++ b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md @@ -8,6 +8,7 @@ tags: - Greedy - Queue - Array + - Two Pointers - Binary Search - Sorting - Monotonic Queue @@ -84,7 +85,21 @@ The last pill is not given because it will not make any worker strong enough for -### Solution 1 +### Solution 1: Greedy + Binary Search + +Sort the tasks in ascending order of completion time and the workers in ascending order of ability. + +Suppose the number of tasks we want to assign is $x$. We can greedily assign the first $x$ tasks to the $x$ workers with the highest strength. If it is possible to complete $x$ tasks, then it is also possible to complete $x-1$, $x-2$, $x-3$, ..., $1$, $0$ tasks. Therefore, we can use binary search to find the maximum $x$ such that it is possible to complete $x$ tasks. + +We define a function $check(x)$ to determine whether it is possible to complete $x$ tasks. + +The implementation of $check(x)$ is as follows: + +Iterate through the $x$ workers with the highest strength in ascending order. Let the current worker being processed be $j$. The current available tasks must satisfy $tasks[i] \leq workers[j] + strength$. + +If the smallest required strength task $task[i]$ among the current available tasks is less than or equal to $workers[j]$, then worker $j$ can complete task $task[i]$ without using a pill. Otherwise, the current worker must use a pill. If there are pills remaining, use one pill and complete the task with the highest required strength among the current available tasks. Otherwise, return `false`. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$, where $n$ is the number of tasks. @@ -272,6 +287,69 @@ func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int { } ``` +#### TypeScript + +```ts +function maxTaskAssign( + tasks: number[], + workers: number[], + pills: number, + strength: number, +): number { + tasks.sort((a, b) => a - b); + workers.sort((a, b) => a - b); + + const n = tasks.length; + const m = workers.length; + + const check = (x: number): boolean => { + const dq = new Array (x); + let head = 0; + let tail = 0; + const empty = () => head === tail; + const pushBack = (val: number) => { + dq[tail++] = val; + }; + const popFront = () => { + head++; + }; + const popBack = () => { + tail--; + }; + const front = () => dq[head]; + + let i = 0; + let p = pills; + + for (let j = m - x; j < m; j++) { + while (i < x && tasks[i] <= workers[j] + strength) { + pushBack(tasks[i]); + i++; + } + + if (empty()) return false; + + if (front() <= workers[j]) { + popFront(); + } else { + if (p === 0) return false; + p--; + popBack(); + } + } + return true; + }; + + let [left, right] = [0, Math.min(n, m)]; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (check(mid)) left = mid; + else right = mid - 1; + } + return left; +} +``` + diff --git a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/Solution.ts b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/Solution.ts new file mode 100644 index 0000000000000..3c32ec160c94d --- /dev/null +++ b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/Solution.ts @@ -0,0 +1,58 @@ +function maxTaskAssign( + tasks: number[], + workers: number[], + pills: number, + strength: number, +): number { + tasks.sort((a, b) => a - b); + workers.sort((a, b) => a - b); + + const n = tasks.length; + const m = workers.length; + + const check = (x: number): boolean => { + const dq = new Array (x); + let head = 0; + let tail = 0; + const empty = () => head === tail; + const pushBack = (val: number) => { + dq[tail++] = val; + }; + const popFront = () => { + head++; + }; + const popBack = () => { + tail--; + }; + const front = () => dq[head]; + + let i = 0; + let p = pills; + + for (let j = m - x; j < m; j++) { + while (i < x && tasks[i] <= workers[j] + strength) { + pushBack(tasks[i]); + i++; + } + + if (empty()) return false; + + if (front() <= workers[j]) { + popFront(); + } else { + if (p === 0) return false; + p--; + popBack(); + } + } + return true; + }; + + let [left, right] = [0, Math.min(n, m)]; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (check(mid)) left = mid; + else right = mid - 1; + } + return left; +} diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md index 53bad43650637..224a410e3d6a1 100644 --- a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md @@ -85,26 +85,112 @@ tags: -### 方法一 +### 方法一:折半枚举 + 数学 + +对于一个 k 镜像数字,我们可以将其分为两部分:前半部分和后半部分。对于偶数长度的数字,前半部分和后半部分完全相同;对于奇数长度的数字,前半部分和后半部分相同,但中间的数字可以是任意数字。 + +我们可以通过枚举前半部分的数字,然后根据前半部分构造出完整的 k 镜像数字。具体步骤如下: + +1. **枚举长度**:从 1 开始枚举数字的长度,直到找到满足条件的 k 镜像数字。 +2. **计算前半部分的范围**:对于长度为 $l$ 的数字,前半部分的范围是 $[10^{(l-1)/2}, 10^{(l+1)/2})$。 +3. **构造 k 镜像数字**:对于每个前半部分的数字 $i$,如果长度为偶数,则直接将 $i$ 作为前半部分;如果长度为奇数,则将 $i$ 除以 10 得到前半部分。然后将前半部分的数字反转并添加到后半部分,构造出完整的 k 镜像数字。 +4. **检查 k 镜像数字**:将构造出的数字转换为 k 进制,检查其是否是回文数。 +5. **累加结果**:如果是 k 镜像数字,则将其累加到结果中,并减少计数器 $n$。当计数器 $n$ 减至 0 时,返回结果。 + +时间复杂度主要取决于枚举的长度和前半部分的范围。由于 $n$ 的最大值为 30,因此在实际操作中,枚举的次数是有限的。空间复杂度 $O(1)$,因为我们只使用了常数级别的额外空间。 +#### Python3 + +```python +class Solution: + def kMirror(self, k: int, n: int) -> int: + def check(x: int, k: int) -> bool: + s = [] + while x: + s.append(x % k) + x //= k + return s == s[::-1] + + ans = 0 + for l in count(1): + x = 10 ** ((l - 1) // 2) + y = 10 ** ((l + 1) // 2) + for i in range(x, y): + v = i + j = i if l % 2 == 0 else i // 10 + while j > 0: + v = v * 10 + j % 10 + j //= 10 + if check(v, k): + ans += v + n -= 1 + if n == 0: + return ans +``` + #### Java ```java class Solution { public long kMirror(int k, int n) { long ans = 0; - for (int l = 1;; ++l) { + for (int l = 1;; l++) { int x = (int) Math.pow(10, (l - 1) / 2); int y = (int) Math.pow(10, (l + 1) / 2); for (int i = x; i < y; i++) { long v = i; - for (int j = l % 2 == 0 ? i : i / 10; j > 0; j /= 10) { + int j = (l % 2 == 0) ? i : i / 10; + while (j > 0) { + v = v * 10 + j % 10; + j /= 10; + } + if (check(v, k)) { + ans += v; + n--; + if (n == 0) { + return ans; + } + } + } + } + } + + private boolean check(long x, int k) { + List s = new ArrayList<>(); + while (x > 0) { + s.add((int) (x % k)); + x /= k; + } + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (!s.get(i).equals(s.get(j))) { + return false; + } + } + return true; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + long long kMirror(int k, int n) { + long long ans = 0; + for (int l = 1;; ++l) { + int x = pow(10, (l - 1) / 2); + int y = pow(10, (l + 1) / 2); + for (int i = x; i < y; ++i) { + long long v = i; + int j = (l % 2 == 0) ? i : i / 10; + while (j > 0) { v = v * 10 + j % 10; + j /= 10; } - String ss = Long.toString(v, k); - if (check(ss.toCharArray())) { + if (check(v, k)) { ans += v; if (--n == 0) { return ans; @@ -114,14 +200,113 @@ class Solution { } } - private boolean check(char[] c) { - for (int i = 0, j = c.length - 1; i < j; i++, j--) { - if (c[i] != c[j]) { +private: + bool check(long long x, int k) { + vector s; + while (x > 0) { + s.push_back(x % k); + x /= k; + } + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (s[i] != s[j]) { return false; } } return true; } +}; +``` + +#### Go + +```go +func kMirror(k int, n int) int64 { + check := func(x int64, k int) bool { + s := []int{} + for x > 0 { + s = append(s, int(x%int64(k))) + x /= int64(k) + } + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + if s[i] != s[j] { + return false + } + } + return true + } + + var ans int64 = 0 + for l := 1; ; l++ { + x := pow10((l - 1) / 2) + y := pow10((l + 1) / 2) + for i := x; i < y; i++ { + v := int64(i) + j := i + if l%2 != 0 { + j = i / 10 + } + for j > 0 { + v = v*10 + int64(j%10) + j /= 10 + } + if check(v, k) { + ans += v + n-- + if n == 0 { + return ans + } + } + } + } +} + +func pow10(exp int) int { + res := 1 + for i := 0; i < exp; i++ { + res *= 10 + } + return res +} +``` + +#### TypeScript + +```ts +function kMirror(k: number, n: number): number { + function check(x: number, k: number): boolean { + const s: number[] = []; + while (x > 0) { + s.push(x % k); + x = Math.floor(x / k); + } + for (let i = 0, j = s.length - 1; i < j; i++, j--) { + if (s[i] !== s[j]) { + return false; + } + } + return true; + } + + let ans = 0; + for (let l = 1; ; l++) { + const x = Math.pow(10, Math.floor((l - 1) / 2)); + const y = Math.pow(10, Math.floor((l + 1) / 2)); + for (let i = x; i < y; i++) { + let v = i; + let j = l % 2 === 0 ? i : Math.floor(i / 10); + while (j > 0) { + v = v * 10 + (j % 10); + j = Math.floor(j / 10); + } + if (check(v, k)) { + ans += v; + n--; + if (n === 0) { + return ans; + } + } + } + } } ``` diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md index ec3ab6bf5b1bd..2238182ec1e96 100644 --- a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md @@ -86,26 +86,112 @@ Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499. -### Solution 1 +### Solution 1: Half Enumeration + Mathematics + +For a k-mirror number, we can divide it into two parts: the first half and the second half. For numbers with even length, the first and second halves are exactly the same; for numbers with odd length, the first and second halves are the same, but the middle digit can be any digit. + +We can enumerate the numbers in the first half, and then construct the complete k-mirror number based on the first half. The specific steps are as follows: + +1. **Enumerate Lengths**: Start enumerating the length of the numbers from 1, until we find enough k-mirror numbers that meet the requirements. +2. **Calculate the Range of the First Half**: For a number of length $l$, the range of the first half is $[10^{(l-1)/2}, 10^{(l+1)/2})$. +3. **Construct k-Mirror Numbers**: For each number $i$ in the first half, if the length is even, use $i$ directly as the first half; if the length is odd, divide $i$ by 10 to get the first half. Then reverse the digits of the first half and append them to form the complete k-mirror number. +4. **Check k-Mirror Numbers**: Convert the constructed number to base $k$ and check whether it is a palindrome. +5. **Accumulate the Result**: If it is a k-mirror number, add it to the result and decrease the counter $n$. When $n$ reaches 0, return the result. + +The time complexity mainly depends on the length being enumerated and the range of the first half. Since the maximum value of $n$ is 30, the number of enumerations is limited in practice. The space complexity is $O(1)$, since only a constant amount of extra space is +#### Python3 + +```python +class Solution: + def kMirror(self, k: int, n: int) -> int: + def check(x: int, k: int) -> bool: + s = [] + while x: + s.append(x % k) + x //= k + return s == s[::-1] + + ans = 0 + for l in count(1): + x = 10 ** ((l - 1) // 2) + y = 10 ** ((l + 1) // 2) + for i in range(x, y): + v = i + j = i if l % 2 == 0 else i // 10 + while j > 0: + v = v * 10 + j % 10 + j //= 10 + if check(v, k): + ans += v + n -= 1 + if n == 0: + return ans +``` + #### Java ```java class Solution { public long kMirror(int k, int n) { long ans = 0; - for (int l = 1;; ++l) { + for (int l = 1;; l++) { int x = (int) Math.pow(10, (l - 1) / 2); int y = (int) Math.pow(10, (l + 1) / 2); for (int i = x; i < y; i++) { long v = i; - for (int j = l % 2 == 0 ? i : i / 10; j > 0; j /= 10) { + int j = (l % 2 == 0) ? i : i / 10; + while (j > 0) { + v = v * 10 + j % 10; + j /= 10; + } + if (check(v, k)) { + ans += v; + n--; + if (n == 0) { + return ans; + } + } + } + } + } + + private boolean check(long x, int k) { + List s = new ArrayList<>(); + while (x > 0) { + s.add((int) (x % k)); + x /= k; + } + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (!s.get(i).equals(s.get(j))) { + return false; + } + } + return true; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + long long kMirror(int k, int n) { + long long ans = 0; + for (int l = 1;; ++l) { + int x = pow(10, (l - 1) / 2); + int y = pow(10, (l + 1) / 2); + for (int i = x; i < y; ++i) { + long long v = i; + int j = (l % 2 == 0) ? i : i / 10; + while (j > 0) { v = v * 10 + j % 10; + j /= 10; } - String ss = Long.toString(v, k); - if (check(ss.toCharArray())) { + if (check(v, k)) { ans += v; if (--n == 0) { return ans; @@ -115,14 +201,113 @@ class Solution { } } - private boolean check(char[] c) { - for (int i = 0, j = c.length - 1; i < j; i++, j--) { - if (c[i] != c[j]) { +private: + bool check(long long x, int k) { + vector s; + while (x > 0) { + s.push_back(x % k); + x /= k; + } + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (s[i] != s[j]) { return false; } } return true; } +}; +``` + +#### Go + +```go +func kMirror(k int, n int) int64 { + check := func(x int64, k int) bool { + s := []int{} + for x > 0 { + s = append(s, int(x%int64(k))) + x /= int64(k) + } + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + if s[i] != s[j] { + return false + } + } + return true + } + + var ans int64 = 0 + for l := 1; ; l++ { + x := pow10((l - 1) / 2) + y := pow10((l + 1) / 2) + for i := x; i < y; i++ { + v := int64(i) + j := i + if l%2 != 0 { + j = i / 10 + } + for j > 0 { + v = v*10 + int64(j%10) + j /= 10 + } + if check(v, k) { + ans += v + n-- + if n == 0 { + return ans + } + } + } + } +} + +func pow10(exp int) int { + res := 1 + for i := 0; i < exp; i++ { + res *= 10 + } + return res +} +``` + +#### TypeScript + +```ts +function kMirror(k: number, n: number): number { + function check(x: number, k: number): boolean { + const s: number[] = []; + while (x > 0) { + s.push(x % k); + x = Math.floor(x / k); + } + for (let i = 0, j = s.length - 1; i < j; i++, j--) { + if (s[i] !== s[j]) { + return false; + } + } + return true; + } + + let ans = 0; + for (let l = 1; ; l++) { + const x = Math.pow(10, Math.floor((l - 1) / 2)); + const y = Math.pow(10, Math.floor((l + 1) / 2)); + for (let i = x; i < y; i++) { + let v = i; + let j = l % 2 === 0 ? i : Math.floor(i / 10); + while (j > 0) { + v = v * 10 + (j % 10); + j = Math.floor(j / 10); + } + if (check(v, k)) { + ans += v; + n--; + if (n === 0) { + return ans; + } + } + } + } } ``` diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.cpp b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.cpp new file mode 100644 index 0000000000000..f0378bdb0147e --- /dev/null +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + long long kMirror(int k, int n) { + long long ans = 0; + for (int l = 1;; ++l) { + int x = pow(10, (l - 1) / 2); + int y = pow(10, (l + 1) / 2); + for (int i = x; i < y; ++i) { + long long v = i; + int j = (l % 2 == 0) ? i : i / 10; + while (j > 0) { + v = v * 10 + j % 10; + j /= 10; + } + if (check(v, k)) { + ans += v; + if (--n == 0) { + return ans; + } + } + } + } + } + +private: + bool check(long long x, int k) { + vector s; + while (x > 0) { + s.push_back(x % k); + x /= k; + } + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (s[i] != s[j]) { + return false; + } + } + return true; + } +}; diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.go b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.go new file mode 100644 index 0000000000000..b99c8b2fea28d --- /dev/null +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.go @@ -0,0 +1,47 @@ +func kMirror(k int, n int) int64 { + check := func(x int64, k int) bool { + s := []int{} + for x > 0 { + s = append(s, int(x%int64(k))) + x /= int64(k) + } + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + if s[i] != s[j] { + return false + } + } + return true + } + + var ans int64 = 0 + for l := 1; ; l++ { + x := pow10((l - 1) / 2) + y := pow10((l + 1) / 2) + for i := x; i < y; i++ { + v := int64(i) + j := i + if l%2 != 0 { + j = i / 10 + } + for j > 0 { + v = v*10 + int64(j%10) + j /= 10 + } + if check(v, k) { + ans += v + n-- + if n == 0 { + return ans + } + } + } + } +} + +func pow10(exp int) int { + res := 1 + for i := 0; i < exp; i++ { + res *= 10 + } + return res +} diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.java b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.java index c08776873b60b..f9dae28dfd03c 100644 --- a/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.java +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.java @@ -1,18 +1,20 @@ class Solution { public long kMirror(int k, int n) { long ans = 0; - for (int l = 1;; ++l) { + for (int l = 1;; l++) { int x = (int) Math.pow(10, (l - 1) / 2); int y = (int) Math.pow(10, (l + 1) / 2); for (int i = x; i < y; i++) { long v = i; - for (int j = l % 2 == 0 ? i : i / 10; j > 0; j /= 10) { + int j = (l % 2 == 0) ? i : i / 10; + while (j > 0) { v = v * 10 + j % 10; + j /= 10; } - String ss = Long.toString(v, k); - if (check(ss.toCharArray())) { + if (check(v, k)) { ans += v; - if (--n == 0) { + n--; + if (n == 0) { return ans; } } @@ -20,12 +22,17 @@ public long kMirror(int k, int n) { } } - private boolean check(char[] c) { - for (int i = 0, j = c.length - 1; i < j; i++, j--) { - if (c[i] != c[j]) { + private boolean check(long x, int k) { + List s = new ArrayList<>(); + while (x > 0) { + s.add((int) (x % k)); + x /= k; + } + for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { + if (!s.get(i).equals(s.get(j))) { return false; } } return true; } -} \ No newline at end of file +} diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.py b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.py new file mode 100644 index 0000000000000..df18cf29d7316 --- /dev/null +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.py @@ -0,0 +1,24 @@ +class Solution: + def kMirror(self, k: int, n: int) -> int: + def check(x: int, k: int) -> bool: + s = [] + while x: + s.append(x % k) + x //= k + return s == s[::-1] + + ans = 0 + for l in count(1): + x = 10 ** ((l - 1) // 2) + y = 10 ** ((l + 1) // 2) + for i in range(x, y): + v = i + j = i if l % 2 == 0 else i // 10 + while j > 0: + v = v * 10 + j % 10 + j //= 10 + if check(v, k): + ans += v + n -= 1 + if n == 0: + return ans diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.ts b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.ts new file mode 100644 index 0000000000000..4d5e04035acec --- /dev/null +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.ts @@ -0,0 +1,36 @@ +function kMirror(k: number, n: number): number { + function check(x: number, k: number): boolean { + const s: number[] = []; + while (x > 0) { + s.push(x % k); + x = Math.floor(x / k); + } + for (let i = 0, j = s.length - 1; i < j; i++, j--) { + if (s[i] !== s[j]) { + return false; + } + } + return true; + } + + let ans = 0; + for (let l = 1; ; l++) { + const x = Math.pow(10, Math.floor((l - 1) / 2)); + const y = Math.pow(10, Math.floor((l + 1) / 2)); + for (let i = x; i < y; i++) { + let v = i; + let j = l % 2 === 0 ? i : Math.floor(i / 10); + while (j > 0) { + v = v * 10 + (j % 10); + j = Math.floor(j / 10); + } + if (check(v, k)) { + ans += v; + n--; + if (n === 0) { + return ans; + } + } + } + } +} diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md index a0c24322cf7ec..60a570609910a 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md @@ -95,9 +95,7 @@ class Solution { public int[] maxSubsequence(int[] nums, int k) { int n = nums.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); Arrays.sort(idx, n - k, n); int[] ans = new int[k]; @@ -109,20 +107,41 @@ class Solution { } ``` +#### C++ + +```cpp +#include + +class Solution { +public: + vector maxSubsequence(vector & nums, int k) { + int n = nums.size(); + vector idx(n); + ranges::iota(idx, 0); + ranges::sort(idx, [&](int i, int j) { return nums[i] < nums[j]; }); + ranges::sort(idx | views::drop(n - k)); + vector ans(k); + for (int i = n - k; i < n; ++i) { + ans[i - (n - k)] = nums[idx[i]]; + } + return ans; + } +}; +``` + #### Go ```go func maxSubsequence(nums []int, k int) []int { - n := len(nums) - idx := make([]int, n) + idx := slices.Clone(make([]int, len(nums))) for i := range idx { idx[i] = i } - sort.Slice(idx, func(i, j int) bool { return nums[idx[i]] < nums[idx[j]] }) - sort.Ints(idx[n-k:]) + slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) + slices.Sort(idx[len(idx)-k:]) ans := make([]int, k) - for i := n - k; i < n; i++ { - ans[i-(n-k)] = nums[idx[i]] + for i := range ans { + ans[i] = nums[idx[len(idx)-k+i]] } return ans } @@ -142,6 +161,28 @@ function maxSubsequence(nums: number[], k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn max_subsequence(nums: Vec , k: i32) -> Vec { + let n = nums.len(); + let k = k as usize; + let mut idx: Vec = (0..n).collect(); + + idx.sort_by_key(|&i| nums[i]); + idx[n - k..].sort(); + + let mut ans = Vec::with_capacity(k); + for i in n - k..n { + ans.push(nums[idx[i]]); + } + + ans + } +} +``` + diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md index e8465c8bb9729..fe9496ca82787 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md @@ -96,9 +96,7 @@ class Solution { public int[] maxSubsequence(int[] nums, int k) { int n = nums.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); Arrays.sort(idx, n - k, n); int[] ans = new int[k]; @@ -110,20 +108,41 @@ class Solution { } ``` +#### C++ + +```cpp +#include + +class Solution { +public: + vector maxSubsequence(vector & nums, int k) { + int n = nums.size(); + vector idx(n); + ranges::iota(idx, 0); + ranges::sort(idx, [&](int i, int j) { return nums[i] < nums[j]; }); + ranges::sort(idx | views::drop(n - k)); + vector ans(k); + for (int i = n - k; i < n; ++i) { + ans[i - (n - k)] = nums[idx[i]]; + } + return ans; + } +}; +``` + #### Go ```go func maxSubsequence(nums []int, k int) []int { - n := len(nums) - idx := make([]int, n) + idx := slices.Clone(make([]int, len(nums))) for i := range idx { idx[i] = i } - sort.Slice(idx, func(i, j int) bool { return nums[idx[i]] < nums[idx[j]] }) - sort.Ints(idx[n-k:]) + slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) + slices.Sort(idx[len(idx)-k:]) ans := make([]int, k) - for i := n - k; i < n; i++ { - ans[i-(n-k)] = nums[idx[i]] + for i := range ans { + ans[i] = nums[idx[len(idx)-k+i]] } return ans } @@ -143,6 +162,28 @@ function maxSubsequence(nums: number[], k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn max_subsequence(nums: Vec , k: i32) -> Vec { + let n = nums.len(); + let k = k as usize; + let mut idx: Vec = (0..n).collect(); + + idx.sort_by_key(|&i| nums[i]); + idx[n - k..].sort(); + + let mut ans = Vec::with_capacity(k); + for i in n - k..n { + ans.push(nums[idx[i]]); + } + + ans + } +} +``` + diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.cpp b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.cpp index 60350b1b94b0a..544a813a15678 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.cpp +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.cpp @@ -1,13 +1,13 @@ +#include + class Solution { public: vector maxSubsequence(vector & nums, int k) { int n = nums.size(); vector idx(n); - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - sort(idx.begin(), idx.end(), [&](int i, int j) { return nums[i] < nums[j]; }); - sort(idx.begin() + (n - k), idx.end()); + ranges::iota(idx, 0); + ranges::sort(idx, [&](int i, int j) { return nums[i] < nums[j]; }); + ranges::sort(idx | views::drop(n - k)); vector ans(k); for (int i = n - k; i < n; ++i) { ans[i - (n - k)] = nums[idx[i]]; diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.go b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.go index 6dac3c53afae9..4bbfb3ffffcd1 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.go +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.go @@ -1,14 +1,13 @@ func maxSubsequence(nums []int, k int) []int { - n := len(nums) - idx := make([]int, n) + idx := slices.Clone(make([]int, len(nums))) for i := range idx { idx[i] = i } - sort.Slice(idx, func(i, j int) bool { return nums[idx[i]] < nums[idx[j]] }) - sort.Ints(idx[n-k:]) + slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) + slices.Sort(idx[len(idx)-k:]) ans := make([]int, k) - for i := n - k; i < n; i++ { - ans[i-(n-k)] = nums[idx[i]] + for i := range ans { + ans[i] = nums[idx[len(idx)-k+i]] } return ans } \ No newline at end of file diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.java b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.java index c4286fe13513d..ec70e12c950d8 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.java +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.java @@ -2,9 +2,7 @@ class Solution { public int[] maxSubsequence(int[] nums, int k) { int n = nums.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); Arrays.sort(idx, n - k, n); int[] ans = new int[k]; diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.rs b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.rs new file mode 100644 index 0000000000000..44c42f409d33d --- /dev/null +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/Solution.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn max_subsequence(nums: Vec , k: i32) -> Vec { + let n = nums.len(); + let k = k as usize; + let mut idx: Vec = (0..n).collect(); + + idx.sort_by_key(|&i| nums[i]); + idx[n - k..].sort(); + + let mut ans = Vec::with_capacity(k); + for i in n - k..n { + ans.push(nums[idx[i]]); + } + + ans + } +} diff --git a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md index 16eadec79aa72..e4be1bb9e729e 100644 --- a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md +++ b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md @@ -73,17 +73,17 @@ tags: ### 方法一:贪心 + 哈希表 -我们先用哈希表 `cnt` 统计每个单词出现的次数。 +我们先用一个哈希表 $\textit{cnt}$ 统计每个单词出现的次数。 -遍历 `cnt` 中的每个单词 $k$ 以及其出现次数 $v$: +遍历 $\textit{cnt}$ 中的每个单词 $k$ 以及其出现次数 $v$: -如果 $k$ 中两个字母相同,那么我们可以将 $\left \lfloor \frac{v}{2} \right \rfloor \times 2$ 个 $k$ 连接到回文串的前后,此时如果 $k$ 还剩余一个,那么我们可以先记录到 $x$ 中。 +- 如果 $k$ 中两个字母相同,那么我们可以将 $\left \lfloor \frac{v}{2} \right \rfloor \times 2$ 个 $k$ 连接到回文串的前后,此时如果 $k$ 还剩余一个,那么我们可以先记录到 $x$ 中。 -如果 $k$ 中两个字母不同,那么我们要找到一个单词 $k'$,使得 $k'$ 中的两个字母与 $k$ 相反,即 $k' = k[1] + k[0]$。如果 $k'$ 存在,那么我们可以将 $\min(v, cnt[k'])$ 个 $k$ 连接到回文串的前后。 +- 如果 $k$ 中两个字母不同,那么我们要找到一个单词 $k'$,使得 $k'$ 中的两个字母与 $k$ 相反,即 $k' = k[1] + k[0]$。如果 $k'$ 存在,那么我们可以将 $\min(v, \textit{cnt}[k'])$ 个 $k$ 连接到回文串的前后。 遍历结束后,如果 $x$ 不为空,那么我们还可以将一个单词连接到回文串的中间。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `words` 的长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为单词的数量。 @@ -111,7 +111,7 @@ class Solution { public int longestPalindrome(String[] words) { Map cnt = new HashMap<>(); for (var w : words) { - cnt.put(w, cnt.getOrDefault(w, 0) + 1); + cnt.merge(w, 1, Integer::sum); } int ans = 0, x = 0; for (var e : cnt.entrySet()) { @@ -183,6 +183,26 @@ func longestPalindrome(words []string) int { } ``` +#### TypeScript + +```ts +function longestPalindrome(words: string[]): number { + const cnt = new Map (); + for (const w of words) cnt.set(w, (cnt.get(w) || 0) + 1); + let [ans, x] = [0, 0]; + for (const [k, v] of cnt.entries()) { + if (k[0] === k[1]) { + x += v & 1; + ans += Math.floor(v / 2) * 2 * 2; + } else { + ans += Math.min(v, cnt.get(k[1] + k[0]) || 0) * 2; + } + } + ans += x ? 2 : 0; + return ans; +} +``` + diff --git a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md index e947717112683..029e61dd8d93e 100644 --- a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md +++ b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md @@ -73,7 +73,19 @@ Note that "ll" is another longest palindrome that can be created, and -### Solution 1 +### Solution 1: Greedy + Hash Table + +First, we use a hash table $\textit{cnt}$ to count the occurrences of each word. + +Iterate through each word $k$ and its count $v$ in $\textit{cnt}$: + +- If the two letters in $k$ are the same, we can concatenate $\left \lfloor \frac{v}{2} \right \rfloor \times 2$ copies of $k$ to the front and back of the palindrome. If there is one $k$ left, we can record it in $x$ for now. + +- If the two letters in $k$ are different, we need to find a word $k'$ such that the two letters in $k'$ are the reverse of $k$, i.e., $k' = k[1] + k[0]$. If $k'$ exists, we can concatenate $\min(v, \textit{cnt}[k'])$ copies of $k$ to the front and back of the palindrome. + +After the iteration, if $x$ is not empty, we can also place one word in the middle of the palindrome. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of words. @@ -101,7 +113,7 @@ class Solution { public int longestPalindrome(String[] words) { Map cnt = new HashMap<>(); for (var w : words) { - cnt.put(w, cnt.getOrDefault(w, 0) + 1); + cnt.merge(w, 1, Integer::sum); } int ans = 0, x = 0; for (var e : cnt.entrySet()) { @@ -173,6 +185,26 @@ func longestPalindrome(words []string) int { } ``` +#### TypeScript + +```ts +function longestPalindrome(words: string[]): number { + const cnt = new Map (); + for (const w of words) cnt.set(w, (cnt.get(w) || 0) + 1); + let [ans, x] = [0, 0]; + for (const [k, v] of cnt.entries()) { + if (k[0] === k[1]) { + x += v & 1; + ans += Math.floor(v / 2) * 2 * 2; + } else { + ans += Math.min(v, cnt.get(k[1] + k[0]) || 0) * 2; + } + } + ans += x ? 2 : 0; + return ans; +} +``` + diff --git a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.java b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.java index 30dd228456061..228a887591207 100644 --- a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.java +++ b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.java @@ -2,7 +2,7 @@ class Solution { public int longestPalindrome(String[] words) { Map cnt = new HashMap<>(); for (var w : words) { - cnt.put(w, cnt.getOrDefault(w, 0) + 1); + cnt.merge(w, 1, Integer::sum); } int ans = 0, x = 0; for (var e : cnt.entrySet()) { diff --git a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.ts b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.ts new file mode 100644 index 0000000000000..04ba6edec8550 --- /dev/null +++ b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.ts @@ -0,0 +1,15 @@ +function longestPalindrome(words: string[]): number { + const cnt = new Map (); + for (const w of words) cnt.set(w, (cnt.get(w) || 0) + 1); + let [ans, x] = [0, 0]; + for (const [k, v] of cnt.entries()) { + if (k[0] === k[1]) { + x += v & 1; + ans += Math.floor(v / 2) * 2 * 2; + } else { + ans += Math.min(v, cnt.get(k[1] + k[0]) || 0) * 2; + } + } + ans += x ? 2 : 0; + return ans; +} diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md index d0f0cc6921a97..b2da1d096f098 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md @@ -30,15 +30,15 @@ tags: 输入:nums = [3,4,9,1,3,9,5], key = 9, k = 1 输出:[1,2,3,4,5,6] -解释:因此,nums[2] == key
且nums[5] == key 。 -- 对下标 0 ,|0 - 2| > k 且 |0 - 5| > k ,所以不存在 j
使得|0 - j| <= k
且nums[j] == key 。所以 0 不是一个 K 近邻下标。 -- 对下标 1 ,|1 - 2| <= k 且 nums[2] == key ,所以 1 是一个 K 近邻下标。 -- 对下标 2 ,|2 - 2| <= k 且 nums[2] == key ,所以 2 是一个 K 近邻下标。 -- 对下标 3 ,|3 - 2| <= k 且 nums[2] == key ,所以 3 是一个 K 近邻下标。 -- 对下标 4 ,|4 - 5| <= k 且 nums[5] == key ,所以 4 是一个 K 近邻下标。 -- 对下标 5 ,|5 - 5| <= k 且 nums[5] == key ,所以 5 是一个 K 近邻下标。 -- 对下标 6 ,|6 - 5| <= k 且 nums[5] == key ,所以 6 是一个 K 近邻下标。 -
因此,按递增顺序返回 [1,2,3,4,5,6] 。 +解释:因此,nums[2] == key
且nums[5] == key
。 +- 对下标 0 ,|0 - 2| > k
且|0 - 5| > k
,所以不存在j
使得|0 - j| <= k
且nums[j] == key
。所以 0 不是一个 K 近邻下标。 +- 对下标 1 ,|1 - 2| <= k
且nums[2] == key
,所以 1 是一个 K 近邻下标。 +- 对下标 2 ,|2 - 2| <= k
且nums[2] == key
,所以 2 是一个 K 近邻下标。 +- 对下标 3 ,|3 - 2| <= k
且nums[2] == key
,所以 3 是一个 K 近邻下标。 +- 对下标 4 ,|4 - 5| <= k
且nums[5] == key
,所以 4 是一个 K 近邻下标。 +- 对下标 5 ,|5 - 5| <= k
且nums[5] == key
,所以 5 是一个 K 近邻下标。 +- 对下标 6 ,|6 - 5| <= k
且nums[5] == key
,所以 6 是一个 K 近邻下标。 +因此,按递增顺序返回 [1,2,3,4,5,6] 。示例 2:
@@ -46,7 +46,7 @@ tags:输入:nums = [2,2,2,2,2], key = 2, k = 2 输出:[0,1,2,3,4] -解释:对 nums 的所有下标 i ,总存在某个下标 j 使得 |i - j| <= k 且 nums[j] == key ,所以每个下标都是一个@@ -170,6 +170,26 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_k_distant_indices(nums: VecK 近邻下标。
+解释:对nums
的所有下标 i ,总存在某个下标 j 使得|i - j| <= k
且nums[j] == key
,所以每个下标都是一个 K 近邻下标。 因此,返回 [0,1,2,3,4] 。, key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut ans = Vec::new(); + for i in 0..n { + for j in 0..n { + if (i as i32 - j as i32).abs() <= k && nums[j] == key { + ans.push(i as i32); + break; + } + } + } + ans + } +} +``` + @@ -309,6 +329,46 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut idx = Vec::new(); + for i in 0..n { + if nums[i] == key { + idx.push(i as i32); + } + } + + let search = |x: i32| -> usize { + let (mut l, mut r) = (0, idx.len()); + while l < r { + let mid = (l + r) >> 1; + if idx[mid] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l + }; + + let mut ans = Vec::new(); + for i in 0..n { + let l = search(i as i32 - k); + let r = search(i as i32 + k + 1) as i32 - 1; + if l as i32 <= r { + ans.push(i as i32); + } + } + + ans + } +} +``` + @@ -414,6 +474,27 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut ans = Vec::new(); + let mut j = 0; + for i in 0..n { + while j < i.saturating_sub(k as usize) || (j < n && nums[j] != key) { + j += 1; + } + if j < n && j <= i + k as usize { + ans.push(i as i32); + } + } + ans + } +} +``` + diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md index 4bc9425ea523a..f8796012d1946 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md @@ -168,6 +168,26 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut ans = Vec::new(); + for i in 0..n { + for j in 0..n { + if (i as i32 - j as i32).abs() <= k && nums[j] == key { + ans.push(i as i32); + break; + } + } + } + ans + } +} +``` + @@ -307,6 +327,46 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut idx = Vec::new(); + for i in 0..n { + if nums[i] == key { + idx.push(i as i32); + } + } + + let search = |x: i32| -> usize { + let (mut l, mut r) = (0, idx.len()); + while l < r { + let mid = (l + r) >> 1; + if idx[mid] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l + }; + + let mut ans = Vec::new(); + for i in 0..n { + let l = search(i as i32 - k); + let r = search(i as i32 + k + 1) as i32 - 1; + if l as i32 <= r { + ans.push(i as i32); + } + } + + ans + } +} +``` + @@ -412,6 +472,27 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut ans = Vec::new(); + let mut j = 0; + for i in 0..n { + while j < i.saturating_sub(k as usize) || (j < n && nums[j] != key) { + j += 1; + } + if j < n && j <= i + k as usize { + ans.push(i as i32); + } + } + ans + } +} +``` + diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.rs b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.rs new file mode 100644 index 0000000000000..3613c2edadca4 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut ans = Vec::new(); + for i in 0..n { + for j in 0..n { + if (i as i32 - j as i32).abs() <= k && nums[j] == key { + ans.push(i as i32); + break; + } + } + } + ans + } +} diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.rs b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.rs new file mode 100644 index 0000000000000..fcfcdb2776a6a --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution2.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn find_k_distant_indices(nums: Vec , key: i32, k: i32) -> Vec { + let n = nums.len(); + let mut idx = Vec::new(); + for i in 0..n { + if nums[i] == key { + idx.push(i as i32); + } + } + + let search = |x: i32| -> usize { + let (mut l, mut r) = (0, idx.len()); + while l < r { + let mid = (l + r) >> 1; + if idx[mid] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l + }; + + let mut ans = Vec::new(); + for i in 0..n { + let l = search(i as i32 - k); + let r = search(i as i32 + k + 1) as i32 - 1; + if l as i32 <= r { + ans.push(i as i32); + } + } + + ans + } +} diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.rs b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.rs new file mode 100644 index 0000000000000..25e7e2b6ec360 --- /dev/null +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/Solution3.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_k_distant_indices(nums: Vec