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 @@
-
+
+
给你两个字符串 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/0200-0299/0245.Shortest Word Distance III/README.md b/solution/0200-0299/0245.Shortest Word Distance III/README.md index 51d9475fc32ee..379385980b016 100644 --- a/solution/0200-0299/0245.Shortest Word Distance III/README.md +++ b/solution/0200-0299/0245.Shortest Word Distance III/README.md @@ -56,13 +56,12 @@ tags: ### 方法一:分情况讨论 -先判断 `word1` 和 `word2` 是否相等: +我们首先判断 $\textit{word1}$ 和 $\textit{word2}$ 是否相等: -如果相等,遍历数组 `wordsDict`,找到两个 `word1` 的下标 $i$ 和 $j$,求 $i-j$ 的最小值。 +- 如果相等,遍历数组 $\textit{wordsDict}$,找到两个 $\textit{word1}$ 的下标 $i$ 和 $j$,求 $i-j$ 的最小值。 +- 如果不相等,遍历数组 $\textit{wordsDict}$,找到 $\textit{word1}$ 和 $\textit{word2}$ 的下标 $i$ 和 $j$,求 $i-j$ 的最小值。 -如果不相等,遍历数组 `wordsDict`,找到 `word1` 和 `word2` 的下标 $i$ 和 $j$,求 $i-j$ 的最小值。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `wordsDict` 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组 $\textit{wordsDict}$ 的长度。空间复杂度 $O(1)$。 @@ -199,6 +198,40 @@ func abs(x int) int { } ``` +#### TypeScript + +```ts +function shortestWordDistance(wordsDict: string[], word1: string, word2: string): number { + let ans = wordsDict.length; + if (word1 === word2) { + let j = -1; + for (let i = 0; i < wordsDict.length; i++) { + if (wordsDict[i] === word1) { + if (j !== -1) { + ans = Math.min(ans, i - j); + } + j = i; + } + } + } else { + let i = -1, + j = -1; + for (let k = 0; k < wordsDict.length; k++) { + if (wordsDict[k] === word1) { + i = k; + } + if (wordsDict[k] === word2) { + j = k; + } + if (i !== -1 && j !== -1) { + ans = Math.min(ans, Math.abs(i - j)); + } + } + } + return ans; +} +``` + diff --git a/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md b/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md index 72ab891b39ce6..6fbcb289984fb 100644 --- a/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md +++ b/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md @@ -45,7 +45,14 @@ tags: -### Solution 1 +### Solution 1: Case Analysis + +First, we check whether $\textit{word1}$ and $\textit{word2}$ are equal: + +- If they are equal, iterate through the array $\textit{wordsDict}$ to find two indices $i$ and $j$ of $\textit{word1}$, and compute the minimum value of $i-j$. +- If they are not equal, iterate through the array $\textit{wordsDict}$ to find the indices $i$ of $\textit{word1}$ and $j$ of $\textit{word2}$, and compute the minimum value of $i-j$. + +The time complexity is $O(n)$, where $n$ is the length of the array $\textit{wordsDict}$. The space complexity is $O(1)$. @@ -182,6 +189,40 @@ func abs(x int) int { } ``` +#### TypeScript + +```ts +function shortestWordDistance(wordsDict: string[], word1: string, word2: string): number { + let ans = wordsDict.length; + if (word1 === word2) { + let j = -1; + for (let i = 0; i < wordsDict.length; i++) { + if (wordsDict[i] === word1) { + if (j !== -1) { + ans = Math.min(ans, i - j); + } + j = i; + } + } + } else { + let i = -1, + j = -1; + for (let k = 0; k < wordsDict.length; k++) { + if (wordsDict[k] === word1) { + i = k; + } + if (wordsDict[k] === word2) { + j = k; + } + if (i !== -1 && j !== -1) { + ans = Math.min(ans, Math.abs(i - j)); + } + } + } + return ans; +} +``` + diff --git a/solution/0200-0299/0245.Shortest Word Distance III/Solution.ts b/solution/0200-0299/0245.Shortest Word Distance III/Solution.ts new file mode 100644 index 0000000000000..acb406b3b5ec7 --- /dev/null +++ b/solution/0200-0299/0245.Shortest Word Distance III/Solution.ts @@ -0,0 +1,29 @@ +function shortestWordDistance(wordsDict: string[], word1: string, word2: string): number { + let ans = wordsDict.length; + if (word1 === word2) { + let j = -1; + for (let i = 0; i < wordsDict.length; i++) { + if (wordsDict[i] === word1) { + if (j !== -1) { + ans = Math.min(ans, i - j); + } + j = i; + } + } + } else { + let i = -1, + j = -1; + for (let k = 0; k < wordsDict.length; k++) { + if (wordsDict[k] === word1) { + i = k; + } + if (wordsDict[k] === word2) { + j = k; + } + if (i !== -1 && j !== -1) { + ans = Math.min(ans, Math.abs(i - j)); + } + } + } + return ans; +} diff --git a/solution/0200-0299/0262.Trips and Users/README.md b/solution/0200-0299/0262.Trips and Users/README.md index 46938213c4cc8..87e992577500e 100644 --- a/solution/0200-0299/0262.Trips and Users/README.md +++ b/solution/0200-0299/0262.Trips and Users/README.md @@ -36,8 +36,6 @@ id 是这张表的主键(具有唯一值的列)。 status 是一个表示行程状态的枚举类型,枚举成员为(‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’) 。 --
表: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:
假设 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
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/0800-0899/0802.Find Eventual Safe States/README.md b/solution/0800-0899/0802.Find Eventual Safe States/README.md index efac1c82f3f3f..06994079ec0b8 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/README.md +++ b/solution/0800-0899/0802.Find Eventual Safe States/README.md @@ -21,7 +21,7 @@ tags:有一个有 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/0900-0999/0909.Snakes and Ladders/README.md b/solution/0900-0999/0909.Snakes and Ladders/README.md index f260b58f25623..f5feac9a8def4 100644 --- a/solution/0900-0999/0909.Snakes and Ladders/README.md +++ b/solution/0900-0999/0909.Snakes and Ladders/README.md @@ -279,6 +279,52 @@ function snakesAndLadders(board: number[][]): number { } ``` +#### Rust + +```rust +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn snakes_and_ladders(board: 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
- -
产品表 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/1128.Number of Equivalent Domino Pairs/README.md b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md index 1929c905a49f2..42812ca2724da 100644 --- a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md +++ b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md @@ -62,7 +62,7 @@ tags: 我们可以将每个多米诺骨牌的两个数字按照大小顺序拼接成一个两位数,这样就可以将等价的多米诺骨牌拼接成相同的两位数。例如,`[1, 2]` 和 `[2, 1]` 拼接成的两位数都是 `12`,`[3, 4]` 和 `[4, 3]` 拼接成的两位数都是 `34`。 -然后我们遍历所有的多米诺骨牌,用一个长度为 $100$ 的数组 $cnt$ 记录每个两位数出现的次数。对于每个多米诺骨牌,我们拼接成的两位数为 $x$,那么答案就会增加 $cnt[x]$,接着我们将 $cnt[x]$ 的值加 $1$。继续遍历下一个多米诺骨牌,就可以统计出所有等价的多米诺骨牌对的数量。 +然后我们遍历所有的多米诺骨牌,用一个哈希表或者一个长度为 $100$ 的数组 $cnt$ 记录每个两位数出现的次数。对于每个多米诺骨牌,我们拼接成的两位数为 $x$,那么答案就会增加 $cnt[x]$,接着我们将 $cnt[x]$ 的值加 $1$。继续遍历下一个多米诺骨牌,就可以统计出所有等价的多米诺骨牌对的数量。 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 是多米诺骨牌的数量,而 $C$ 是多米诺骨牌中拼接成的两位数的最大数量,即 $100$。 @@ -132,6 +132,44 @@ func numEquivDominoPairs(dominoes [][]int) (ans int) { } ``` +#### TypeScript + +```ts +function numEquivDominoPairs(dominoes: number[][]): number { + const cnt: number[] = new Array(100).fill(0); + let ans = 0; + + for (const [a, b] of dominoes) { + const key = a < b ? a * 10 + b : b * 10 + a; + ans += cnt[key]; + cnt[key]++; + } + + return ans; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_equiv_domino_pairs(dominoes: Vec-
请查询出所有浏览过自己文章的作者
+请查询出所有浏览过自己文章的作者。
-结果按照 id
升序排列。
结果按照作者的 id
升序排列。
查询结果的格式如下所示:
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/1200-1299/1257.Smallest Common Region/README.md b/solution/1200-1299/1257.Smallest Common Region/README.md index f9a73717dfc2d..9f9d29a65c437 100644 --- a/solution/1200-1299/1257.Smallest Common Region/README.md +++ b/solution/1200-1299/1257.Smallest Common Region/README.md @@ -23,14 +23,14 @@ tags: -给你一些区域列表 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/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/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..4c329fbbdcd4b 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: -给你一个整数
+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 ++For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums1. Therefore, answer[1] = [4,6].+输入: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..cae87b2201938 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 tonums
two times independently:-
- 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 the new integer (either
+a
orb
) must not have any leading zeros, and it 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/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 (); + 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/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/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/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/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]. 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: -
- -
3 <= m <= 105
- +
1 <= k*2 < m
1 < k*2 < m
1 <= num <= 105
- At most
105
calls will be made toaddElement
andcalculateMKAverage
.给你一个 有向图 ,它含有
+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/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/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: 给你一个整数数组
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/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..ac5d851b018b6 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,69 @@ 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); +} +``` + 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..97650014c80a7 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,69 @@ 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); +} +``` + 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/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/2215.Find the Difference of Two Arrays/README_EN.md b/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md index e86a18a1e14d4..c2a94c37409ba 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md @@ -36,7 +36,7 @@ tags: Output: [[1,3],[4,6]] Explanation: For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3]. -For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6]. Example 2:
diff --git a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md index 88e65ee3b9473..5dd30b7801c23 100644 --- a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md +++ b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md @@ -170,6 +170,29 @@ function successfulPairs(spells: number[], potions: number[], success: number): } ``` +#### Rust + +```rust +impl Solution { + pub fn successful_pairs(spells: Vec, mut potions: Vec , success: i64) -> Vec { + potions.sort(); + let m = potions.len(); + + spells.into_iter().map(|v| { + let i = potions.binary_search_by(|&p| { + let prod = (p as i64) * (v as i64); + if prod >= success { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Less + } + }).unwrap_or_else(|x| x); + (m - i) as i32 + }).collect() + } +} +``` + diff --git a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md index 463d652b4ed1e..9ff195d0061ff 100644 --- a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md +++ b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md @@ -170,6 +170,29 @@ function successfulPairs(spells: number[], potions: number[], success: number): } ``` +#### Rust + +```rust +impl Solution { + pub fn successful_pairs(spells: Vec , mut potions: Vec , success: i64) -> Vec { + potions.sort(); + let m = potions.len(); + + spells.into_iter().map(|v| { + let i = potions.binary_search_by(|&p| { + let prod = (p as i64) * (v as i64); + if prod >= success { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Less + } + }).unwrap_or_else(|x| x); + (m - i) as i32 + }).collect() + } +} +``` + diff --git a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/Solution.rs b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/Solution.rs new file mode 100644 index 0000000000000..138b9f3096dff --- /dev/null +++ b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/Solution.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn successful_pairs(spells: Vec , mut potions: Vec , success: i64) -> Vec { + potions.sort(); + let m = potions.len(); + + spells + .into_iter() + .map(|v| { + let i = potions + .binary_search_by(|&p| { + let prod = (p as i64) * (v as i64); + if prod >= success { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Less + } + }) + .unwrap_or_else(|x| x); + (m - i) as i32 + }) + .collect() + } +} diff --git a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md index 6e48a84065363..0710acaa06bbc 100644 --- a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md +++ b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md @@ -23,7 +23,7 @@ tags: 给你一个二进制字符串
-s
和一个正整数k
。请你返回
+s
的 最长 子序列,且该子序列对应的 二进制 数字小于等于k
。请你返回
s
的 最长 子序列的长度,且该子序列对应的 二进制 数字小于等于k
。注意:
@@ -37,7 +37,8 @@ tags:示例 1:
-输入:s = "1001010", k = 5 ++输入:s = "1001010", k = 5 输出:5 解释:s 中小于等于 5 的最长子序列是 "00010" ,对应的十进制数字是 2 。 注意 "00100" 和 "00101" 也是可行的最长子序列,十进制分别对应 4 和 5 。 @@ -46,7 +47,8 @@ tags:示例 2:
-输入:s = "00101001", k = 1 ++输入:s = "00101001", k = 1 输出:6 解释:"000001" 是 s 中小于等于 1 的最长子序列,对应的十进制数字是 1 。 最长子序列的长度为 6 ,所以返回 6 。 diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md index 7835659c6285f..8b2b3a641d83b 100644 --- a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md @@ -53,7 +53,7 @@ tags: 输出:11 解释:存在以下理想数组: - 以 1 开头的数组(9 个): - - 不含其他不同值(1 个):[1,1,1,1,1] + - 不含其他不同值(1 个):[1,1,1,1,1] - 含一个不同值 2(4 个):[1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2] - 含一个不同值 3(4 个):[1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3] - 以 2 开头的数组(1 个):[2,2,2,2,2] diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md index acc766b46b2ff..9e2cde912546e 100644 --- a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md @@ -53,8 +53,8 @@ There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays. Input: n = 5, maxValue = 3 Output: 11 Explanation: The following are the possible ideal arrays: -- Arrays starting with the value 1 (9 arrays): - - With no other distinct values (1 array): [1,1,1,1,1] +- Arrays starting with the value 1 (9 arrays): + - With no other distinct values (1 array): [1,1,1,1,1] - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2] - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3] - Arrays starting with the value 2 (1 array): [2,2,2,2,2] @@ -92,8 +92,8 @@ $$ where $k$ represents the maximum value of the array, i.e., $\textit{maxValue}$. -- **Time Complexity**: $O(m \times \log^2 m)$ -- **Space Complexity**: $O(m \times \log m)$ +- **Time Complexity**: $O(m \times \log^2 m)$ +- **Space Complexity**: $O(m \times \log m)$ diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md index ef26b3b7f4864..5f6bcf5335353 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md @@ -69,9 +69,9 @@ tags: ### 方法一:哈希表或数组 -我们观察到,每一次操作,都可以把数组 `nums` 中相同且非零的元素减少到 $0$,因此,我们只需要统计数组 `nums` 中有多少个不同的非零元素,即为最少操作数。统计不同的非零元素,可以使用哈希表或数组来实现。 +我们观察到,每一次操作,都可以把数组 $\textit{nums}$ 中相同且非零的元素减少到 $0$,因此,我们只需要统计数组 $\textit{nums}$ 中有多少个不同的非零元素,即为最少操作数。统计不同的非零元素,可以使用哈希表或数组来实现。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 @@ -141,9 +141,9 @@ func minimumOperations(nums []int) (ans int) { ```ts function minimumOperations(nums: number[]): number { - const set = new Set(nums); - set.delete(0); - return set.size; + const s = new Set(nums); + s.delete(0); + return s.size; } ``` @@ -153,9 +153,9 @@ function minimumOperations(nums: number[]): number { use std::collections::HashSet; impl Solution { pub fn minimum_operations(nums: Vec) -> i32 { - let mut set = nums.iter().collect:: >(); - set.remove(&0); - set.len() as i32 + let mut s = nums.iter().collect:: >(); + s.remove(&0); + s.len() as i32 } } ``` diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md index c838453885ea3..2fe4810adaeae 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md @@ -66,7 +66,11 @@ In the third operation, choose x = 2. Now, nums = [0,0,0,0,0]. -### Solution 1 +### Solution 1: Hash Table or Array + +We observe that in each operation, all identical nonzero elements in the array $\textit{nums}$ can be reduced to $0$. Therefore, we only need to count the number of distinct nonzero elements in $\textit{nums}$, which is the minimum number of operations required. To count the distinct nonzero elements, we can use a hash table or an array. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. @@ -136,9 +140,9 @@ func minimumOperations(nums []int) (ans int) { ```ts function minimumOperations(nums: number[]): number { - const set = new Set(nums); - set.delete(0); - return set.size; + const s = new Set(nums); + s.delete(0); + return s.size; } ``` @@ -148,9 +152,9 @@ function minimumOperations(nums: number[]): number { use std::collections::HashSet; impl Solution { pub fn minimum_operations(nums: Vec ) -> i32 { - let mut set = nums.iter().collect:: >(); - set.remove(&0); - set.len() as i32 + let mut s = nums.iter().collect:: >(); + s.remove(&0); + s.len() as i32 } } ``` diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.rs b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.rs index f151e5c72c7e4..4ff22f3cef398 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.rs +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.rs @@ -1,8 +1,8 @@ use std::collections::HashSet; impl Solution { pub fn minimum_operations(nums: Vec ) -> i32 { - let mut set = nums.iter().collect:: >(); - set.remove(&0); - set.len() as i32 + let mut s = nums.iter().collect:: >(); + s.remove(&0); + s.len() as i32 } } diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.ts b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.ts index 3af64fe7ad831..cf008ba706dba 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.ts +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.ts @@ -1,5 +1,5 @@ function minimumOperations(nums: number[]): number { - const set = new Set(nums); - set.delete(0); - return set.size; + const s = new Set(nums); + s.delete(0); + return s.size; } diff --git a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md index a1c8bfc0ec628..ad1b415e313c9 100644 --- a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md +++ b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md @@ -160,6 +160,26 @@ function maximumGroups(grades: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn maximum_groups(grades: Vec ) -> i32 { + let n = grades.len() as i64; + let (mut l, mut r) = (0i64, n); + while l < r { + let mid = (l + r + 1) / 2; + if mid * mid + mid > 2 * n { + r = mid - 1; + } else { + l = mid; + } + } + l as i32 + } +} +``` + diff --git a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md index c8e777fea4956..c62526d71ac88 100644 --- a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md +++ b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md @@ -65,7 +65,17 @@ It can be shown that it is not possible to form more than 3 groups. -### Solution 1 +### Solution 1: Greedy + Binary Search + +Observing the conditions in the problem, the number of students in the $i$-th group must be less than that in the $(i+1)$-th group, and the total score of students in the $i$-th group must be less than that in the $(i+1)$-th group. We only need to sort the students by their scores in ascending order, and then assign $1$, $2$, ..., $k$ students to each group in order. If the last group does not have enough students for $k$, we can distribute these students to the previous last group. + +Therefore, we need to find the largest $k$ such that $\frac{(1 + k) \times k}{2} \leq n$, where $n$ is the total number of students. We can use binary search to solve this. + +We define the left boundary of binary search as $l = 1$ and the right boundary as $r = n$. Each time, the midpoint is $mid = \lfloor \frac{l + r + 1}{2} \rfloor$. If $(1 + mid) \times mid \gt 2 \times n$, it means $mid$ is too large, so we shrink the right boundary to $mid - 1$; otherwise, we increase the left boundary to $mid$. + +Finally, we return $l$ as the answer. + +The time complexity is $O(\log n)$ and the space complexity is $O(1)$, where $n$ is the total number of students. @@ -150,6 +160,26 @@ function maximumGroups(grades: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn maximum_groups(grades: Vec ) -> i32 { + let n = grades.len() as i64; + let (mut l, mut r) = (0i64, n); + while l < r { + let mid = (l + r + 1) / 2; + if mid * mid + mid > 2 * n { + r = mid - 1; + } else { + l = mid; + } + } + l as i32 + } +} +``` + diff --git a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/Solution.rs b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/Solution.rs new file mode 100644 index 0000000000000..958bb57d2c90b --- /dev/null +++ b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/Solution.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn maximum_groups(grades: Vec ) -> i32 { + let n = grades.len() as i64; + let (mut l, mut r) = (0i64, n); + while l < r { + let mid = (l + r + 1) / 2; + if mid * mid + mid > 2 * n { + r = mid - 1; + } else { + l = mid; + } + } + l as i32 + } +} diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md index 4be648359d10b..a778a983177ba 100644 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md @@ -86,16 +86,16 @@ tags: ```python class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def dijkstra(i): + def f(i): dist = [inf] * n dist[i] = 0 - q = [(0, i)] + q = deque([i]) while q: - i = heappop(q)[1] + i = q.popleft() for j in g[i]: - if dist[j] > dist[i] + 1: + if dist[j] == inf: dist[j] = dist[i] + 1 - heappush(q, (dist[j], j)) + q.append(j) return dist g = defaultdict(list) @@ -103,8 +103,8 @@ class Solution: if j != -1: g[i].append(j) n = len(edges) - d1 = dijkstra(node1) - d2 = dijkstra(node2) + d1 = f(node1) + d2 = f(node2) ans, d = -1, inf for i, (a, b) in enumerate(zip(d1, d2)): if (t := max(a, b)) < d: @@ -129,8 +129,8 @@ class Solution { g[i].add(edges[i]); } } - int[] d1 = dijkstra(node1); - int[] d2 = dijkstra(node2); + int[] d1 = f(node1); + int[] d2 = f(node2); int d = 1 << 30; int ans = -1; for (int i = 0; i < n; ++i) { @@ -143,19 +143,18 @@ class Solution { return ans; } - private int[] dijkstra(int i) { + private int[] f(int i) { int[] dist = new int[n]; Arrays.fill(dist, 1 << 30); dist[i] = 0; - PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); - q.offer(new int[] {0, i}); + Deque q = new ArrayDeque<>(); + q.offer(i); while (!q.isEmpty()) { - var p = q.poll(); - i = p[1]; + i = q.poll(); for (int j : g[i]) { - if (dist[j] > dist[i] + 1) { + if (dist[j] == 1 << 30) { dist[j] = dist[i] + 1; - q.offer(new int[] {dist[j], j}); + q.offer(j); } } } @@ -179,26 +178,24 @@ public: } const int inf = 1 << 30; using pii = pair ; - auto dijkstra = [&](int i) { + auto f = [&](int i) { vector dist(n, inf); dist[i] = 0; - priority_queue , greater > q; - q.emplace(0, i); + queue q{{i}}; while (!q.empty()) { - auto p = q.top(); + i = q.front(); q.pop(); - i = p.second; for (int j : g[i]) { - if (dist[j] > dist[i] + 1) { + if (dist[j] == inf) { dist[j] = dist[i] + 1; - q.emplace(dist[j], j); + q.push(j); } } } return dist; }; - vector d1 = dijkstra(node1); - vector d2 = dijkstra(node2); + vector d1 = f(node1); + vector d2 = f(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { int t = max(d1[i], d2[i]); @@ -224,27 +221,27 @@ func closestMeetingNode(edges []int, node1 int, node2 int) int { } } const inf int = 1 << 30 - dijkstra := func(i int) []int { + f := func(i int) []int { dist := make([]int, n) for j := range dist { dist[j] = inf } dist[i] = 0 - q := hp{} - heap.Push(&q, pair{0, i}) + q := []int{i} for len(q) > 0 { - i := heap.Pop(&q).(pair).i + i = q[0] + q = q[1:] for _, j := range g[i] { - if dist[j] > dist[i]+1 { + if dist[j] == inf { dist[j] = dist[i] + 1 - heap.Push(&q, pair{dist[j], j}) + q = append(q, j) } } } return dist } - d1 := dijkstra(node1) - d2 := dijkstra(node2) + d1 := f(node1) + d2 := f(node2) ans, d := -1, inf for i, a := range d1 { b := d2[i] @@ -256,15 +253,6 @@ func closestMeetingNode(edges []int, node1 int, node2 int) int { } return ans } - -type pair struct{ d, i int } -type hp []pair - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { return h[i].d < h[j].d } -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` #### TypeScript @@ -309,134 +297,89 @@ function closestMeetingNode(edges: number[], node1: number, node2: number): numb } ``` - - - - - - -### 方法二 - - +#### Rust -#### Python3 +```rust +use std::collections::VecDeque; -```python -class Solution: - def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def f(i): - dist = [inf] * n - dist[i] = 0 - q = deque([i]) - while q: - i = q.popleft() - for j in g[i]: - if dist[j] == inf: - dist[j] = dist[i] + 1 - q.append(j) - return dist - - g = defaultdict(list) - for i, j in enumerate(edges): - if j != -1: - g[i].append(j) - n = len(edges) - d1 = f(node1) - d2 = f(node2) - ans, d = -1, inf - for i, (a, b) in enumerate(zip(d1, d2)): - if (t := max(a, b)) < d: - d = t - ans = i - return ans -``` - -#### Java - -```java -class Solution { - private int n; - private List [] g; - - public int closestMeetingNode(int[] edges, int node1, int node2) { - n = edges.length; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].add(edges[i]); +impl Solution { + pub fn closest_meeting_node(edges: Vec , node1: i32, node2: i32) -> i32 { + let n = edges.len(); + let mut g = vec![Vec::new(); n]; + for i in 0..n { + if edges[i] != -1 { + g[i].push(edges[i] as usize); } } - int[] d1 = f(node1); - int[] d2 = f(node2); - int d = 1 << 30; - int ans = -1; - for (int i = 0; i < n; ++i) { - int t = Math.max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } - - private int[] f(int i) { - int[] dist = new int[n]; - Arrays.fill(dist, 1 << 30); - dist[i] = 0; - Deque q = new ArrayDeque<>(); - q.offer(i); - while (!q.isEmpty()) { - i = q.poll(); - for (int j : g[i]) { - if (dist[j] == 1 << 30) { - dist[j] = dist[i] + 1; - q.offer(j); + let inf = 1 << 30; + let f = |mut i: usize| -> Vec { + let mut dist = vec![inf; n]; + dist[i] = 0; + let mut q = VecDeque::new(); + q.push_back(i); + while !q.is_empty() { + i = q.pop_front().unwrap(); + for &j in &g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1; + q.push_back(j); + } } } + dist + }; + let d1 = f(node1 as usize); + let d2 = f(node2 as usize); + let mut ans = -1; + let mut d = inf; + for i in 0..n { + let t = std::cmp::max(d1[i], d2[i]); + if t < d { + d = t; + ans = i as i32; + } } - return dist; + ans } } ``` -#### C++ +#### C# -```cpp -class Solution { -public: - int closestMeetingNode(vector & edges, int node1, int node2) { - int n = edges.size(); - vector > g(n); +```cs +public class Solution { + public int ClosestMeetingNode(int[] edges, int node1, int node2) { + int n = edges.Length; + List [] g = new List [n]; for (int i = 0; i < n; ++i) { + g[i] = new List (); if (edges[i] != -1) { - g[i].push_back(edges[i]); + g[i].Add(edges[i]); } } - const int inf = 1 << 30; - using pii = pair ; - auto f = [&](int i) { - vector dist(n, inf); + int inf = 1 << 30; + int[] f(int i) { + int[] dist = new int[n]; + Array.Fill(dist, inf); dist[i] = 0; - queue q{{i}}; - while (!q.empty()) { - i = q.front(); - q.pop(); - for (int j : g[i]) { + Queue q = new Queue (); + q.Enqueue(i); + while (q.Count > 0) { + i = q.Dequeue(); + foreach (int j in g[i]) { if (dist[j] == inf) { dist[j] = dist[i] + 1; - q.push(j); + q.Enqueue(j); } } } return dist; - }; - vector d1 = f(node1); - vector d2 = f(node2); + } + int[] d1 = f(node1); + int[] d2 = f(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { - int t = max(d1[i], d2[i]); + int t = Math.Max(d1[i], d2[i]); if (t < d) { d = t; ans = i; @@ -444,52 +387,53 @@ public: } return ans; } -}; +} ``` -#### Go +#### Swift -```go -func closestMeetingNode(edges []int, node1 int, node2 int) int { - n := len(edges) - g := make([][]int, n) - for i, j := range edges { - if j != -1 { - g[i] = append(g[i], j) - } - } - const inf int = 1 << 30 - f := func(i int) []int { - dist := make([]int, n) - for j := range dist { - dist[j] = inf - } - dist[i] = 0 - q := []int{i} - for len(q) > 0 { - i = q[0] - q = q[1:] - for _, j := range g[i] { - if dist[j] == inf { - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - } - return dist - } - d1 := f(node1) - d2 := f(node2) - ans, d := -1, inf - for i, a := range d1 { - b := d2[i] - t := max(a, b) - if t < d { - d = t - ans = i - } - } - return ans +```swift +class Solution { + func closestMeetingNode(_ edges: [Int], _ node1: Int, _ node2: Int) -> Int { + let n = edges.count + var g = [[Int]](repeating: [], count: n) + for i in 0.. [Int] { + var dist = [Int](repeating: inf, count: n) + dist[i] = 0 + var q = [i] + var idx = 0 + while idx < q.count { + let i = q[idx] + idx += 1 + for j in g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1 + q.append(j) + } + } + } + return dist + } + + let d1 = f(node1) + let d2 = f(node2) + var ans = -1, d = inf + for i in 0.. -### Solution 1 +### Solution 1: BFS + Enumerate Common Nodes + +We can first use BFS to calculate the distance from $node1$ and $node2$ to every node, denoted as $d_1$ and $d_2$ respectively. Then, enumerate all common nodes $i$, and for each, compute $\max(d_1[i], d_2[i])$. The answer is the node with the minimal such value. + +The complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes. + +Related problems: + +- [2203. Minimum Weighted Subgraph With the Required Paths](https://github.com/doocs/leetcode/blob/main/solution/2200-2299/2203.Minimum%20Weighted%20Subgraph%20With%20the%20Required%20Paths/README_EN.md) @@ -74,16 +82,16 @@ The maximum of those two distances is 2. It can be proven that we cannot get a n ```python class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def dijkstra(i): + def f(i): dist = [inf] * n dist[i] = 0 - q = [(0, i)] + q = deque([i]) while q: - i = heappop(q)[1] + i = q.popleft() for j in g[i]: - if dist[j] > dist[i] + 1: + if dist[j] == inf: dist[j] = dist[i] + 1 - heappush(q, (dist[j], j)) + q.append(j) return dist g = defaultdict(list) @@ -91,8 +99,8 @@ class Solution: if j != -1: g[i].append(j) n = len(edges) - d1 = dijkstra(node1) - d2 = dijkstra(node2) + d1 = f(node1) + d2 = f(node2) ans, d = -1, inf for i, (a, b) in enumerate(zip(d1, d2)): if (t := max(a, b)) < d: @@ -117,8 +125,8 @@ class Solution { g[i].add(edges[i]); } } - int[] d1 = dijkstra(node1); - int[] d2 = dijkstra(node2); + int[] d1 = f(node1); + int[] d2 = f(node2); int d = 1 << 30; int ans = -1; for (int i = 0; i < n; ++i) { @@ -131,19 +139,18 @@ class Solution { return ans; } - private int[] dijkstra(int i) { + private int[] f(int i) { int[] dist = new int[n]; Arrays.fill(dist, 1 << 30); dist[i] = 0; - PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); - q.offer(new int[] {0, i}); + Deque q = new ArrayDeque<>(); + q.offer(i); while (!q.isEmpty()) { - var p = q.poll(); - i = p[1]; + i = q.poll(); for (int j : g[i]) { - if (dist[j] > dist[i] + 1) { + if (dist[j] == 1 << 30) { dist[j] = dist[i] + 1; - q.offer(new int[] {dist[j], j}); + q.offer(j); } } } @@ -167,26 +174,24 @@ public: } const int inf = 1 << 30; using pii = pair ; - auto dijkstra = [&](int i) { + auto f = [&](int i) { vector dist(n, inf); dist[i] = 0; - priority_queue , greater > q; - q.emplace(0, i); + queue q{{i}}; while (!q.empty()) { - auto p = q.top(); + i = q.front(); q.pop(); - i = p.second; for (int j : g[i]) { - if (dist[j] > dist[i] + 1) { + if (dist[j] == inf) { dist[j] = dist[i] + 1; - q.emplace(dist[j], j); + q.push(j); } } } return dist; }; - vector d1 = dijkstra(node1); - vector d2 = dijkstra(node2); + vector d1 = f(node1); + vector d2 = f(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { int t = max(d1[i], d2[i]); @@ -212,27 +217,27 @@ func closestMeetingNode(edges []int, node1 int, node2 int) int { } } const inf int = 1 << 30 - dijkstra := func(i int) []int { + f := func(i int) []int { dist := make([]int, n) for j := range dist { dist[j] = inf } dist[i] = 0 - q := hp{} - heap.Push(&q, pair{0, i}) + q := []int{i} for len(q) > 0 { - i := heap.Pop(&q).(pair).i + i = q[0] + q = q[1:] for _, j := range g[i] { - if dist[j] > dist[i]+1 { + if dist[j] == inf { dist[j] = dist[i] + 1 - heap.Push(&q, pair{dist[j], j}) + q = append(q, j) } } } return dist } - d1 := dijkstra(node1) - d2 := dijkstra(node2) + d1 := f(node1) + d2 := f(node2) ans, d := -1, inf for i, a := range d1 { b := d2[i] @@ -244,15 +249,6 @@ func closestMeetingNode(edges []int, node1 int, node2 int) int { } return ans } - -type pair struct{ d, i int } -type hp []pair - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { return h[i].d < h[j].d } -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` #### TypeScript @@ -297,134 +293,89 @@ function closestMeetingNode(edges: number[], node1: number, node2: number): numb } ``` - - - - - - -### Solution 2 +#### Rust - +```rust +use std::collections::VecDeque; -#### Python3 - -```python -class Solution: - def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def f(i): - dist = [inf] * n - dist[i] = 0 - q = deque([i]) - while q: - i = q.popleft() - for j in g[i]: - if dist[j] == inf: - dist[j] = dist[i] + 1 - q.append(j) - return dist - - g = defaultdict(list) - for i, j in enumerate(edges): - if j != -1: - g[i].append(j) - n = len(edges) - d1 = f(node1) - d2 = f(node2) - ans, d = -1, inf - for i, (a, b) in enumerate(zip(d1, d2)): - if (t := max(a, b)) < d: - d = t - ans = i - return ans -``` - -#### Java - -```java -class Solution { - private int n; - private List [] g; - - public int closestMeetingNode(int[] edges, int node1, int node2) { - n = edges.length; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].add(edges[i]); - } - } - int[] d1 = f(node1); - int[] d2 = f(node2); - int d = 1 << 30; - int ans = -1; - for (int i = 0; i < n; ++i) { - int t = Math.max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; +impl Solution { + pub fn closest_meeting_node(edges: Vec , node1: i32, node2: i32) -> i32 { + let n = edges.len(); + let mut g = vec![Vec::new(); n]; + for i in 0..n { + if edges[i] != -1 { + g[i].push(edges[i] as usize); } } - return ans; - } - - private int[] f(int i) { - int[] dist = new int[n]; - Arrays.fill(dist, 1 << 30); - dist[i] = 0; - Deque q = new ArrayDeque<>(); - q.offer(i); - while (!q.isEmpty()) { - i = q.poll(); - for (int j : g[i]) { - if (dist[j] == 1 << 30) { - dist[j] = dist[i] + 1; - q.offer(j); + let inf = 1 << 30; + let f = |mut i: usize| -> Vec { + let mut dist = vec![inf; n]; + dist[i] = 0; + let mut q = VecDeque::new(); + q.push_back(i); + while !q.is_empty() { + i = q.pop_front().unwrap(); + for &j in &g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1; + q.push_back(j); + } } } + dist + }; + let d1 = f(node1 as usize); + let d2 = f(node2 as usize); + let mut ans = -1; + let mut d = inf; + for i in 0..n { + let t = std::cmp::max(d1[i], d2[i]); + if t < d { + d = t; + ans = i as i32; + } } - return dist; + ans } } ``` -#### C++ +#### C# -```cpp -class Solution { -public: - int closestMeetingNode(vector & edges, int node1, int node2) { - int n = edges.size(); - vector > g(n); +```cs +public class Solution { + public int ClosestMeetingNode(int[] edges, int node1, int node2) { + int n = edges.Length; + List [] g = new List [n]; for (int i = 0; i < n; ++i) { + g[i] = new List (); if (edges[i] != -1) { - g[i].push_back(edges[i]); + g[i].Add(edges[i]); } } - const int inf = 1 << 30; - using pii = pair ; - auto f = [&](int i) { - vector dist(n, inf); + int inf = 1 << 30; + int[] f(int i) { + int[] dist = new int[n]; + Array.Fill(dist, inf); dist[i] = 0; - queue q{{i}}; - while (!q.empty()) { - i = q.front(); - q.pop(); - for (int j : g[i]) { + Queue q = new Queue (); + q.Enqueue(i); + while (q.Count > 0) { + i = q.Dequeue(); + foreach (int j in g[i]) { if (dist[j] == inf) { dist[j] = dist[i] + 1; - q.push(j); + q.Enqueue(j); } } } return dist; - }; - vector d1 = f(node1); - vector d2 = f(node2); + } + int[] d1 = f(node1); + int[] d2 = f(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { - int t = max(d1[i], d2[i]); + int t = Math.Max(d1[i], d2[i]); if (t < d) { d = t; ans = i; @@ -432,52 +383,53 @@ public: } return ans; } -}; +} ``` -#### Go +#### Swift -```go -func closestMeetingNode(edges []int, node1 int, node2 int) int { - n := len(edges) - g := make([][]int, n) - for i, j := range edges { - if j != -1 { - g[i] = append(g[i], j) - } - } - const inf int = 1 << 30 - f := func(i int) []int { - dist := make([]int, n) - for j := range dist { - dist[j] = inf - } - dist[i] = 0 - q := []int{i} - for len(q) > 0 { - i = q[0] - q = q[1:] - for _, j := range g[i] { - if dist[j] == inf { - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - } - return dist - } - d1 := f(node1) - d2 := f(node2) - ans, d := -1, inf - for i, a := range d1 { - b := d2[i] - t := max(a, b) - if t < d { - d = t - ans = i - } - } - return ans +```swift +class Solution { + func closestMeetingNode(_ edges: [Int], _ node1: Int, _ node2: Int) -> Int { + let n = edges.count + var g = [[Int]](repeating: [], count: n) + for i in 0.. [Int] { + var dist = [Int](repeating: inf, count: n) + dist[i] = 0 + var q = [i] + var idx = 0 + while idx < q.count { + let i = q[idx] + idx += 1 + for j in g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1 + q.append(j) + } + } + } + return dist + } + + let d1 = f(node1) + let d2 = f(node2) + var ans = -1, d = inf + for i in 0.. ; - auto dijkstra = [&](int i) { + auto f = [&](int i) { vector dist(n, inf); dist[i] = 0; - priority_queue , greater > q; - q.emplace(0, i); + queue q{{i}}; while (!q.empty()) { - auto p = q.top(); + i = q.front(); q.pop(); - i = p.second; for (int j : g[i]) { - if (dist[j] > dist[i] + 1) { + if (dist[j] == inf) { dist[j] = dist[i] + 1; - q.emplace(dist[j], j); + q.push(j); } } } return dist; }; - vector d1 = dijkstra(node1); - vector d2 = dijkstra(node2); + vector d1 = f(node1); + vector d2 = f(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { int t = max(d1[i], d2[i]); diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.cs b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.cs new file mode 100644 index 0000000000000..ab53e947041f1 --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.cs @@ -0,0 +1,41 @@ +public class Solution { + public int ClosestMeetingNode(int[] edges, int node1, int node2) { + int n = edges.Length; + List [] g = new List [n]; + for (int i = 0; i < n; ++i) { + g[i] = new List (); + if (edges[i] != -1) { + g[i].Add(edges[i]); + } + } + int inf = 1 << 30; + int[] f(int i) { + int[] dist = new int[n]; + Array.Fill(dist, inf); + dist[i] = 0; + Queue q = new Queue (); + q.Enqueue(i); + while (q.Count > 0) { + i = q.Dequeue(); + foreach (int j in g[i]) { + if (dist[j] == inf) { + dist[j] = dist[i] + 1; + q.Enqueue(j); + } + } + } + return dist; + } + int[] d1 = f(node1); + int[] d2 = f(node2); + int ans = -1, d = inf; + for (int i = 0; i < n; ++i) { + int t = Math.Max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } +} diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.go b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.go index 052996ec8a859..2942464df6754 100644 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.go +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.go @@ -7,27 +7,27 @@ func closestMeetingNode(edges []int, node1 int, node2 int) int { } } const inf int = 1 << 30 - dijkstra := func(i int) []int { + f := func(i int) []int { dist := make([]int, n) for j := range dist { dist[j] = inf } dist[i] = 0 - q := hp{} - heap.Push(&q, pair{0, i}) + q := []int{i} for len(q) > 0 { - i := heap.Pop(&q).(pair).i + i = q[0] + q = q[1:] for _, j := range g[i] { - if dist[j] > dist[i]+1 { + if dist[j] == inf { dist[j] = dist[i] + 1 - heap.Push(&q, pair{dist[j], j}) + q = append(q, j) } } } return dist } - d1 := dijkstra(node1) - d2 := dijkstra(node2) + d1 := f(node1) + d2 := f(node2) ans, d := -1, inf for i, a := range d1 { b := d2[i] @@ -38,13 +38,4 @@ func closestMeetingNode(edges []int, node1 int, node2 int) int { } } return ans -} - -type pair struct{ d, i int } -type hp []pair - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { return h[i].d < h[j].d } -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } \ No newline at end of file +} \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.java b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.java index 0b0ec4b25ebc3..6cb9c23907765 100644 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.java +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.java @@ -11,8 +11,8 @@ public int closestMeetingNode(int[] edges, int node1, int node2) { g[i].add(edges[i]); } } - int[] d1 = dijkstra(node1); - int[] d2 = dijkstra(node2); + int[] d1 = f(node1); + int[] d2 = f(node2); int d = 1 << 30; int ans = -1; for (int i = 0; i < n; ++i) { @@ -25,19 +25,18 @@ public int closestMeetingNode(int[] edges, int node1, int node2) { return ans; } - private int[] dijkstra(int i) { + private int[] f(int i) { int[] dist = new int[n]; Arrays.fill(dist, 1 << 30); dist[i] = 0; - PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); - q.offer(new int[] {0, i}); + Deque q = new ArrayDeque<>(); + q.offer(i); while (!q.isEmpty()) { - var p = q.poll(); - i = p[1]; + i = q.poll(); for (int j : g[i]) { - if (dist[j] > dist[i] + 1) { + if (dist[j] == 1 << 30) { dist[j] = dist[i] + 1; - q.offer(new int[] {dist[j], j}); + q.offer(j); } } } diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.py b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.py index 69e4b10c9ea89..d6b338ca128d3 100644 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.py +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.py @@ -1,15 +1,15 @@ class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def dijkstra(i): + def f(i): dist = [inf] * n dist[i] = 0 - q = [(0, i)] + q = deque([i]) while q: - i = heappop(q)[1] + i = q.popleft() for j in g[i]: - if dist[j] > dist[i] + 1: + if dist[j] == inf: dist[j] = dist[i] + 1 - heappush(q, (dist[j], j)) + q.append(j) return dist g = defaultdict(list) @@ -17,8 +17,8 @@ def dijkstra(i): if j != -1: g[i].append(j) n = len(edges) - d1 = dijkstra(node1) - d2 = dijkstra(node2) + d1 = f(node1) + d2 = f(node2) ans, d = -1, inf for i, (a, b) in enumerate(zip(d1, d2)): if (t := max(a, b)) < d: diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.rs b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.rs new file mode 100644 index 0000000000000..6adeeb6babc8e --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.rs @@ -0,0 +1,42 @@ +use std::collections::VecDeque; + +impl Solution { + pub fn closest_meeting_node(edges: Vec , node1: i32, node2: i32) -> i32 { + let n = edges.len(); + let mut g = vec![Vec::new(); n]; + for i in 0..n { + if edges[i] != -1 { + g[i].push(edges[i] as usize); + } + } + let inf = 1 << 30; + let f = |mut i: usize| -> Vec { + let mut dist = vec![inf; n]; + dist[i] = 0; + let mut q = VecDeque::new(); + q.push_back(i); + while !q.is_empty() { + i = q.pop_front().unwrap(); + for &j in &g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1; + q.push_back(j); + } + } + } + dist + }; + let d1 = f(node1 as usize); + let d2 = f(node2 as usize); + let mut ans = -1; + let mut d = inf; + for i in 0..n { + let t = std::cmp::max(d1[i], d2[i]); + if t < d { + d = t; + ans = i as i32; + } + } + ans + } +} diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.swift b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.swift new file mode 100644 index 0000000000000..666d11d928ec2 --- /dev/null +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.swift @@ -0,0 +1,42 @@ +class Solution { + func closestMeetingNode(_ edges: [Int], _ node1: Int, _ node2: Int) -> Int { + let n = edges.count + var g = [[Int]](repeating: [], count: n) + for i in 0.. [Int] { + var dist = [Int](repeating: inf, count: n) + dist[i] = 0 + var q = [i] + var idx = 0 + while idx < q.count { + let i = q[idx] + idx += 1 + for j in g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1 + q.append(j) + } + } + } + return dist + } + + let d1 = f(node1) + let d2 = f(node2) + var ans = -1, d = inf + for i in 0.. & edges, int node1, int node2) { - int n = edges.size(); - vector > g(n); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].push_back(edges[i]); - } - } - const int inf = 1 << 30; - using pii = pair ; - auto f = [&](int i) { - vector dist(n, inf); - dist[i] = 0; - queue q{{i}}; - while (!q.empty()) { - i = q.front(); - q.pop(); - for (int j : g[i]) { - if (dist[j] == inf) { - dist[j] = dist[i] + 1; - q.push(j); - } - } - } - return dist; - }; - vector d1 = f(node1); - vector d2 = f(node2); - int ans = -1, d = inf; - for (int i = 0; i < n; ++i) { - int t = max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } -}; \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.go b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.go deleted file mode 100644 index 2942464df6754..0000000000000 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.go +++ /dev/null @@ -1,41 +0,0 @@ -func closestMeetingNode(edges []int, node1 int, node2 int) int { - n := len(edges) - g := make([][]int, n) - for i, j := range edges { - if j != -1 { - g[i] = append(g[i], j) - } - } - const inf int = 1 << 30 - f := func(i int) []int { - dist := make([]int, n) - for j := range dist { - dist[j] = inf - } - dist[i] = 0 - q := []int{i} - for len(q) > 0 { - i = q[0] - q = q[1:] - for _, j := range g[i] { - if dist[j] == inf { - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - } - return dist - } - d1 := f(node1) - d2 := f(node2) - ans, d := -1, inf - for i, a := range d1 { - b := d2[i] - t := max(a, b) - if t < d { - d = t - ans = i - } - } - return ans -} \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.java b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.java deleted file mode 100644 index 6cb9c23907765..0000000000000 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.java +++ /dev/null @@ -1,45 +0,0 @@ -class Solution { - private int n; - private List [] g; - - public int closestMeetingNode(int[] edges, int node1, int node2) { - n = edges.length; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].add(edges[i]); - } - } - int[] d1 = f(node1); - int[] d2 = f(node2); - int d = 1 << 30; - int ans = -1; - for (int i = 0; i < n; ++i) { - int t = Math.max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } - - private int[] f(int i) { - int[] dist = new int[n]; - Arrays.fill(dist, 1 << 30); - dist[i] = 0; - Deque q = new ArrayDeque<>(); - q.offer(i); - while (!q.isEmpty()) { - i = q.poll(); - for (int j : g[i]) { - if (dist[j] == 1 << 30) { - dist[j] = dist[i] + 1; - q.offer(j); - } - } - } - return dist; - } -} \ No newline at end of file diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.py b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.py deleted file mode 100644 index d6b338ca128d3..0000000000000 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution2.py +++ /dev/null @@ -1,27 +0,0 @@ -class Solution: - def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def f(i): - dist = [inf] * n - dist[i] = 0 - q = deque([i]) - while q: - i = q.popleft() - for j in g[i]: - if dist[j] == inf: - dist[j] = dist[i] + 1 - q.append(j) - return dist - - g = defaultdict(list) - for i, j in enumerate(edges): - if j != -1: - g[i].append(j) - n = len(edges) - d1 = f(node1) - d2 = f(node2) - ans, d = -1, inf - for i, (a, b) in enumerate(zip(d1, d2)): - if (t := max(a, b)) < d: - d = t - ans = i - return ans diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md index 6c1e3b08fc26e..4a33472fc96d8 100644 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md @@ -82,13 +82,13 @@ tags: 题目可以转化为,给定一个字符串序列,在借助一个辅助栈的情况下,将其转化为字典序最小的字符串序列。 -我们可以用数组 `cnt` 维护字符串 $s$ 中每个字符的出现次数,用栈 `stk` 作为题目中的辅助栈,用变量 `mi` 维护还未遍历到的字符串中最小的字符。 +我们可以用数组 $\textit{cnt}$ 维护字符串 $s$ 中每个字符的出现次数,用栈 $\textit{stk}$ 作为题目中的辅助栈,用变量 $\textit{mi}$ 维护还未遍历到的字符串中最小的字符。 -遍历字符串 $s$,对于每个字符 $c$,我们先将字符 $c$ 在数组 `cnt` 中的出现次数减一,更新 `mi`。然后将字符 $c$ 入栈,此时如果栈顶元素小于等于 `mi`,则循环将栈顶元素出栈,并将出栈的字符加入答案。 +遍历字符串 $s$,对于每个字符 $c$,我们先将字符 $c$ 在数组 $\textit{cnt}$ 中的出现次数减一,更新 $\textit{mi}$。然后将字符 $c$ 入栈,此时如果栈顶元素小于等于 $\textit{mi}$,则循环将栈顶元素出栈,并将出栈的字符加入答案。 遍历结束,返回答案即可。 -时间复杂度 $O(n+C)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 为字符集大小,本题中 $C=26$。 +时间复杂度 $O(n + |\Sigma|)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度,而 $|\Sigma|$ 为字符集大小,本题中 $|\Sigma| = 26$。 @@ -193,101 +193,59 @@ func robotWithString(s string) string { ```ts function robotWithString(s: string): string { - let cnt = new Array(128).fill(0); - for (let c of s) cnt[c.charCodeAt(0)] += 1; - let min_index = 'a'.charCodeAt(0); - let ans = []; - let stack = []; - for (let c of s) { - cnt[c.charCodeAt(0)] -= 1; - while (min_index <= 'z'.charCodeAt(0) && cnt[min_index] == 0) { - min_index += 1; + const cnt = new Map (); + for (const c of s) { + cnt.set(c, (cnt.get(c) || 0) + 1); + } + const ans: string[] = []; + const stk: string[] = []; + let mi = 'a'; + for (const c of s) { + cnt.set(c, (cnt.get(c) || 0) - 1); + while (mi < 'z' && (cnt.get(mi) || 0) === 0) { + mi = String.fromCharCode(mi.charCodeAt(0) + 1); } - stack.push(c); - while (stack.length > 0 && stack[stack.length - 1].charCodeAt(0) <= min_index) { - ans.push(stack.pop()); + stk.push(c); + while (stk.length > 0 && stk[stk.length - 1] <= mi) { + ans.push(stk.pop()!); } } return ans.join(''); } ``` - - - - - - -### 方法二 - - - -#### Python3 - -```python -class Solution: - def robotWithString(self, s: str) -> str: - n = len(s) - right = [chr(ord('z') + 1)] * (n + 1) - for i in range(n - 1, -1, -1): - right[i] = min(s[i], right[i + 1]) - ans = [] - stk = [] - for i, c in enumerate(s): - stk.append(c) - while stk and stk[-1] <= right[i + 1]: - ans.append(stk.pop()) - return ''.join(ans) -``` - -#### Java +#### Rust -```java -class Solution { - public String robotWithString(String s) { - int n = s.length(); - int[] right = new int[n]; - right[n - 1] = n - 1; - for (int i = n - 2; i >= 0; --i) { - right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; +```rust +impl Solution { + pub fn robot_with_string(s: String) -> String { + let mut cnt = [0; 26]; + for &c in s.as_bytes() { + cnt[(c - b'a') as usize] += 1; } - StringBuilder ans = new StringBuilder(); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - stk.push(s.charAt(i)); - while ( - !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { - ans.append(stk.pop()); - } - } - return ans.toString(); - } -} -``` -#### C++ + let mut ans = Vec::with_capacity(s.len()); + let mut stk = Vec::new(); + let mut mi = 0; -```cpp -class Solution { -public: - string robotWithString(string s) { - int n = s.size(); - vector right(n, n - 1); - for (int i = n - 2; i >= 0; --i) { - right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; - } - string ans; - string stk; - for (int i = 0; i < n; ++i) { - stk += s[i]; - while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { - ans += stk.back(); - stk.pop_back(); + for &c in s.as_bytes() { + cnt[(c - b'a') as usize] -= 1; + while mi < 26 && cnt[mi] == 0 { + mi += 1; + } + stk.push(c); + while let Some(&top) = stk.last() { + if (top - b'a') as usize <= mi { + ans.push(stk.pop().unwrap()); + } else { + break; + } } } - return ans; + + String::from_utf8(ans).unwrap() } -}; +} ``` diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md index 028be62ce4fdd..c75b8577212a3 100644 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md @@ -81,15 +81,15 @@ Perform second operation four times p="addb", s="", t=" ### Solution 1: Greedy + Stack -The problem can be transformed into, given a string sequence, convert it into the lexicographically smallest string sequence with the help of an auxiliary stack. +The problem can be transformed into: given a string sequence, use an auxiliary stack to convert it into the lexicographically smallest string sequence. -We can use an array `cnt` to maintain the occurrence count of each character in string $s$, use a stack `stk` as the auxiliary stack in the problem, and use a variable `mi` to maintain the smallest character in the string that has not been traversed yet. +We can use an array $\textit{cnt}$ to maintain the count of each character in string $s$, use a stack $\textit{stk}$ as the auxiliary stack mentioned in the problem, and use a variable $\textit{mi}$ to keep track of the smallest character not yet traversed in the string. -Traverse the string $s$, for each character $c$, we first decrement the occurrence count of character $c$ in array `cnt`, and update `mi`. Then push character $c$ into the stack. At this point, if the top element of the stack is less than or equal to `mi`, then loop to pop the top element of the stack, and add the popped character to the answer. +Traverse the string $s$. For each character $c$, first decrement its count in the array $\textit{cnt}$ and update $\textit{mi}$. Then push $c$ onto the stack. At this point, if the top element of the stack is less than or equal to $\textit{mi}$, repeatedly pop the top element from the stack and add it to the answer. -After the traversal ends, return the answer. +After the traversal, return the answer. -The time complexity is $O(n+C)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$, and $C$ is the size of the character set, in this problem $C=26$. +The time complexity is $O(n + |\Sigma|)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$ and $|\Sigma|$ is the size of the character set, which is $26$ in this problem. @@ -194,101 +194,59 @@ func robotWithString(s string) string { ```ts function robotWithString(s: string): string { - let cnt = new Array(128).fill(0); - for (let c of s) cnt[c.charCodeAt(0)] += 1; - let min_index = 'a'.charCodeAt(0); - let ans = []; - let stack = []; - for (let c of s) { - cnt[c.charCodeAt(0)] -= 1; - while (min_index <= 'z'.charCodeAt(0) && cnt[min_index] == 0) { - min_index += 1; + const cnt = new Map (); + for (const c of s) { + cnt.set(c, (cnt.get(c) || 0) + 1); + } + const ans: string[] = []; + const stk: string[] = []; + let mi = 'a'; + for (const c of s) { + cnt.set(c, (cnt.get(c) || 0) - 1); + while (mi < 'z' && (cnt.get(mi) || 0) === 0) { + mi = String.fromCharCode(mi.charCodeAt(0) + 1); } - stack.push(c); - while (stack.length > 0 && stack[stack.length - 1].charCodeAt(0) <= min_index) { - ans.push(stack.pop()); + stk.push(c); + while (stk.length > 0 && stk[stk.length - 1] <= mi) { + ans.push(stk.pop()!); } } return ans.join(''); } ``` - - - - - - -### Solution 2 - - - -#### Python3 - -```python -class Solution: - def robotWithString(self, s: str) -> str: - n = len(s) - right = [chr(ord('z') + 1)] * (n + 1) - for i in range(n - 1, -1, -1): - right[i] = min(s[i], right[i + 1]) - ans = [] - stk = [] - for i, c in enumerate(s): - stk.append(c) - while stk and stk[-1] <= right[i + 1]: - ans.append(stk.pop()) - return ''.join(ans) -``` - -#### Java +#### Rust -```java -class Solution { - public String robotWithString(String s) { - int n = s.length(); - int[] right = new int[n]; - right[n - 1] = n - 1; - for (int i = n - 2; i >= 0; --i) { - right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; +```rust +impl Solution { + pub fn robot_with_string(s: String) -> String { + let mut cnt = [0; 26]; + for &c in s.as_bytes() { + cnt[(c - b'a') as usize] += 1; } - StringBuilder ans = new StringBuilder(); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - stk.push(s.charAt(i)); - while ( - !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { - ans.append(stk.pop()); - } - } - return ans.toString(); - } -} -``` -#### C++ + let mut ans = Vec::with_capacity(s.len()); + let mut stk = Vec::new(); + let mut mi = 0; -```cpp -class Solution { -public: - string robotWithString(string s) { - int n = s.size(); - vector right(n, n - 1); - for (int i = n - 2; i >= 0; --i) { - right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; - } - string ans; - string stk; - for (int i = 0; i < n; ++i) { - stk += s[i]; - while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { - ans += stk.back(); - stk.pop_back(); + for &c in s.as_bytes() { + cnt[(c - b'a') as usize] -= 1; + while mi < 26 && cnt[mi] == 0 { + mi += 1; + } + stk.push(c); + while let Some(&top) = stk.last() { + if (top - b'a') as usize <= mi { + ans.push(stk.pop().unwrap()); + } else { + break; + } } } - return ans; + + String::from_utf8(ans).unwrap() } -}; +} ``` diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.rs b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.rs new file mode 100644 index 0000000000000..196fe12afcb03 --- /dev/null +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn robot_with_string(s: String) -> String { + let mut cnt = [0; 26]; + for &c in s.as_bytes() { + cnt[(c - b'a') as usize] += 1; + } + + let mut ans = Vec::with_capacity(s.len()); + let mut stk = Vec::new(); + let mut mi = 0; + + for &c in s.as_bytes() { + cnt[(c - b'a') as usize] -= 1; + while mi < 26 && cnt[mi] == 0 { + mi += 1; + } + stk.push(c); + while let Some(&top) = stk.last() { + if (top - b'a') as usize <= mi { + ans.push(stk.pop().unwrap()); + } else { + break; + } + } + } + + String::from_utf8(ans).unwrap() + } +} diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.ts b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.ts index a5d7abd536797..a2ace8e318f4d 100644 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.ts +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.ts @@ -1,17 +1,19 @@ function robotWithString(s: string): string { - let cnt = new Array(128).fill(0); - for (let c of s) cnt[c.charCodeAt(0)] += 1; - let min_index = 'a'.charCodeAt(0); - let ans = []; - let stack = []; - for (let c of s) { - cnt[c.charCodeAt(0)] -= 1; - while (min_index <= 'z'.charCodeAt(0) && cnt[min_index] == 0) { - min_index += 1; + const cnt = new Map (); + for (const c of s) { + cnt.set(c, (cnt.get(c) || 0) + 1); + } + const ans: string[] = []; + const stk: string[] = []; + let mi = 'a'; + for (const c of s) { + cnt.set(c, (cnt.get(c) || 0) - 1); + while (mi < 'z' && (cnt.get(mi) || 0) === 0) { + mi = String.fromCharCode(mi.charCodeAt(0) + 1); } - stack.push(c); - while (stack.length > 0 && stack[stack.length - 1].charCodeAt(0) <= min_index) { - ans.push(stack.pop()); + stk.push(c); + while (stk.length > 0 && stk[stk.length - 1] <= mi) { + ans.push(stk.pop()!); } } return ans.join(''); diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.cpp b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.cpp deleted file mode 100644 index 52342943adfa6..0000000000000 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - string robotWithString(string s) { - int n = s.size(); - vector right(n, n - 1); - for (int i = n - 2; i >= 0; --i) { - right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; - } - string ans; - string stk; - for (int i = 0; i < n; ++i) { - stk += s[i]; - while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { - ans += stk.back(); - stk.pop_back(); - } - } - return ans; - } -}; \ No newline at end of file diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.java b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.java deleted file mode 100644 index fb44e686de474..0000000000000 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.java +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { - public String robotWithString(String s) { - int n = s.length(); - int[] right = new int[n]; - right[n - 1] = n - 1; - for (int i = n - 2; i >= 0; --i) { - right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; - } - StringBuilder ans = new StringBuilder(); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - stk.push(s.charAt(i)); - while ( - !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { - ans.append(stk.pop()); - } - } - return ans.toString(); - } -} \ No newline at end of file diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.py b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.py deleted file mode 100644 index 2765d7590b32f..0000000000000 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution2.py +++ /dev/null @@ -1,13 +0,0 @@ -class Solution: - def robotWithString(self, s: str) -> str: - n = len(s) - right = [chr(ord('z') + 1)] * (n + 1) - for i in range(n - 1, -1, -1): - right[i] = min(s[i], right[i + 1]) - ans = [] - stk = [] - for i, c in enumerate(s): - stk.append(c) - while stk and stk[-1] <= right[i + 1]: - ans.append(stk.pop()) - return ''.join(ans) diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md index b0e15a6ef5fb0..90951ded0a45b 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md @@ -66,17 +66,17 @@ tags: ### 方法一:枚举右端点 -由题意,我们可以知道,定界子数组的所有元素都在区间 `[minK, maxK]` 中,且最小值一定为 `minK`,最大值一定为 `maxK`。 +由题意,我们可以知道,定界子数组的所有元素都在区间 $[\textit{minK}, \textit{maxK}]$ 中,且最小值一定为 $\textit{minK}$,最大值一定为 $\textit{maxK}$。 -我们遍历数组 $nums$,统计以 `nums[i]` 为右端点的定界子数组的个数,然后将所有的个数相加即可。 +我们遍历数组 $\textit{nums}$,统计以 $\textit{nums}[i]$ 为右端点的定界子数组的个数,然后将所有的个数相加即可。 具体实现逻辑如下: -1. 维护最近一个不在区间 `[minK, maxK]` 中的元素的下标 $k$,初始值为 $-1$。那么当前元素 `nums[i]` 的左端点一定大于 $k$。 -1. 维护最近一个值为 `minK` 的下标 $j_1$,最近一个值为 `maxK` 的下标 $j_2$,初始值均为 $-1$。那么当前元素 `nums[i]` 的左端点一定小于等于 $\min(j_1, j_2)$。 -1. 综上可知,以当前元素为右端点的定界子数组的个数为 $\max(0, \min(j_1, j_2) - k)$。累加所有的个数即可。 +1. 维护最近一个不在区间 $[\textit{minK}, \textit{maxK}]$ 中的元素的下标 $k$,初始值为 $-1$。那么当前元素 $\textit{nums}[i]$ 的左端点一定大于 $k$。 +2. 维护最近一个值为 $\textit{minK}$ 的下标 $j_1$,最近一个值为 $\textit{maxK}$ 的下标 $j_2$,初始值均为 $-1$。那么当前元素 $\textit{nums}[i]$ 的左端点一定小于等于 $\min(j_1, j_2)$。 +3. 综上可知,以当前元素为右端点的定界子数组的个数为 $\max\bigl(0,\ \min(j_1, j_2) - k\bigr)$。累加所有的个数即可。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组 $\textit{nums}$ 的长度。空间复杂度 $O(1)$。 @@ -130,10 +130,16 @@ public: long long countSubarrays(vector