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..fcb48f7b9e1d6 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/0100-0199/0195.Tenth Line/README_EN.md b/solution/0100-0199/0195.Tenth Line/README_EN.md index 7ca9f7187d210..69bdfb2395242 100644 --- a/solution/0100-0199/0195.Tenth Line/README_EN.md +++ b/solution/0100-0199/0195.Tenth Line/README_EN.md @@ -23,26 +23,41 @@ tags:Assume that file.txt
has the following content:
+ Line 1 + Line 2 + Line 3 + Line 4 + Line 5 + Line 6 + Line 7 + Line 8 + Line 9 + Line 10 +
Your script should output the tenth line, which is:
+ Line 10 +
-
表: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/0700-0799/0799.Champagne Tower/README_EN.md b/solution/0700-0799/0799.Champagne Tower/README_EN.md index 7c1df1e554754..c04fa21334900 100644 --- a/solution/0700-0799/0799.Champagne Tower/README_EN.md +++ b/solution/0700-0799/0799.Champagne Tower/README_EN.md @@ -27,35 +27,51 @@ tags:Now after pouring some non-negative integer cups of champagne, return how full the jth
glass in the ith
row is (both i
and j
are 0-indexed.)
+
Example 1:
+ Input: poured = 1, query_row = 1, query_glass = 1 + Output: 0.00000 + Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. +
Example 2:
+ Input: poured = 2, query_row = 1, query_glass = 1 + Output: 0.50000 + Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. +
Example 3:
+ Input: poured = 100000009, query_row = 33, query_glass = 17 + Output: 1.00000 +
+
Constraints:
0 <= poured <= 109
0 <= query_glass <= query_row < 100
0 <= poured <= 109
0 <= query_glass <= query_row < 100
有一个有 n
个节点的有向图,节点按 0
到 n - 1
编号。图由一个 索引从 0 开始 的 2D 整数数组 graph
表示, graph[i]
是与节点 i
相邻的节点的整数数组,这意味着从节点 i
到 graph[i]
中的每个节点都有一条边。
如果一个节点没有连出的有向边,则该节点是 终端节点 。如果从该节点开始的所有可能路径都通向 终端节点 ,则该节点为 安全节点 。
+如果一个节点没有连出的有向边,则该节点是 终端节点 。如果从该节点开始的所有可能路径都通向 终端节点 ,则该节点为 终端节点(或另一个安全节点)。
返回一个由图中所有 安全节点 组成的数组作为答案。答案数组中的元素应当按 升序 排列。
diff --git a/solution/0800-0899/0819.Most Common Word/README.md b/solution/0800-0899/0819.Most Common Word/README.md index f3adddcb4620e..20a453ae26ab5 100644 --- a/solution/0800-0899/0819.Most Common Word/README.md +++ b/solution/0800-0899/0819.Most Common Word/README.md @@ -23,6 +23,8 @@ tags:paragraph
中的单词 不区分大小写 ,答案应以 小写 形式返回。
注意 单词不包含标点符号。
+
示例 1:
diff --git a/solution/0800-0899/0819.Most Common Word/README_EN.md b/solution/0800-0899/0819.Most Common Word/README_EN.md index ebcacda3c5c8e..2aae27ab03f78 100644 --- a/solution/0800-0899/0819.Most Common Word/README_EN.md +++ b/solution/0800-0899/0819.Most Common Word/README_EN.md @@ -23,6 +23,8 @@ tags:The words in paragraph
are case-insensitive and the answer should be returned in lowercase.
Note that words can not contain punctuation symbols.
+
Example 1:
diff --git a/solution/0800-0899/0838.Push Dominoes/README.md b/solution/0800-0899/0838.Push Dominoes/README.md index e6f79c7abba0b..d37d4feea673e 100644 --- a/solution/0800-0899/0838.Push Dominoes/README.md +++ b/solution/0800-0899/0838.Push Dominoes/README.md @@ -68,7 +68,30 @@ tags: -### 方法一 +### 方法一:多源 BFS + +把所有初始受到推力的骨牌(`L` 或 `R`)视作 **源点**,它们会同时向外扩散各自的力。用队列按时间层级(0, 1, 2 …)进行 BFS: + +我们定义 $\text{time[i]}$ 记录第 *i* 张骨牌第一次受力的时刻,`-1` 表示尚未受力,定义 $\text{force[i]}$ 是一个长度可变的列表,存放该骨牌在同一时刻收到的方向(`'L'`、`'R'`)。初始时把所有 `L/R` 的下标压入队列,并将它们的时间置 0。 + +当弹出下标 *i* 时,若 $\text{force[i]}$ 只有一个方向,骨牌就会倒向该方向 $f$。设下一张骨牌下标为 + +$$ +j = +\begin{cases} +i - 1, & f = L,\\ +i + 1, & f = R. +\end{cases} +$$ + +若 $0 \leq j < n$: + +- 若 $\text{time[j]}=-1$,说明 *j* 从未受力,记录 $\text{time[j]}=\text{time[i]}+1$ 并入队,同时把 $f$ 写入 $\text{force[j]}$。 +- 若 $\text{time[j]}=\text{time[i]}+1$,说明它在同一“下一刻”已受过另一股力,此时只把 $f$ 追加到 $\text{force[j]}$,形成对冲;后续因 `len(force[j])==2`,它将保持竖直。 + +队列清空后,所有 $\text{force[i]}$ 长度为 1 的位置倒向对应方向;长度为 2 的位置保持 `.`。最终将字符数组拼接为答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是骨牌的数量。 @@ -242,44 +265,40 @@ func pushDominoes(dominoes string) string { ```ts function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } ``` diff --git a/solution/0800-0899/0838.Push Dominoes/README_EN.md b/solution/0800-0899/0838.Push Dominoes/README_EN.md index ce232677d18a7..ec5ef4c80d36c 100644 --- a/solution/0800-0899/0838.Push Dominoes/README_EN.md +++ b/solution/0800-0899/0838.Push Dominoes/README_EN.md @@ -67,7 +67,30 @@ tags: -### Solution 1 +### Solution 1: Multi-Source BFS + +Treat all initially pushed dominoes (`L` or `R`) as **sources**, which simultaneously propagate their forces outward. Use a queue to perform BFS layer by layer (0, 1, 2, ...): + +We define $\text{time[i]}$ to record the first moment when the _i_-th domino is affected by a force, with `-1` indicating it has not been affected yet. We also define $\text{force[i]}$ as a variable-length list that stores the directions (`'L'`, `'R'`) of forces acting on the domino at the same moment. Initially, push all indices of `L/R` dominoes into the queue and set their `time` to 0. + +When dequeuing index _i_, if $\text{force[i]}$ contains only one direction, the domino will fall in that direction $f$. Let the index of the next domino be: + +$$ +j = +\begin{cases} +i - 1, & f = L,\\ +i + 1, & f = R. +\end{cases} +$$ + +If $0 \leq j < n$: + +- If $\text{time[j]} = -1$, it means _j_ has not been affected yet. Record $\text{time[j]} = \text{time[i]} + 1$, enqueue it, and append $f$ to $\text{force[j]}$. +- If $\text{time[j]} = \text{time[i]} + 1$, it means _j_ has already been affected by another force at the same "next moment." In this case, append $f$ to $\text{force[j]}$, causing a standoff. Subsequently, since $\text{len(force[j])} = 2$, it will remain upright. + +After the queue is emptied, all positions where $\text{force[i]}$ has a length of 1 will fall in the corresponding direction, while positions with a length of 2 will remain as `.`. Finally, concatenate the character array to form the answer. + +The complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of dominoes. @@ -241,44 +264,40 @@ func pushDominoes(dominoes string) string { ```ts function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } ``` diff --git a/solution/0800-0899/0838.Push Dominoes/Solution.ts b/solution/0800-0899/0838.Push Dominoes/Solution.ts index d9e8412c5d062..0b912d31ca203 100644 --- a/solution/0800-0899/0838.Push Dominoes/Solution.ts +++ b/solution/0800-0899/0838.Push Dominoes/Solution.ts @@ -1,41 +1,37 @@ function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } diff --git a/solution/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/1108.Defanging an IP Address/README_EN.md b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md index d141c92ba6e45..537e7be2aa54c 100644 --- a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md +++ b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md @@ -23,18 +23,29 @@ tags:A defanged IP address replaces every period "."
with "[.]"
.
+
Example 1:
+Input: address = "1.1.1.1" + Output: "1[.]1[.]1[.]1" +
Example 2:
+Input: address = "255.100.50.0" + Output: "255[.]100[.]50[.]0" ++
+
Constraints:
address
is a valid IPv4 address.address
is a valid IPv4 address.A string is a valid parentheses string (denoted VPS) if and only if it consists of "("
and ")"
characters only, and:
AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.We can similarly define the nesting depth depth(S)
of any VPS S
as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.For example, ""
, "()()"
, and "()(()())"
are VPS's (with nesting depths 0, 1, and 2), and ")("
and "(()"
are not VPS's.
We may make the following moves:
'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.(Here, the only positions that exist on the board are positions with letters on them.)
@@ -40,19 +46,31 @@ tags:Return a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
+
Example 1:
+Input: target = "leet" + Output: "DDR!UURRR!!DDD!" +
Example 2:
+Input: target = "code" + Output: "RR!DDRR!UUL!R!" ++
+
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.1 <= target.length <= 100
target
consists only of English lowercase letters.Given a 2D grid
of 0
s and 1
s, return the number of elements in the largest square subgrid that has all 1
s on its border, or 0
if such a subgrid doesn't exist in the grid
.
+
Example 1:
+ Input: grid = [[1,1,1],[1,0,1],[1,1,1]] + Output: 9 +
Example 2:
+ Input: grid = [[1,1,0,0]] + Output: 1 +
+
Constraints:
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
-
请查询出所有浏览过自己文章的作者
+请查询出所有浏览过自己文章的作者。
-结果按照 id
升序排列。
结果按照作者的 id
升序排列。
查询结果的格式如下所示:
diff --git a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md index 6b9897e53caa4..d39c633d50950 100644 --- a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md +++ b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md @@ -21,13 +21,11 @@ tags: -给你一份『词汇表』(字符串数组) words
和一张『字母表』(字符串) chars
。
给定一个字符串数组 words
和一个字符串 chars
。
假如你可以用 chars
中的『字母』(字符)拼写出 words
中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
如果字符串可以由 chars
中的字符组成(每个字符在 每个 words
中只能使用一次),则认为它是好的。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars
中的每个字母都只能用一次。
返回词汇表 words
中你掌握的所有单词的 长度之和。
返回 words
中所有好的字符串的长度之和。
@@ -56,7 +54,7 @@ tags:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
words[i]
和 chars
中都仅包含小写英文字母You are given an array of strings words
and a string chars
.
A string is good if it can be formed by characters from chars
(each character can only be used once).
A string is good if it can be formed by characters from chars
(each character can only be used once for each word in words
).
Return the sum of lengths of all good strings in words.
diff --git a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md index d947861120f5a..b4e5e94f2f0f6 100644 --- a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md +++ b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md @@ -25,13 +25,17 @@ tags:Return the shortest distance between the given start
and destination
stops.
+
Example 1:
+ Input: distance = [1,2,3,4], start = 0, destination = 1 + Output: 1 + Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
@@ -41,9 +45,13 @@ tags:
+ Input: distance = [1,2,3,4], start = 0, destination = 2 + Output: 3 + Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3. +
@@ -53,19 +61,29 @@ tags:
+ Input: distance = [1,2,3,4], start = 0, destination = 3 + Output: 4 + Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4. +
+
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
Given 2 integers n
and start
. Your task is return any permutation p
of (0,1,2.....,2^n -1)
such that :
p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.+
Example 1:
+ Input: n = 2, start = 3 + Output: [3,2,0,1] + Explanation: The binary representation of the permutation is (11,10,00,01). + All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2] +
Example 2:
+ Input: n = 3, start = 2 + Output: [2,6,7,5,4,0,1,3] + Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011). +
+
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n
1 <= n <= 16
0 <= start < 2 ^ n
+
Example 1:
+ Input: num = 23 + Output: "1000" +
Example 2:
+ Input: num = 107 + Output: "101100" +
+
Constraints:
0 <= num <= 10^9
0 <= num <= 10^9
给你一些区域列表 regions
,每个列表的第一个区域都包含这个列表内所有其他区域。
给你一些区域列表 regions
,每个列表的第一个区域都 直接 包含这个列表内所有其他区域。
如果一个区域 x
直接包含区域 y
,并且区域 y
直接包含区域 z
,那么说区域 x
间接 包含区域 z
。请注意,区域 x
也 间接 包含所有在 y
中 间接 包含的区域。
很自然地,如果区域 x
包含区域 y
,那么区域 x
比区域 y
大。同时根据定义,区域 x
包含自身。
给定两个区域 region1
和 region2
,找到同时包含这两个区域的 最小 区域。
如果给定区域 r1
,r2
和 r3
,使得 r1
包含 r3
,那么数据保证 r2
不会包含 r3
。
数据同样保证最小区域一定存在。
diff --git a/solution/1200-1299/1257.Smallest Common Region/README_EN.md b/solution/1200-1299/1257.Smallest Common Region/README_EN.md index d5b52f58e36c7..2085a7c0a74a4 100644 --- a/solution/1200-1299/1257.Smallest Common Region/README_EN.md +++ b/solution/1200-1299/1257.Smallest Common Region/README_EN.md @@ -23,13 +23,13 @@ tags: -
You are given some lists of regions
where the first region of each list includes all other regions in that list.
You are given some lists of regions
where the first region of each list directly contains all other regions in that list.
Naturally, if a region x
contains another region y
then x
is bigger than y
. Also, by definition, a region x
contains itself.
If a region x
contains a region y
directly, and region y
contains region z
directly, then region x
is said to contain region z
indirectly. Note that region x
also indirectly contains all regions indirectly containd in y
.
Given two regions: region1
and region2
, return the smallest region that contains both of them.
Naturally, if a region x
contains (either directly or indirectly) another region y
, then x
is bigger than or equal to y
in size. Also, by definition, a region x
contains itself.
If you are given regions r1
, r2
, and r3
such that r1
includes r3
, it is guaranteed there is no r2
such that r2
includes r3
.
Given two regions: region1
and region2
, return the smallest region that contains both of them.
It is guaranteed the smallest region exists.
@@ -65,6 +65,7 @@ region2 = "New York"region1 != region2
regions[i][j]
, region1
, and region2
consist of English letters.给你一个整数数组 nums
,请你返回其中位数为 偶数 的数字的个数。
给你一个整数数组 nums
,请你返回其中包含 偶数 个数位的数字的个数。
@@ -131,6 +131,16 @@ function findNumbers(nums: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_numbers(nums: Vec
containedBoxes[i]
:整数,表示放在 box[i]
里的盒子所对应的下标。给你一个 initialBoxes
数组,表示你现在得到的盒子,你可以获得里面的糖果,也可以用盒子里的钥匙打开新的盒子,还可以继续探索从这个盒子里找到的其他盒子。
给你一个整数数组 initialBoxes
,包含你最初拥有的盒子。你可以拿走每个 已打开盒子 里的所有糖果,并且可以使用其中的钥匙去开启新的盒子,并且可以使用在其中发现的其他盒子。
请你按照上述规则,返回可以获得糖果的 最大数目 。
@@ -37,7 +37,8 @@ tags:示例 1:
-输入:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0] ++输入:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0] 输出:16 解释: 一开始你有盒子 0 。你将获得它里面的 7 个糖果和盒子 1 和 2。 @@ -48,7 +49,8 @@ tags:示例 2:
-输入:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0] ++输入:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0] 输出:6 解释: 你一开始拥有盒子 0 。打开它你可以找到盒子 1,2,3,4,5 和它们对应的钥匙。 @@ -57,19 +59,22 @@ tags:示例 3:
-输入:status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1] ++输入:status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1] 输出:1示例 4:
-输入:status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = [] ++输入:status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = [] 输出:0示例 5:
-输入:status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0] ++输入:status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0] 输出:7@@ -99,7 +104,24 @@ tags: -### 方法一:BFS +### 方法一:BFS + 哈希集合 + +题目给定一批盒子,每个盒子可能有状态(开/关)、糖果、钥匙、以及其他盒子。我们的目标是通过初始给定的一些盒子,尽可能多地打开更多盒子,并收集其中的糖果。可以通过获得钥匙来解锁新盒子,通过盒子中嵌套的盒子来获取更多资源。 + +我们采用 BFS 的方式模拟整个探索过程。 + +我们用一个队列 $q$ 表示当前可以访问的、**已经开启** 的盒子;用两个集合 $\textit{has}$ 和 $\textit{took}$ 分别记录**我们拥有的所有盒子**和**已经处理过的盒子**,防止重复。 + +初始时,将所有 $\textit{initialBoxes}$ 添加到 $\textit{has}$ 中,如果初始盒子状态为开启,立即加入队列 $\textit{q}$ 并累计糖果; + +然后进行 BFS,依次从 $\textit{q}$ 中取出盒子: + +- 获取盒子中的钥匙 $\textit{keys[box]}$,将能解锁的盒子加入队列; +- 收集盒子中包含的其他盒子 $\textit{containedBoxes[box]}$,如果状态是开启的且未处理过,则立即处理; + +每个盒子最多处理一次,糖果累计一次,最终返回总糖果数 $\textit{ans}$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是盒子的总数。 @@ -115,25 +137,31 @@ class Solution: containedBoxes: List[List[int]], initialBoxes: List[int], ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} - + q = deque() + has, took = set(initialBoxes), set() + ans = 0 + + for box in initialBoxes: + if status[box]: + q.append(box) + took.add(box) + ans += candies[box] while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) + box = q.popleft() + for k in keys[box]: + if not status[k]: + status[k] = 1 + if k in has and k not in took: + q.append(k) + took.add(k) + ans += candies[k] + + for b in containedBoxes[box]: + has.add(b) + if status[b] and b not in took: + q.append(b) + took.add(b) + ans += candies[b] return ans ``` @@ -143,35 +171,36 @@ class Solution: class Solution { public int maxCandies( int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; Dequeq = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); + Set has = new HashSet<>(); + Set took = new HashSet<>(); + int ans = 0; + for (int box : initialBoxes) { + has.add(box); + if (status[box] == 1) { + q.offer(box); + took.add(box); + ans += candies[box]; } } while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); + int box = q.poll(); + for (int k : keys[box]) { + if (status[k] == 0) { + status[k] = 1; + if (has.contains(k) && !took.contains(k)) { + q.offer(k); + took.add(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); + for (int b : containedBoxes[box]) { + has.add(b); + if (status[b] == 1 && !took.contains(b)) { + q.offer(b); + took.add(b); + ans += candies[b]; } } } @@ -185,40 +214,50 @@ class Solution { ```cpp class Solution { public: - int maxCandies(vector & status, vector & candies, vector >& keys, vector >& containedBoxes, vector & initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); + int maxCandies( + vector & status, + vector & candies, + vector >& keys, + vector >& containedBoxes, + vector & initialBoxes) { queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); + unordered_set has, took; + int ans = 0; + + for (int box : initialBoxes) { + has.insert(box); + if (status[box]) { + q.push(box); + took.insert(box); + ans += candies[box]; } } + while (!q.empty()) { - int i = q.front(); + int box = q.front(); q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); + + for (int k : keys[box]) { + if (!status[k]) { + status[k] = 1; + if (has.count(k) && !took.count(k)) { + q.push(k); + took.insert(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); + + for (int b : containedBoxes[box]) { + has.insert(b); + if (status[b] && !took.count(b)) { + q.push(b); + took.insert(b); + ans += candies[b]; } } } + return ans; } }; @@ -227,41 +266,147 @@ public: #### Go ```go -func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { - ans := 0 - n := len(status) - has := make([]bool, n) - took := make([]bool, n) - var q []int - for _, i := range initialBoxes { - has[i] = true - if status[i] == 1 { - ans += candies[i] - took[i] = true - q = append(q, i) +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) (ans int) { + q := []int{} + has := make(map[int]bool) + took := make(map[int]bool) + for _, box := range initialBoxes { + has[box] = true + if status[box] == 1 { + q = append(q, box) + took[box] = true + ans += candies[box] } } for len(q) > 0 { - i := q[0] + box := q[0] q = q[1:] - for _, k := range keys[i] { - status[k] = 1 - if has[k] && !took[k] { - ans += candies[k] - took[k] = true - q = append(q, k) + for _, k := range keys[box] { + if status[k] == 0 { + status[k] = 1 + if has[k] && !took[k] { + q = append(q, k) + took[k] = true + ans += candies[k] + } } } - for _, j := range containedBoxes[i] { - has[j] = true - if status[j] == 1 && !took[j] { - ans += candies[j] - took[j] = true - q = append(q, j) + for _, b := range containedBoxes[box] { + has[b] = true + if status[b] == 1 && !took[b] { + q = append(q, b) + took[b] = true + ans += candies[b] } } } - return ans + return +} +``` + +#### TypeScript + +```ts +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const q: number[] = []; + const has: Set = new Set(); + const took: Set = new Set(); + let ans = 0; + + for (const box of initialBoxes) { + has.add(box); + if (status[box] === 1) { + q.push(box); + took.add(box); + ans += candies[box]; + } + } + + while (q.length > 0) { + const box = q.pop()!; + + for (const k of keys[box]) { + if (status[k] === 0) { + status[k] = 1; + if (has.has(k) && !took.has(k)) { + q.push(k); + took.add(k); + ans += candies[k]; + } + } + } + + for (const b of containedBoxes[box]) { + has.add(b); + if (status[b] === 1 && !took.has(b)) { + q.push(b); + took.add(b); + ans += candies[b]; + } + } + } + + return ans; +} +``` + +#### Rust + +```rust +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn max_candies( + mut status: Vec , + candies: Vec , + keys: Vec >, + contained_boxes: Vec >, + initial_boxes: Vec , + ) -> i32 { + let mut q: VecDeque = VecDeque::new(); + let mut has: HashSet = HashSet::new(); + let mut took: HashSet = HashSet::new(); + let mut ans = 0; + + for &box_ in &initial_boxes { + has.insert(box_); + if status[box_ as usize] == 1 { + q.push_back(box_); + took.insert(box_); + ans += candies[box_ as usize]; + } + } + + while let Some(box_) = q.pop_front() { + for &k in &keys[box_ as usize] { + if status[k as usize] == 0 { + status[k as usize] = 1; + if has.contains(&k) && !took.contains(&k) { + q.push_back(k); + took.insert(k); + ans += candies[k as usize]; + } + } + } + + for &b in &contained_boxes[box_ as usize] { + has.insert(b); + if status[b as usize] == 1 && !took.contains(&b) { + q.push_back(b); + took.insert(b); + ans += candies[b as usize]; + } + } + } + + ans + } } ``` diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md index 206d86924e214..3e1c094f6f83d 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md @@ -79,7 +79,24 @@ The total number of candies will be 6. -### Solution 1 +### Solution 1: BFS + Hash Set + +The problem gives a set of boxes, each of which may have a state (open/closed), candies, keys, and other boxes inside. Our goal is to use the initially given boxes to open as many more boxes as possible and collect the candies inside. We can unlock new boxes by obtaining keys, and get more resources through boxes nested inside other boxes. + +We use BFS to simulate the entire exploration process. + +We use a queue $q$ to represent the currently accessible and **already opened** boxes; two sets, $\textit{has}$ and $\textit{took}$, are used to record **all boxes we own** and **boxes we have already processed**, to avoid duplicates. + +Initially, add all $\textit{initialBoxes}$ to $\textit{has}$. If an initial box is open, immediately add it to the queue $\textit{q}$ and accumulate its candies. + +Then perform BFS, taking boxes out of $\textit{q}$ one by one: + +- Obtain the keys in the box $\textit{keys[box]}$ and add any boxes that can be unlocked to the queue; +- Collect other boxes contained in the box $\textit{containedBoxes[box]}$. If a contained box is open and has not been processed, process it immediately; + +Each box is processed at most once, and candies are accumulated once. Finally, return the total number of candies $\textit{ans}$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the total number of boxes. @@ -95,25 +112,31 @@ class Solution: containedBoxes: List[List[int]], initialBoxes: List[int], ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} - + q = deque() + has, took = set(initialBoxes), set() + ans = 0 + + for box in initialBoxes: + if status[box]: + q.append(box) + took.add(box) + ans += candies[box] while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) + box = q.popleft() + for k in keys[box]: + if not status[k]: + status[k] = 1 + if k in has and k not in took: + q.append(k) + took.add(k) + ans += candies[k] + + for b in containedBoxes[box]: + has.add(b) + if status[b] and b not in took: + q.append(b) + took.add(b) + ans += candies[b] return ans ``` @@ -123,35 +146,36 @@ class Solution: class Solution { public int maxCandies( int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; Deque q = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); + Set has = new HashSet<>(); + Set took = new HashSet<>(); + int ans = 0; + for (int box : initialBoxes) { + has.add(box); + if (status[box] == 1) { + q.offer(box); + took.add(box); + ans += candies[box]; } } while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); + int box = q.poll(); + for (int k : keys[box]) { + if (status[k] == 0) { + status[k] = 1; + if (has.contains(k) && !took.contains(k)) { + q.offer(k); + took.add(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); + for (int b : containedBoxes[box]) { + has.add(b); + if (status[b] == 1 && !took.contains(b)) { + q.offer(b); + took.add(b); + ans += candies[b]; } } } @@ -165,40 +189,50 @@ class Solution { ```cpp class Solution { public: - int maxCandies(vector & status, vector & candies, vector >& keys, vector >& containedBoxes, vector & initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); + int maxCandies( + vector & status, + vector & candies, + vector >& keys, + vector >& containedBoxes, + vector & initialBoxes) { queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); + unordered_set has, took; + int ans = 0; + + for (int box : initialBoxes) { + has.insert(box); + if (status[box]) { + q.push(box); + took.insert(box); + ans += candies[box]; } } + while (!q.empty()) { - int i = q.front(); + int box = q.front(); q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); + + for (int k : keys[box]) { + if (!status[k]) { + status[k] = 1; + if (has.count(k) && !took.count(k)) { + q.push(k); + took.insert(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); + + for (int b : containedBoxes[box]) { + has.insert(b); + if (status[b] && !took.count(b)) { + q.push(b); + took.insert(b); + ans += candies[b]; } } } + return ans; } }; @@ -207,41 +241,147 @@ public: #### Go ```go -func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { - ans := 0 - n := len(status) - has := make([]bool, n) - took := make([]bool, n) - var q []int - for _, i := range initialBoxes { - has[i] = true - if status[i] == 1 { - ans += candies[i] - took[i] = true - q = append(q, i) +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) (ans int) { + q := []int{} + has := make(map[int]bool) + took := make(map[int]bool) + for _, box := range initialBoxes { + has[box] = true + if status[box] == 1 { + q = append(q, box) + took[box] = true + ans += candies[box] } } for len(q) > 0 { - i := q[0] + box := q[0] q = q[1:] - for _, k := range keys[i] { - status[k] = 1 - if has[k] && !took[k] { - ans += candies[k] - took[k] = true - q = append(q, k) + for _, k := range keys[box] { + if status[k] == 0 { + status[k] = 1 + if has[k] && !took[k] { + q = append(q, k) + took[k] = true + ans += candies[k] + } } } - for _, j := range containedBoxes[i] { - has[j] = true - if status[j] == 1 && !took[j] { - ans += candies[j] - took[j] = true - q = append(q, j) + for _, b := range containedBoxes[box] { + has[b] = true + if status[b] == 1 && !took[b] { + q = append(q, b) + took[b] = true + ans += candies[b] } } } - return ans + return +} +``` + +#### TypeScript + +```ts +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const q: number[] = []; + const has: Set = new Set(); + const took: Set = new Set(); + let ans = 0; + + for (const box of initialBoxes) { + has.add(box); + if (status[box] === 1) { + q.push(box); + took.add(box); + ans += candies[box]; + } + } + + while (q.length > 0) { + const box = q.pop()!; + + for (const k of keys[box]) { + if (status[k] === 0) { + status[k] = 1; + if (has.has(k) && !took.has(k)) { + q.push(k); + took.add(k); + ans += candies[k]; + } + } + } + + for (const b of containedBoxes[box]) { + has.add(b); + if (status[b] === 1 && !took.has(b)) { + q.push(b); + took.add(b); + ans += candies[b]; + } + } + } + + return ans; +} +``` + +#### Rust + +```rust +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn max_candies( + mut status: Vec , + candies: Vec , + keys: Vec >, + contained_boxes: Vec >, + initial_boxes: Vec , + ) -> i32 { + let mut q: VecDeque = VecDeque::new(); + let mut has: HashSet = HashSet::new(); + let mut took: HashSet = HashSet::new(); + let mut ans = 0; + + for &box_ in &initial_boxes { + has.insert(box_); + if status[box_ as usize] == 1 { + q.push_back(box_); + took.insert(box_); + ans += candies[box_ as usize]; + } + } + + while let Some(box_) = q.pop_front() { + for &k in &keys[box_ as usize] { + if status[k as usize] == 0 { + status[k as usize] = 1; + if has.contains(&k) && !took.contains(&k) { + q.push_back(k); + took.insert(k); + ans += candies[k as usize]; + } + } + } + + for &b in &contained_boxes[box_ as usize] { + has.insert(b); + if status[b as usize] == 1 && !took.contains(&b) { + q.push_back(b); + took.insert(b); + ans += candies[b as usize]; + } + } + } + + ans + } } ``` diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp index 7b85217a5a1f3..fffc87bc0c3df 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.cpp @@ -1,39 +1,49 @@ class Solution { public: - int maxCandies(vector & status, vector & candies, vector >& keys, vector >& containedBoxes, vector & initialBoxes) { - int ans = 0; - int n = status.size(); - vector has(n); - vector took(n); + int maxCandies( + vector & status, + vector & candies, + vector >& keys, + vector >& containedBoxes, + vector & initialBoxes) { queue q; - for (int& i : initialBoxes) { - has[i] = true; - if (status[i]) { - ans += candies[i]; - took[i] = true; - q.push(i); + unordered_set has, took; + int ans = 0; + + for (int box : initialBoxes) { + has.insert(box); + if (status[box]) { + q.push(box); + took.insert(box); + ans += candies[box]; } } + while (!q.empty()) { - int i = q.front(); + int box = q.front(); q.pop(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.push(k); + + for (int k : keys[box]) { + if (!status[k]) { + status[k] = 1; + if (has.count(k) && !took.count(k)) { + q.push(k); + took.insert(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] && !took[j]) { - ans += candies[j]; - took[j] = true; - q.push(j); + + for (int b : containedBoxes[box]) { + has.insert(b); + if (status[b] && !took.count(b)) { + q.push(b); + took.insert(b); + ans += candies[b]; } } } + return ans; } -}; \ No newline at end of file +}; diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go index 4ff69d070109e..610853ade8f02 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.go @@ -1,36 +1,36 @@ -func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { - ans := 0 - n := len(status) - has := make([]bool, n) - took := make([]bool, n) - var q []int - for _, i := range initialBoxes { - has[i] = true - if status[i] == 1 { - ans += candies[i] - took[i] = true - q = append(q, i) +func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) (ans int) { + q := []int{} + has := make(map[int]bool) + took := make(map[int]bool) + for _, box := range initialBoxes { + has[box] = true + if status[box] == 1 { + q = append(q, box) + took[box] = true + ans += candies[box] } } for len(q) > 0 { - i := q[0] + box := q[0] q = q[1:] - for _, k := range keys[i] { - status[k] = 1 - if has[k] && !took[k] { - ans += candies[k] - took[k] = true - q = append(q, k) + for _, k := range keys[box] { + if status[k] == 0 { + status[k] = 1 + if has[k] && !took[k] { + q = append(q, k) + took[k] = true + ans += candies[k] + } } } - for _, j := range containedBoxes[i] { - has[j] = true - if status[j] == 1 && !took[j] { - ans += candies[j] - took[j] = true - q = append(q, j) + for _, b := range containedBoxes[box] { + has[b] = true + if status[b] == 1 && !took[b] { + q = append(q, b) + took[b] = true + ans += candies[b] } } } - return ans -} \ No newline at end of file + return +} diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java index 3d9e243bfdfa3..d473b7305010c 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.java @@ -1,38 +1,39 @@ class Solution { public int maxCandies( int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) { - int ans = 0; - int n = status.length; - boolean[] has = new boolean[n]; - boolean[] took = new boolean[n]; Deque q = new ArrayDeque<>(); - for (int i : initialBoxes) { - has[i] = true; - if (status[i] == 1) { - ans += candies[i]; - took[i] = true; - q.offer(i); + Set has = new HashSet<>(); + Set took = new HashSet<>(); + int ans = 0; + for (int box : initialBoxes) { + has.add(box); + if (status[box] == 1) { + q.offer(box); + took.add(box); + ans += candies[box]; } } while (!q.isEmpty()) { - int i = q.poll(); - for (int k : keys[i]) { - status[k] = 1; - if (has[k] && !took[k]) { - ans += candies[k]; - took[k] = true; - q.offer(k); + int box = q.poll(); + for (int k : keys[box]) { + if (status[k] == 0) { + status[k] = 1; + if (has.contains(k) && !took.contains(k)) { + q.offer(k); + took.add(k); + ans += candies[k]; + } } } - for (int j : containedBoxes[i]) { - has[j] = true; - if (status[j] == 1 && !took[j]) { - ans += candies[j]; - took[j] = true; - q.offer(j); + for (int b : containedBoxes[box]) { + has.add(b); + if (status[b] == 1 && !took.contains(b)) { + q.offer(b); + took.add(b); + ans += candies[b]; } } } return ans; } -} \ No newline at end of file +} diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py index fe996159a7a50..2aed0b52ec7ef 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py @@ -7,23 +7,29 @@ def maxCandies( containedBoxes: List[List[int]], initialBoxes: List[int], ) -> int: - q = deque([i for i in initialBoxes if status[i] == 1]) - ans = sum(candies[i] for i in initialBoxes if status[i] == 1) - has = set(initialBoxes) - took = {i for i in initialBoxes if status[i] == 1} + q = deque() + has, took = set(initialBoxes), set() + ans = 0 + for box in initialBoxes: + if status[box]: + q.append(box) + took.add(box) + ans += candies[box] while q: - i = q.popleft() - for k in keys[i]: - status[k] = 1 - if k in has and k not in took: - ans += candies[k] - took.add(k) - q.append(k) - for j in containedBoxes[i]: - has.add(j) - if status[j] and j not in took: - ans += candies[j] - took.add(j) - q.append(j) + box = q.popleft() + for k in keys[box]: + if not status[k]: + status[k] = 1 + if k in has and k not in took: + q.append(k) + took.add(k) + ans += candies[k] + + for b in containedBoxes[box]: + has.add(b) + if status[b] and b not in took: + q.append(b) + took.add(b) + ans += candies[b] return ans diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.rs b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.rs new file mode 100644 index 0000000000000..852f702b4d83e --- /dev/null +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.rs @@ -0,0 +1,49 @@ +use std::collections::{HashSet, VecDeque}; + +impl Solution { + pub fn max_candies( + mut status: Vec , + candies: Vec , + keys: Vec >, + contained_boxes: Vec >, + initial_boxes: Vec , + ) -> i32 { + let mut q: VecDeque = VecDeque::new(); + let mut has: HashSet = HashSet::new(); + let mut took: HashSet = HashSet::new(); + let mut ans = 0; + + for &box_ in &initial_boxes { + has.insert(box_); + if status[box_ as usize] == 1 { + q.push_back(box_); + took.insert(box_); + ans += candies[box_ as usize]; + } + } + + while let Some(box_) = q.pop_front() { + for &k in &keys[box_ as usize] { + if status[k as usize] == 0 { + status[k as usize] = 1; + if has.contains(&k) && !took.contains(&k) { + q.push_back(k); + took.insert(k); + ans += candies[k as usize]; + } + } + } + + for &b in &contained_boxes[box_ as usize] { + has.insert(b); + if status[b as usize] == 1 && !took.contains(&b) { + q.push_back(b); + took.insert(b); + ans += candies[b as usize]; + } + } + } + + ans + } +} diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.ts b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.ts new file mode 100644 index 0000000000000..4a6b7feaa674e --- /dev/null +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.ts @@ -0,0 +1,47 @@ +function maxCandies( + status: number[], + candies: number[], + keys: number[][], + containedBoxes: number[][], + initialBoxes: number[], +): number { + const q: number[] = []; + const has: Set = new Set(); + const took: Set = new Set(); + let ans = 0; + + for (const box of initialBoxes) { + has.add(box); + if (status[box] === 1) { + q.push(box); + took.add(box); + ans += candies[box]; + } + } + + while (q.length > 0) { + const box = q.pop()!; + + for (const k of keys[box]) { + if (status[k] === 0) { + status[k] = 1; + if (has.has(k) && !took.has(k)) { + q.push(k); + took.add(k); + ans += candies[k]; + } + } + } + + for (const b of containedBoxes[box]) { + has.add(b); + if (status[b] === 1 && !took.has(b)) { + q.push(b); + took.add(b); + ans += candies[b]; + } + } + } + + return ans; +} diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md index e9ae14167981a..42f8aab8492d8 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md +++ b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md @@ -29,21 +29,35 @@ tags: In case there is no path, return
[0, 0]
.+
Example 1:
+Input: board = ["E23","2X2","12S"] + Output: [7,1] +Example 2:
+Input: board = ["E12","1X1","21S"] + Output: [4,2] +Example 3:
+Input: board = ["E11","XXX","11S"] + Output: [0,0] +++
Constraints:
-
diff --git a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md index 25cf3e136deec..5d94e91fb76df 100644 --- a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md +++ b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md @@ -19,39 +19,55 @@ tags:- + +
2 <= board.length == board[i].length <= 100
- +
2 <= board.length == board[i].length <= 100
Given 3 positives numbers
a
,b
andc
. Return the minimum flips required in some bits ofa
andb
to make (a
ORb
==c
). (bitwise OR operation).
+ Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.+
Example 1:
+ Input: a = 2, b = 6, c = 5 + Output: 3 + Explanation: After flips a = 1 , b = 4 , c = 5 such that (a
ORb
==c
)Example 2:
+ Input: a = 4, b = 2, c = 7 + Output: 1 +Example 3:
+ Input: a = 1, b = 2, c = 3 + Output: 0 ++
Constraints:
-
diff --git a/solution/1300-1399/1324.Print Words Vertically/README_EN.md b/solution/1300-1399/1324.Print Words Vertically/README_EN.md index e1542d061c72f..c86ec25b2c2cb 100644 --- a/solution/1300-1399/1324.Print Words Vertically/README_EN.md +++ b/solution/1300-1399/1324.Print Words Vertically/README_EN.md @@ -21,46 +21,71 @@ tags:- -
1 <= a <= 10^9
- -
1 <= b <= 10^9
- + +
1 <= c <= 10^9
- + +
1 <= a <= 10^9
- + +
1 <= b <= 10^9
- +
1 <= c <= 10^9
Given a string
s
. Return all the words vertically in the same order in which they appear ins
.
+ Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
+ Each word would be put on only one column and that in one column there will be only one word.+
Example 1:
+ Input: s = "HOW ARE YOU" + Output: ["HAY","ORO","WEU"] + Explanation: Each word is printed vertically. + "HAY" + "ORO" + "WEU" +Example 2:
+ Input: s = "TO BE OR NOT TO BE" + Output: ["TBONTB","OEROOE"," T"] + Explanation: Trailing spaces is not allowed. + "TBONTB" + "OEROOE" + " T" +Example 3:
+ Input: s = "CONTEST IS COMING" + Output: ["CIC","OSO","N M","T I","E N","S G","T"] ++
Constraints:
-
diff --git a/solution/1300-1399/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: -- -
1 <= s.length <= 200
- -
s
contains only upper case English letters.- It's guaranteed that there is only one space between 2 words.
+ +- + +
1 <= s.length <= 200
- + +
s
contains only upper case English letters.- It's guaranteed that there is only one space between 2 words.
+给你一个整数
+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/1418.Display Table of Food Orders in a Restaurant/README_EN.md b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md index 809ec164c6da3..dd6bc86d1a53a 100644 --- a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md +++ b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md @@ -27,48 +27,77 @@ tags:Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
+
Example 1:
+ Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]] + Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] + Explanation: + The displaying table looks like: + Table,Beef Burrito,Ceviche,Fried Chicken,Water + 3 ,0 ,2 ,1 ,0 + 5 ,0 ,1 ,0 ,1 + 10 ,1 ,0 ,0 ,0 + For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche". + For the table 5: Carla orders "Water" and "Ceviche". + For the table 10: Corina orders "Beef Burrito". +Example 2:
+ Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]] + Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] + Explanation: + For the table 1: Adam and Brianna order "Canadian Waffles". + For the table 12: James, Ratesh and Amadeus order "Fried Chicken". +Example 3:
+ Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]] + Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]] ++
Constraints:
-
diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md index f27f75f2fd31b..2d6da8186663c 100644 --- a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md @@ -19,24 +19,26 @@ tags: -- -
1 <= orders.length <= 5 * 10^4
- -
orders[i].length == 3
- -
1 <= customerNamei.length, foodItemi.length <= 20
- -
customerNamei
andfoodItemi
consist of lowercase and uppercase English letters and the space character.- + +
tableNumberi
is a valid integer between1
and500
.- + +
1 <= orders.length <= 5 * 10^4
- + +
orders[i].length == 3
- + +
1 <= customerNamei.length, foodItemi.length <= 20
- + +
customerNamei
andfoodItemi
consist of lowercase and uppercase English letters and the space character.- +
tableNumberi
is a valid integer between1
and500
.给你一个整数
+num
。你可以对它进行如下步骤恰好 两次 :给你一个整数
num
。你可以对它进行以下步骤共计 两次:
- 选择一个数字
x (0 <= x <= 9)
.- 选择另一个数字
y (0 <= y <= 9)
。数字y
可以等于x
。- 将
-num
中所有出现x
的数位都用y
替换。- 得到的新的整数 不能 有前导 0 ,得到的新整数也 不能 是 0 。
令两次对
num
的操作得到的结果分别为a
和b
。请你返回
+a
和b
的 最大差值 。注意,新的整数(
+a
或b
)必须不能 含有前导 0,并且 非 0。
示例 1:
-输入:num = 555 ++输入:num = 555 输出:888 解释:第一次选择 x = 5 且 y = 9 ,并把得到的新数字保存在 a 中。 第二次选择 x = 5 且 y = 1 ,并把得到的新数字保存在 b 中。 @@ -45,7 +47,8 @@ tags:示例 2:
-输入:num = 9 ++输入:num = 9 输出:8 解释:第一次选择 x = 9 且 y = 9 ,并把得到的新数字保存在 a 中。 第二次选择 x = 9 且 y = 1 ,并把得到的新数字保存在 b 中。 @@ -54,19 +57,22 @@ tags:示例 3:
-输入:num = 123456 ++输入:num = 123456 输出:820000示例 4:
-输入:num = 10000 ++输入:num = 10000 输出:80000示例 5:
-输入:num = 9288 ++输入:num = 9288 输出:8700diff --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..d31d01cb1c408 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:
diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md index 75f9d52c74990..4a07c72b0b946 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md @@ -26,17 +26,25 @@ tags:Return the number of good nodes in the binary tree.
+
Example 1:
+ Input: root = [3,1,4,3,null,1,5] + Output: 4 + Explanation: Nodes in blue are good. + Root Node (3) is always a good node. + Node 4 -> (3,4) is the maximum value in the path starting from the root. + Node 5 -> (3,4,5) is the maximum value in the path + Node 3 -> (3,1,3) is the maximum value in the path.Example 2:
@@ -44,23 +52,33 @@ Node 3 -> (3,1,3) is the maximum value in the path.
+ Input: root = [3,3,null,4,2] + Output: 3 + Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.Example 3:
+ Input: root = [1] + Output: 1 + Explanation: Root is considered as good.+
Constraints:
[1, 10^5]
.[-10^4, 10^4]
.[1, 10^5]
.[-10^4, 10^4]
.Return the array in the form [x1,y1,x2,y2,...,xn,yn]
.
+
Example 1:
+ Input: nums = [2,5,1,3,4,7], n = 3 + Output: [2,3,5,4,1,7] + Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. +
Example 2:
+ Input: nums = [1,2,3,4,4,3,2,1], n = 4 + Output: [1,4,2,3,3,2,4,1] +
Example 3:
+ Input: nums = [1,1,2,2], n = 2 + Output: [1,2,1,2] +
+
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
Given an array of integers arr
and an integer k
. Find the least number of unique integers after removing exactly k
elements.
+
Example 1:
+ Input: arr = [5,5,4], k = 1 + Output: 1 + Explanation: Remove the single 4, only 5 is left. +Example 2:
+ Input: arr = [4,3,1,1,3,3,2], k = 3 + Output: 2 + Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
+
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
Given two non-negative integers low
and high
. Return the count of odd numbers between low
and high
(inclusive).
+
Example 1:
+ Input: low = 3, high = 7 + Output: 3 + Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
+ Input: low = 8, high = 10 + Output: 1 + Explanation: The odd numbers between 8 and 10 are [9].
+
Constraints:
0 <= low <= high <= 10^9
0 <= low <= high <= 10^9
A triplet (arr[i], arr[j], arr[k])
is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x|
denotes the absolute value of x
.
Return the number of good triplets.
+
Example 1:
+ Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 + Output: 4 + Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. +
Example 2:
+ Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1 + Output: 0 + Explanation: No triplet satisfies all conditions. +
+
Constraints:
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
Notice that the distance between the two cities is the number of edges in the path between them.
+
Example 1:
+ Input: n = 4, edges = [[1,2],[2,3],[2,4]] + Output: [3,4,0] + Explanation: + The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. + The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. + No subtree has two nodes where the max distance between them is 3. +
Example 2:
+ Input: n = 2, edges = [[1,2]] + Output: [1] +
Example 3:
+ Input: n = 3, edges = [[1,2],[2,3]] + Output: [2,1] +
+
Constraints:
2 <= n <= 15
edges.length == n-1
edges[i].length == 2
1 <= ui, vi <= n
(ui, vi)
are distinct.2 <= n <= 15
edges.length == n-1
edges[i].length == 2
1 <= ui, vi <= n
(ui, vi)
are distinct.The FontInfo
interface is defined as such:
+ interface FontInfo { + // Returns the width of character ch on the screen using font size fontSize. + // O(1) per call + public int getWidth(int fontSize, char ch); + + // Returns the height of any character on the screen using font size fontSize. + // O(1) per call + public int getHeight(int fontSize); + }
The calculated width of text
for some fontSize
is the sum of every getWidth(fontSize, text[i])
call for each 0 <= i < text.length
(0-indexed). The calculated height of text
for some fontSize
is getHeight(fontSize)
. Note that text
is displayed on a single line.
It is also guaranteed that for any font size fontSize
and any character ch
:
getHeight(fontSize) <= getHeight(fontSize+1)
getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
getHeight(fontSize) <= getHeight(fontSize+1)
getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
Return the maximum font size you can use to display text
on the screen. If text
cannot fit on the display with any font size, return -1
.
+
Example 1:
+ Input: text = "helloworld", w = 80, h = 20, fonts = [6,8,10,12,14,16,18,24,36] + Output: 6 +
Example 2:
+ Input: text = "leetcode", w = 1000, h = 50, fonts = [1,2,4] + Output: 4 +
Example 3:
+ Input: text = "easyquestion", w = 100, h = 100, fonts = [10,15,20,25] + Output: -1 +
+
Constraints:
1 <= text.length <= 50000
text
contains only lowercase English letters.1 <= w <= 107
1 <= h <= 104
1 <= fonts.length <= 105
1 <= fonts[i] <= 105
fonts
is sorted in ascending order and does not contain duplicates.1 <= text.length <= 50000
text
contains only lowercase English letters.1 <= w <= 107
1 <= h <= 104
1 <= fonts.length <= 105
1 <= fonts[i] <= 105
fonts
is sorted in ascending order and does not contain duplicates.Each node has three attributes:
coefficient
: an integer representing the number multiplier of the term. The coefficient of the term 9x4
is 9
.power
: an integer representing the exponent. The power of the term 9x4
is 4
.next
: a pointer to the next node in the list, or null
if it is the last node of the list.coefficient
: an integer representing the number multiplier of the term. The coefficient of the term 9x4
is 9
.power
: an integer representing the exponent. The power of the term 9x4
is 4
.next
: a pointer to the next node in the list, or null
if it is the last node of the list.For example, the polynomial 5x3 + 4x - 7
is represented by the polynomial linked list illustrated below:
The input/output format is as a list of n
nodes, where each node is represented as its [coefficient, power]
. For example, the polynomial 5x3 + 4x - 7
would be represented as: [[5,3],[4,1],[-7,0]]
.
+
Example 1:
+ Input: poly1 = [[1,1]], poly2 = [[1,0]] + Output: [[1,1],[1,0]] + Explanation: poly1 = x. poly2 = 1. The sum is x + 1. +
Example 2:
+ Input: poly1 = [[2,2],[4,1],[3,0]], poly2 = [[3,2],[-4,1],[-1,0]] + Output: [[5,2],[2,0]] + Explanation: poly1 = 2x2 + 4x + 3. poly2 = 3x2 - 4x - 1. The sum is 5x2 + 2. Notice that we omit the "0x" term. +
Example 3:
+ Input: poly1 = [[1,2]], poly2 = [[-1,2]] + Output: [] + Explanation: The sum is 0. We return an empty list. +
+
Constraints:
0 <= n <= 104
-109 <= PolyNode.coefficient <= 109
PolyNode.coefficient != 0
0 <= PolyNode.power <= 109
PolyNode.power > PolyNode.next.power
0 <= n <= 104
-109 <= PolyNode.coefficient <= 109
PolyNode.coefficient != 0
0 <= PolyNode.power <= 109
PolyNode.power > PolyNode.next.power
Given an integer array instructions
, you are asked to create a sorted array from the elements in instructions
. You start with an empty container nums
. For each element from left to right in instructions
, insert it into nums
. The cost of each insertion is the minimum of the following:
nums
that are strictly less than instructions[i]
.nums
that are strictly greater than instructions[i]
.nums
that are strictly less than instructions[i]
.nums
that are strictly greater than instructions[i]
.For example, if inserting element 3
into nums = [1,2,3,5]
, the cost of insertion is min(2, 1)
(elements 1
and 2
are less than 3
, element 5
is greater than 3
) and nums
will become [1,2,3,3,5]
.
Return the total cost to insert all elements from instructions
into nums
. Since the answer may be large, return it modulo 109 + 7
+
Example 1:
+ Input: instructions = [1,5,6,2] + Output: 1 + Explanation: Begin with nums = []. + Insert 1 with cost min(0, 0) = 0, now nums = [1]. + Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. + Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. + Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. + The total cost is 0 + 0 + 0 + 1 = 1.
Example 2:
+ Input: instructions = [1,2,3,6,5,4] + Output: 3 + Explanation: Begin with nums = []. + Insert 1 with cost min(0, 0) = 0, now nums = [1]. + Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. + Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. + Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. + Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. + Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. + The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3. +
Example 3:
+ Input: instructions = [1,3,3,3,2,4,2,1,2] + Output: 4 + Explanation: Begin with nums = []. + Insert 1 with cost min(0, 0) = 0, now nums = [1]. + Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. + Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. + Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. + Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. + Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. + Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. + Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. + Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. + The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4. +
+
Constraints:
1 <= instructions.length <= 105
1 <= instructions[i] <= 105
1 <= instructions.length <= 105
1 <= instructions[i] <= 105
The test input is read as 3 lines:
TreeNode root
int fromNode
(not available to correctBinaryTree
)int toNode
(not available to correctBinaryTree
)TreeNode root
int fromNode
(not available to correctBinaryTree
)int toNode
(not available to correctBinaryTree
)After the binary tree rooted at root
is parsed, the TreeNode
with value of fromNode
will have its right child pointer pointing to the TreeNode
with a value of toNode
. Then, root
is passed to correctBinaryTree
.
+
Example 1:
+ Input: root = [1,2,3], fromNode = 2, toNode = 3 + Output: [1,null,3] + Explanation: The node with value 2 is invalid, so remove it. +
Example 2:
@@ -52,22 +61,35 @@ tags:+ Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4 + Output: [8,3,1,null,null,9,4,null,null,5,6] + Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2. +
+
Constraints:
[3, 104]
.-109 <= Node.val <= 109
Node.val
are unique.fromNode != toNode
fromNode
and toNode
will exist in the tree and will be on the same depth.toNode
is to the right of fromNode
.fromNode.right
is null
in the initial tree from the test data.[3, 104]
.-109 <= Node.val <= 109
Node.val
are unique.fromNode != toNode
fromNode
and toNode
will exist in the tree and will be on the same depth.toNode
is to the right of fromNode
.fromNode.right
is null
in the initial tree from the test data.Return the number of rectangles that can make a square with a side length of maxLen
.
+
Example 1:
+ Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] + Output: 3 + Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5]. + The largest possible square is of length 5, and you can get it out of 3 rectangles. +
Example 2:
+ Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] + Output: 3 +
+
Constraints:
1 <= rectangles.length <= 1000
rectangles[i].length == 2
1 <= li, wi <= 109
li != wi
1 <= rectangles.length <= 1000
rectangles[i].length == 2
1 <= li, wi <= 109
li != wi
Return the maximum possible subarray sum after exactly one operation. The subarray must be non-empty.
+
Example 1:
+ Input: nums = [2,-1,-4,-3] + Output: 17 + Explanation: You can perform the operation on index 2 (0-indexed) to make nums = [2,-1,16,-3]. Now, the maximum subarray sum is 2 + -1 + 16 = 17.
Example 2:
+ Input: nums = [1,-1,1,1,-1,-1,1] + Output: 4 + Explanation: You can perform the operation on index 1 (0-indexed) to make nums = [1,1,1,1,-1,-1,1]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4.
+
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= nums.length <= 105
-104 <= nums[i] <= 104
Return the merged string.
+
Example 1:
+ Input: word1 = "abc", word2 = "pqr" + Output: "apbqcr" + Explanation: The merged string will be merged as so: + word1: a b c + word2: p q r + merged: a p b q c r +
Example 2:
+ Input: word1 = "ab", word2 = "pqrs" + Output: "apbqrs" + Explanation: Notice that as word2 is longer, "rs" is appended to the end. + word1: a b + word2: p q r s + merged: a p b q r s +
Example 3:
+ Input: word1 = "abcd", word2 = "pq" + Output: "apbqcd" + Explanation: Notice that as word1 is longer, "cd" is appended to the end. + word1: a b c d + word2: p q + merged: a p b q c d +
+
Constraints:
1 <= word1.length, word2.length <= 100
word1
and word2
consist of lowercase English letters.1 <= word1.length, word2.length <= 100
word1
and word2
consist of lowercase English letters.A garden is valid if it meets these conditions:
As the appointed gardener, you have the ability to remove any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden valid. The beauty of the garden is the sum of the beauty of all the remaining flowers.
@@ -33,36 +36,53 @@ tags:Return the maximum possible beauty of some valid garden after you have removed any (possibly none) flowers.
+
Example 1:
+ Input: flowers = [1,2,3,1,2] + Output: 8 + Explanation: You can produce the valid garden [2,3,1,2] to have a total beauty of 2 + 3 + 1 + 2 = 8.
Example 2:
+ Input: flowers = [100,1,1,-3,1] + Output: 3 + Explanation: You can produce the valid garden [1,1,1] to have a total beauty of 1 + 1 + 1 = 3. +
Example 3:
+ Input: flowers = [-1,-2,0,-1] + Output: -2 + Explanation: You can produce the valid garden [-1,-1] to have a total beauty of -1 + -1 = -2. +
+
Constraints:
2 <= flowers.length <= 105
-104 <= flowers[i] <= 104
2 <= flowers.length <= 105
-104 <= flowers[i] <= 104
You are given a 2D integer array orders
, where each orders[i] = [pricei, amounti, orderTypei]
denotes that amounti
orders have been placed of type orderTypei
at the price pricei
. The orderTypei
is:
0
if it is a batch of buy
orders, or1
if it is a batch of sell
orders.0
if it is a batch of buy
orders, or1
if it is a batch of sell
orders.Note that orders[i]
represents a batch of amounti
independent orders with the same price and order type. All orders represented by orders[i]
will be placed before all orders represented by orders[i+1]
for all valid i
.
There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
buy
order, you look at the sell
order with the smallest price in the backlog. If that sell
order's price is smaller than or equal to the current buy
order's price, they will match and be executed, and that sell
order will be removed from the backlog. Else, the buy
order is added to the backlog.sell
order, you look at the buy
order with the largest price in the backlog. If that buy
order's price is larger than or equal to the current sell
order's price, they will match and be executed, and that buy
order will be removed from the backlog. Else, the sell
order is added to the backlog.buy
order, you look at the sell
order with the smallest price in the backlog. If that sell
order's price is smaller than or equal to the current buy
order's price, they will match and be executed, and that sell
order will be removed from the backlog. Else, the buy
order is added to the backlog.sell
order, you look at the buy
order with the largest price in the backlog. If that buy
order's price is larger than or equal to the current sell
order's price, they will match and be executed, and that buy
order will be removed from the backlog. Else, the sell
order is added to the backlog.Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7
.
+
Example 1:
++ Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]] + Output: 6 + Explanation: Here is what happens with the orders: + - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. + - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. + - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. + - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. + Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6. +
Example 2:
++ Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]] + Output: 999999984 + Explanation: Here is what happens with the orders: + - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. + - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. + - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. + - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. + Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7). +
+
Constraints:
1 <= orders.length <= 105
orders[i].length == 3
1 <= pricei, amounti <= 109
orderTypei
is either 0
or 1
.1 <= orders.length <= 105
orders[i].length == 3
1 <= pricei, amounti <= 109
orderTypei
is either 0
or 1
.A nice pair is a pair (i, j)
where 0 <= i < j < nums.length
and low <= (nums[i] XOR nums[j]) <= high
.
+
Example 1:
+ Input: nums = [1,4,2,7], low = 2, high = 6 + Output: 6 + Explanation: All nice pairs (i, j) are as follows: + - (0, 1): nums[0] XOR nums[1] = 5 + - (0, 2): nums[0] XOR nums[2] = 3 + - (0, 3): nums[0] XOR nums[3] = 6 + - (1, 2): nums[1] XOR nums[2] = 6 + - (1, 3): nums[1] XOR nums[3] = 3 + - (2, 3): nums[2] XOR nums[3] = 5 +
Example 2:
+ Input: nums = [9,8,4,2,1], low = 5, high = 14 + Output: 8 + Explanation: All nice pairs (i, j) are as follows: + - (0, 2): nums[0] XOR nums[2] = 13 + - (0, 3): nums[0] XOR nums[3] = 11 + - (0, 4): nums[0] XOR nums[4] = 8 + - (1, 2): nums[1] XOR nums[2] = 12 + - (1, 3): nums[1] XOR nums[3] = 10 + - (1, 4): nums[1] XOR nums[4] = 9 + - (2, 3): nums[2] XOR nums[3] = 6 + - (2, 4): nums[2] XOR nums[4] = 5
+
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i] <= 2 * 104
1 <= low <= high <= 2 * 104
1 <= nums.length <= 2 * 104
1 <= nums[i] <= 2 * 104
1 <= low <= high <= 2 * 104
You are given a positive integer primeFactors
. You are asked to construct a positive integer n
that satisfies the following conditions:
n
(not necessarily distinct) is at most primeFactors
.n
is maximized. Note that a divisor of n
is nice if it is divisible by every prime factor of n
. For example, if n = 12
, then its prime factors are [2,2,3]
, then 6
and 12
are nice divisors, while 3
and 4
are not.Return the number of nice divisors of n
. Since that number can be too large, return it modulo 109 + 7
.
Note that a prime number is a natural number greater than 1
that is not a product of two smaller natural numbers. The prime factors of a number n
is a list of prime numbers such that their product equals n
.
+
Example 1:
+ Input: primeFactors = 5 + Output: 6 + Explanation: 200 is a valid value of n. + It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200]. + There is not other value of n that has at most 5 prime factors and more nice divisors. +
Example 2:
+ Input: primeFactors = 8 + Output: 18 +
+
Constraints:
1 <= primeFactors <= 109
1 <= primeFactors <= 109
3 <= m <= 105
1 <= k*2 < m
1 < k*2 < m
1 <= num <= 105
105
calls will be made to addElement
and calculateMKAverage
.You are given an integer array nums
(0-indexed). In one operation, you can choose an element of the array and increment it by 1
.
nums = [1,2,3]
, you can choose to increment nums[1]
to make nums = [1,3,3]
.nums = [1,2,3]
, you can choose to increment nums[1]
to make nums = [1,3,3]
.Return the minimum number of operations needed to make nums
strictly increasing.
An array nums
is strictly increasing if nums[i] < nums[i+1]
for all 0 <= i < nums.length - 1
. An array of length 1
is trivially strictly increasing.
+
Example 1:
+ Input: nums = [1,1,1] + Output: 3 + Explanation: You can do the following operations: + 1) Increment nums[2], so nums becomes [1,1,2]. + 2) Increment nums[1], so nums becomes [1,2,2]. + 3) Increment nums[2], so nums becomes [1,2,3]. +
Example 2:
+ Input: nums = [1,5,2,4,1] + Output: 14 +
Example 3:
+ Input: nums = [8] + Output: 0 +
+
Constraints:
1 <= nums.length <= 5000
1 <= nums[i] <= 104
1 <= nums.length <= 5000
1 <= nums[i] <= 104
Return the linked list after the deletions.
+
Example 1:
++ Input: head = [1,2,3,2] + Output: [1,3] + Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3]. +
Example 2:
++ Input: head = [2,1,1,2] + Output: [] + Explanation: 2 and 1 both appear twice. All the elements should be deleted. +
Example 3:
++ Input: head = [3,2,2,1,3,2,4] + Output: [1,4] + Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4]. +
+
Constraints:
[1, 105]
1 <= Node.val <= 105
[1, 105]
1 <= Node.val <= 105
给你一个 有向图 ,它含有 n
个节点和 m
条边。节点编号从 0
到 n - 1
。
给你一个 有向图 ,它含有 n
个节点和 m
条边。节点编号从 0
到 n - 1
。
给你一个字符串 colors
,其中 colors[i]
是小写英文字母,表示图中第 i
个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组 edges
,其中 edges[j] = [aj, bj]
表示从节点 aj
到节点 bj
有一条 有向边 。
给你一个字符串 colors
,其中 colors[i]
是小写英文字母,表示图中第 i
个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组 edges
,其中 edges[j] = [aj, bj]
表示从节点 aj
到节点 bj
有一条 有向边 。
图中一条有效 路径 是一个点序列 x1 -> x2 -> x3 -> ... -> xk
,对于所有 1 <= i < k
,从 xi
到 xi+1
在图中有一条有向边。路径的 颜色值 是路径中 出现次数最多 颜色的节点数目。
图中一条有效 路径 是一个点序列 x1 -> x2 -> x3 -> ... -> xk
,对于所有 1 <= i < k
,从 xi
到 xi+1
在图中有一条有向边。路径的 颜色值 是路径中 出现次数最多 颜色的节点数目。
请你返回给定图中有效路径里面的 最大颜色值 。如果图中含有环,请返回 -1
。
请你返回给定图中有效路径里面的 最大颜色值 。如果图中含有环,请返回 -1
。
+
示例 1:
-输入:colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]] ++输入:colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]] 输出:3 -解释:路径 0 -> 2 -> 3 -> 4 含有 3 个颜色为"a" 的节点(上图中的红色节点)。
+解释:路径 0 -> 2 -> 3 -> 4 含有 3 个颜色为 "a" 的节点(上图中的红色节点)。示例 2:
-+
-
输入:colors = "a", edges = [[0,0]] ++输入:colors = "a", edges = [[0,0]] 输出:-1 解释:从 0 到 0 有一个环。-+
提示:
@@ -60,8 +62,8 @@ tags:
m == edges.length
1 <= n <= 105
0 <= m <= 105
colors
只含有小写英文字母。0 <= aj, bj < n
colors
只含有小写英文字母。0 <= aj, bj < n
There are n
stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:
x > 1
, and remove the leftmost x
stones from the row.x > 1
, and remove the leftmost x
stones from the row.The game stops when only one stone is left in the row.
@@ -39,48 +43,77 @@ tags:Given an integer array stones
of length n
where stones[i]
represents the value of the ith
stone from the left, return the score difference between Alice and Bob if they both play optimally.
+
Example 1:
+ Input: stones = [-1,2,-3,4,-5] + Output: 5 + Explanation: + - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of + value 2 on the left. stones = [2,-5]. + - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on + the left. stones = [-3]. + The difference between their scores is 2 - (-3) = 5. +
Example 2:
+ Input: stones = [7,-6,5,10,5,-2,-6] + Output: 13 + Explanation: + - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a + stone of value 13 on the left. stones = [13]. + The difference between their scores is 13 - 0 = 13. +
Example 3:
+ Input: stones = [-10,-12] + Output: -22 + Explanation: + - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her + score and places a stone of value -22 on the left. stones = [-22]. + The difference between their scores is (-22) - 0 = -22. +
+
Constraints:
n == stones.length
2 <= n <= 105
-104 <= stones[i] <= 104
n == stones.length
2 <= n <= 105
-104 <= stones[i] <= 104
The product sum of two equal-length arrays a
and b
is equal to the sum of a[i] * b[i]
for all 0 <= i < a.length
(0-indexed).
a = [1,2,3,4]
and b = [5,2,3,1]
, the product sum would be 1*5 + 2*2 + 3*3 + 4*1 = 22
.a = [1,2,3,4]
and b = [5,2,3,1]
, the product sum would be 1*5 + 2*2 + 3*3 + 4*1 = 22
.Given two arrays nums1
and nums2
of length n
, return the minimum product sum if you are allowed to rearrange the order of the elements in nums1
.
+
Example 1:
+ Input: nums1 = [5,3,4,2], nums2 = [4,2,2,5] + Output: 40 + Explanation: We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40. +
Example 2:
+ Input: nums1 = [2,1,4,5,7], nums2 = [3,2,4,8,6] + Output: 65 + Explanation: We can rearrange nums1 to become [5,7,4,1,2]. The product sum of [5,7,4,1,2] and [3,2,4,8,6] is 5*3 + 7*2 + 4*4 + 1*8 + 2*6 = 65. +
+
Constraints:
n == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 100
n == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 100
The pair sum of a pair (a,b)
is equal to a + b
. The maximum pair sum is the largest pair sum in a list of pairs.
(1,5)
, (2,3)
, and (4,4)
, the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.(1,5)
, (2,3)
, and (4,4)
, the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.Given an array nums
of even length n
, pair up the elements of nums
into n / 2
pairs such that:
nums
is in exactly one pair, andnums
is in exactly one pair, andReturn the minimized maximum pair sum after optimally pairing up the elements.
+
Example 1:
+ Input: nums = [3,5,2,3] + Output: 7 + Explanation: The elements can be paired up into pairs (3,3) and (5,2). + The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. +
Example 2:
+ Input: nums = [3,5,4,2,4,6] + Output: 8 + Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). + The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. +
+
Constraints:
n == nums.length
2 <= n <= 105
n
is even.1 <= nums[i] <= 105
n == nums.length
2 <= n <= 105
n
is even.1 <= nums[i] <= 105
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
[4,2,5,3]
is (4 + 5) - (2 + 3) = 4
.[4,2,5,3]
is (4 + 5) - (2 + 3) = 4
.Given an array nums
, return the maximum alternating sum of any subsequence of nums
(after reindexing the elements of the subsequence).
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4]
is a subsequence of [4,2,3,7,2,1,4]
(the underlined elements), while [2,4,2]
is not.
+
Example 1:
+ Input: nums = [4,2,5,3] + Output: 7 + Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. +
Example 2:
+ Input: nums = [5,6,7,8] + Output: 8 + Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. +
Example 3:
+ Input: nums = [6,2,1,2,4,5] + Output: 10 + Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10. +
+
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= nums.length <= 105
1 <= nums[i] <= 105
The product difference between two pairs (a, b)
and (c, d)
is defined as (a * b) - (c * d)
.
(5, 6)
and (2, 7)
is (5 * 6) - (2 * 7) = 16
.(5, 6)
and (2, 7)
is (5 * 6) - (2 * 7) = 16
.Given an integer array nums
, choose four distinct indices w
, x
, y
, and z
such that the product difference between pairs (nums[w], nums[x])
and (nums[y], nums[z])
is maximized.
Return the maximum such product difference.
+
Example 1:
+ Input: nums = [5,6,2,7,4] + Output: 34 + Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). + The product difference is (6 * 7) - (2 * 4) = 34. +
Example 2:
+ Input: nums = [4,2,5,9,7,4,8] + Output: 64 + Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). + The product difference is (9 * 8) - (2 * 4) = 64. +
+
Constraints:
4 <= nums.length <= 104
1 <= nums[i] <= 104
4 <= nums.length <= 104
1 <= nums[i] <= 104
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
+Return the matrix after applying k
cyclic rotations to it.
+
Example 1:
++ Input: grid = [[40,10],[30,20]], k = 1 + Output: [[10,20],[40,30]] + Explanation: The figures above represent the grid at every state. +
Example 2:
++ Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2 + Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]] + Explanation: The figures above represent the grid at every state. +
+
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 50
m
and n
are even integers.1 <= grid[i][j] <= 5000
1 <= k <= 109
m == grid.length
n == grid[i].length
2 <= m, n <= 50
m
and n
are even integers.1 <= grid[i][j] <= 5000
1 <= k <= 109
A wonderful string is a string where at most one letter appears an odd number of times.
"ccjjc"
and "abab"
are wonderful, but "ab"
is not."ccjjc"
and "abab"
are wonderful, but "ab"
is not.Given a string word
that consists of the first ten lowercase English letters ('a'
through 'j'
), return the number of wonderful non-empty substrings in word
. If the same substring appears multiple times in word
, then count each occurrence separately.
A substring is a contiguous sequence of characters in a string.
+
Example 1:
+ Input: word = "aba" + Output: 4 + Explanation: The four wonderful substrings are underlined below: + - "aba" -> "a" + - "aba" -> "b" + - "aba" -> "a" + - "aba" -> "aba" +
Example 2:
+ Input: word = "aabb" + Output: 9 + Explanation: The nine wonderful substrings are underlined below: + - "aabb" -> "a" + - "aabb" -> "aa" + - "aabb" -> "aab" + - "aabb" -> "aabb" + - "aabb" -> "a" + - "aabb" -> "abb" + - "aabb" -> "b" + - "aabb" -> "bb" + - "aabb" -> "b" +
Example 3:
+ Input: word = "he" + Output: 2 + Explanation: The two wonderful substrings are underlined below: + - "he" -> "h" + - "he" -> "e" +
+
Constraints:
1 <= word.length <= 105
word
consists of lowercase English letters from 'a'
to 'j'
.1 <= word.length <= 105
word
consists of lowercase English letters from 'a'
to 'j'
.Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7
.
+
Example 1:
++ Input: prevRoom = [-1,0,1] + Output: 1 + Explanation: There is only one way to build the additional rooms: 0 → 1 → 2 +
Example 2:
++ Input: prevRoom = [-1,0,0,1,2] + Output: 6 + Explanation: + The 6 ways are: + 0 → 1 → 3 → 2 → 4 + 0 → 2 → 4 → 1 → 3 + 0 → 1 → 2 → 3 → 4 + 0 → 1 → 2 → 4 → 3 + 0 → 2 → 1 → 3 → 4 + 0 → 2 → 1 → 4 → 3 +
+
Constraints:
n == prevRoom.length
2 <= n <= 105
prevRoom[0] == -1
0 <= prevRoom[i] < n
for all 1 <= i < n
0
once all the rooms are built.n == prevRoom.length
2 <= n <= 105
prevRoom[0] == -1
0 <= prevRoom[i] < n
for all 1 <= i < n
0
once all the rooms are built.给你一个整数数组 piles
,数组 下标从 0 开始 ,其中 piles[i]
表示第 i
堆石子中的石子数量。另给你一个整数 k
,请你执行下述操作 恰好 k
次:
piles[i]
,并从中 移除 floor(piles[i] / 2)
颗石子。piles[i]
,并从中 移除 ceil(piles[i] / 2)
颗石子。注意:你可以对 同一堆 石子多次执行此操作。
返回执行 k
次操作后,剩下石子的 最小 总数。
floor(x)
为 小于 或 等于 x
的 最大 整数。(即,对 x
向下取整)。
ceil(x)
为 大于 或 等于 x
的 最小 整数。(即,对 x
向上取整)。
diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md index 3bec84a9ba286..cc0e8df44b0fe 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md @@ -23,14 +23,14 @@ tags:
You are given a 0-indexed integer array piles
, where piles[i]
represents the number of stones in the ith
pile, and an integer k
. You should apply the following operation exactly k
times:
piles[i]
and remove floor(piles[i] / 2)
stones from it.piles[i]
and remove ceil(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 to x
(i.e., rounds x
down).
ceil(x)
is the smallest integer that is greater than or equal to x
(i.e., rounds x
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: VecExample 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给你一个二进制字符串 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 & nums, int minK, int maxK) { long long ans = 0; int j1 = -1, j2 = -1, k = -1; - for (int i = 0; i < nums.size(); ++i) { - if (nums[i] < minK || nums[i] > maxK) k = i; - if (nums[i] == minK) j1 = i; - if (nums[i] == maxK) j2 = i; + for (int i = 0; i < static_cast (nums.size()); ++i) { + if (nums[i] < minK || nums[i] > maxK) { + k = i; + } + if (nums[i] == minK) { + j1 = i; + } + if (nums[i] == maxK) { + j2 = i; + } ans += max(0, min(j1, j2) - k); } return ans; @@ -167,23 +173,15 @@ func countSubarrays(nums []int, minK int, maxK int) int64 { ```ts function countSubarrays(nums: number[], minK: number, maxK: number): number { - let res = 0; - let minIndex = -1; - let maxIndex = -1; - let k = -1; - nums.forEach((num, i) => { - if (num === minK) { - minIndex = i; - } - if (num === maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += Math.max(Math.min(minIndex, maxIndex) - k, 0); - }); - return res; + let ans = 0; + let [j1, j2, k] = [-1, -1, -1]; + for (let i = 0; i < nums.length; ++i) { + if (nums[i] < minK || nums[i] > maxK) k = i; + if (nums[i] === minK) j1 = i; + if (nums[i] === maxK) j2 = i; + ans += Math.max(0, Math.min(j1, j2) - k); + } + return ans; } ``` @@ -192,25 +190,27 @@ function countSubarrays(nums: number[], minK: number, maxK: number): number { ```rust impl Solution { pub fn count_subarrays(nums: Vec , min_k: i32, max_k: i32) -> i64 { - let mut res = 0; - let mut min_index = -1; - let mut max_index = -1; - let mut k = -1; - for i in 0..nums.len() { - let num = nums[i]; + let mut ans: i64 = 0; + let mut j1: i64 = -1; + let mut j2: i64 = -1; + let mut k: i64 = -1; + for (i, &v) in nums.iter().enumerate() { let i = i as i64; - if num == min_k { - min_index = i; + if v < min_k || v > max_k { + k = i; } - if num == max_k { - max_index = i; + if v == min_k { + j1 = i; } - if num < min_k || num > max_k { - k = i; + if v == max_k { + j2 = i; + } + let m = j1.min(j2); + if m > k { + ans += m - k; } - res += (0).max(min_index.min(max_index) - k); } - res + ans } } ``` @@ -218,28 +218,17 @@ impl Solution { #### C ```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { - long long res = 0; - int minIndex = -1; - int maxIndex = -1; - int k = -1; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num == minK) { - minIndex = i; - } - if (num == maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += max(min(minIndex, maxIndex) - k, 0); + long long ans = 0; + int j1 = -1, j2 = -1, k = -1; + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < minK || nums[i] > maxK) k = i; + if (nums[i] == minK) j1 = i; + if (nums[i] == maxK) j2 = i; + int m = j1 < j2 ? j1 : j2; + if (m > k) ans += (long long) (m - k); } - return res; + return ans; } ``` diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md index 83e8bbb0189cd..649f2bd4c1f71 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md @@ -65,19 +65,19 @@ tags: -### Solution 1: Enumeration of Right Endpoint +### Solution 1: Enumerate the Right Endpoint -From the problem description, we know that all elements of the bounded subarray are in the interval `[minK, maxK]`, and the minimum value must be `minK`, and the maximum value must be `maxK`. +According to the problem description, we know that all elements of a bounded subarray are within the range $[\textit{minK}, \textit{maxK}]$, and the minimum value must be $\textit{minK}$, while the maximum value must be $\textit{maxK}$. -We traverse the array $nums$, count the number of bounded subarrays with `nums[i]` as the right endpoint, and then add all the counts. +We iterate through the array $\textit{nums}$ and count the number of bounded subarrays with $\textit{nums}[i]$ as the right endpoint. Then, we sum up all the counts. The specific implementation logic is as follows: -1. Maintain the index $k$ of the most recent element not in the interval `[minK, maxK]`, initially set to $-1$. Therefore, the left endpoint of the current element `nums[i]` must be greater than $k$. -1. Maintain the index $j_1$ of the most recent element with a value of `minK`, and the index $j_2$ of the most recent element with a value of `maxK`, both initially set to $-1$. Therefore, the left endpoint of the current element `nums[i]` must be less than or equal to $\min(j_1, j_2)$. -1. In summary, the number of bounded subarrays with the current element as the right endpoint is $\max(0, \min(j_1, j_2) - k)$. Add up all the counts to get the result. +1. Maintain the index $k$ of the most recent element that is not within the range $[\textit{minK}, \textit{maxK}]$, initialized to $-1$. The left endpoint of the current element $\textit{nums}[i]$ must be greater than $k$. +2. Maintain the most recent index $j_1$ where the value is $\textit{minK}$ and the most recent index $j_2$ where the value is $\textit{maxK}$, both initialized to $-1$. The left endpoint of the current element $\textit{nums}[i]$ must be less than or equal to $\min(j_1, j_2)$. +3. Based on the above, the number of bounded subarrays with the current element as the right endpoint is $\max\bigl(0,\ \min(j_1, j_2) - k\bigr)$. Accumulate all these counts to get the result. -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. +The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$. @@ -131,10 +131,16 @@ public: long long countSubarrays(vector & nums, int minK, int maxK) { long long ans = 0; int j1 = -1, j2 = -1, k = -1; - for (int i = 0; i < nums.size(); ++i) { - if (nums[i] < minK || nums[i] > maxK) k = i; - if (nums[i] == minK) j1 = i; - if (nums[i] == maxK) j2 = i; + for (int i = 0; i < static_cast (nums.size()); ++i) { + if (nums[i] < minK || nums[i] > maxK) { + k = i; + } + if (nums[i] == minK) { + j1 = i; + } + if (nums[i] == maxK) { + j2 = i; + } ans += max(0, min(j1, j2) - k); } return ans; @@ -168,23 +174,15 @@ func countSubarrays(nums []int, minK int, maxK int) int64 { ```ts function countSubarrays(nums: number[], minK: number, maxK: number): number { - let res = 0; - let minIndex = -1; - let maxIndex = -1; - let k = -1; - nums.forEach((num, i) => { - if (num === minK) { - minIndex = i; - } - if (num === maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += Math.max(Math.min(minIndex, maxIndex) - k, 0); - }); - return res; + let ans = 0; + let [j1, j2, k] = [-1, -1, -1]; + for (let i = 0; i < nums.length; ++i) { + if (nums[i] < minK || nums[i] > maxK) k = i; + if (nums[i] === minK) j1 = i; + if (nums[i] === maxK) j2 = i; + ans += Math.max(0, Math.min(j1, j2) - k); + } + return ans; } ``` @@ -193,25 +191,27 @@ function countSubarrays(nums: number[], minK: number, maxK: number): number { ```rust impl Solution { pub fn count_subarrays(nums: Vec , min_k: i32, max_k: i32) -> i64 { - let mut res = 0; - let mut min_index = -1; - let mut max_index = -1; - let mut k = -1; - for i in 0..nums.len() { - let num = nums[i]; + let mut ans: i64 = 0; + let mut j1: i64 = -1; + let mut j2: i64 = -1; + let mut k: i64 = -1; + for (i, &v) in nums.iter().enumerate() { let i = i as i64; - if num == min_k { - min_index = i; + if v < min_k || v > max_k { + k = i; } - if num == max_k { - max_index = i; + if v == min_k { + j1 = i; } - if num < min_k || num > max_k { - k = i; + if v == max_k { + j2 = i; + } + let m = j1.min(j2); + if m > k { + ans += m - k; } - res += (0).max(min_index.min(max_index) - k); } - res + ans } } ``` @@ -219,28 +219,17 @@ impl Solution { #### C ```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { - long long res = 0; - int minIndex = -1; - int maxIndex = -1; - int k = -1; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num == minK) { - minIndex = i; - } - if (num == maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += max(min(minIndex, maxIndex) - k, 0); + long long ans = 0; + int j1 = -1, j2 = -1, k = -1; + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < minK || nums[i] > maxK) k = i; + if (nums[i] == minK) j1 = i; + if (nums[i] == maxK) j2 = i; + int m = j1 < j2 ? j1 : j2; + if (m > k) ans += (long long) (m - k); } - return res; + return ans; } ``` diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c index 79b6e9f914c78..103d8562484b6 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.c @@ -1,23 +1,12 @@ -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { - long long res = 0; - int minIndex = -1; - int maxIndex = -1; - int k = -1; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num == minK) { - minIndex = i; - } - if (num == maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += max(min(minIndex, maxIndex) - k, 0); + long long ans = 0; + int j1 = -1, j2 = -1, k = -1; + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < minK || nums[i] > maxK) k = i; + if (nums[i] == minK) j1 = i; + if (nums[i] == maxK) j2 = i; + int m = j1 < j2 ? j1 : j2; + if (m > k) ans += (long long) (m - k); } - return res; -} \ No newline at end of file + return ans; +} diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.cpp b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.cpp index c86cccf957ff6..4efd60861e03a 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.cpp +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.cpp @@ -3,12 +3,18 @@ class Solution { long long countSubarrays(vector & nums, int minK, int maxK) { long long ans = 0; int j1 = -1, j2 = -1, k = -1; - for (int i = 0; i < nums.size(); ++i) { - if (nums[i] < minK || nums[i] > maxK) k = i; - if (nums[i] == minK) j1 = i; - if (nums[i] == maxK) j2 = i; + for (int i = 0; i < static_cast (nums.size()); ++i) { + if (nums[i] < minK || nums[i] > maxK) { + k = i; + } + if (nums[i] == minK) { + j1 = i; + } + if (nums[i] == maxK) { + j2 = i; + } ans += max(0, min(j1, j2) - k); } return ans; } -}; \ No newline at end of file +}; diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.rs b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.rs index 5b0737dd0d011..49f7a9e3f736e 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.rs +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.rs @@ -1,23 +1,25 @@ impl Solution { pub fn count_subarrays(nums: Vec , min_k: i32, max_k: i32) -> i64 { - let mut res = 0; - let mut min_index = -1; - let mut max_index = -1; - let mut k = -1; - for i in 0..nums.len() { - let num = nums[i]; + let mut ans: i64 = 0; + let mut j1: i64 = -1; + let mut j2: i64 = -1; + let mut k: i64 = -1; + for (i, &v) in nums.iter().enumerate() { let i = i as i64; - if num == min_k { - min_index = i; + if v < min_k || v > max_k { + k = i; } - if num == max_k { - max_index = i; + if v == min_k { + j1 = i; } - if num < min_k || num > max_k { - k = i; + if v == max_k { + j2 = i; + } + let m = j1.min(j2); + if m > k { + ans += m - k; } - res += (0).max(min_index.min(max_index) - k); } - res + ans } } diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.ts b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.ts index 015f4051d37d3..d02b08888d372 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.ts +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/Solution.ts @@ -1,19 +1,11 @@ function countSubarrays(nums: number[], minK: number, maxK: number): number { - let res = 0; - let minIndex = -1; - let maxIndex = -1; - let k = -1; - nums.forEach((num, i) => { - if (num === minK) { - minIndex = i; - } - if (num === maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += Math.max(Math.min(minIndex, maxIndex) - k, 0); - }); - return res; + let ans = 0; + let [j1, j2, k] = [-1, -1, -1]; + for (let i = 0; i < nums.length; ++i) { + if (nums[i] < minK || nums[i] > maxK) k = i; + if (nums[i] === minK) j1 = i; + if (nums[i] === maxK) j2 = i; + ans += Math.max(0, Math.min(j1, j2) - k); + } + return ans; } diff --git a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md index 8f0d867aa8cf8..191d9c2169c33 100644 --- a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md +++ b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md @@ -7,6 +7,7 @@ tags: - 脑筋急转弯 - 数组 - 数学 + - 前缀和 --- diff --git a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md index dea25e375b8c0..f1e6fed05473e 100644 --- a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md +++ b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md @@ -7,6 +7,7 @@ tags: - Brainteaser - Array - Math + - Prefix Sum --- diff --git a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md index ddc1aad7d23b1..2b142c01d33c3 100644 --- a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md +++ b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md @@ -65,11 +65,11 @@ tags: 我们注意到,最大差值具备单调性,即如果最大差值 $x$ 满足条件,那么 $x-1$ 也一定满足条件。因此我们可以使用二分查找的方法,找到最小的满足条件的最大差值。 -我们可以将数组 `nums` 排序,然后枚举最大差值 $x$,判断是否存在 $p$ 个下标对,每个下标对对应数值取差值的最大值不超过 $x$。如果存在,那么我们就可以将 $x$ 减小,否则我们就将 $x$ 增大。 +我们可以将数组 $\textit{nums}$ 排序,然后枚举最大差值 $x$,判断是否存在 $p$ 个下标对,每个下标对对应数值取差值的最大值不超过 $x$。如果存在,那么我们就可以将 $x$ 减小,否则我们就将 $x$ 增大。 -判断是否存在 $p$ 个下标对,每个下标对对应数值取差值的最大值不超过 $x$,可以使用贪心的方法。我们从左到右遍历数组 `nums`,对于当前遍历到的下标 $i$,如果 $i+1$ 位置的数与 $i$ 位置的数的差值不超过 $x$,那么我们就可以将 $i$ 和 $i+1$ 位置的数作为一个下标对,更新下标对的数量 $cnt$,然后将 $i$ 的值增加 $2$。否则,我们就将 $i$ 的值增加 $1$。遍历结束,如果 $cnt$ 的值大于等于 $p$,那么就说明存在 $p$ 个下标对,每个下标对对应数值取差值的最大值不超过 $x$,否则就说明不存在。 +判断是否存在 $p$ 个下标对,每个下标对对应数值取差值的最大值不超过 $x$,可以使用贪心的方法。我们从左到右遍历数组 $\textit{nums}$,对于当前遍历到的下标 $i$,如果 $i+1$ 位置的数与 $i$ 位置的数的差值不超过 $x$,那么我们就可以将 $i$ 和 $i+1$ 位置的数作为一个下标对,更新下标对的数量 $cnt$,然后将 $i$ 的值增加 $2$。否则,我们就将 $i$ 的值增加 $1$。遍历结束,如果 $cnt$ 的值大于等于 $p$,那么就说明存在 $p$ 个下标对,每个下标对对应数值取差值的最大值不超过 $x$,否则就说明不存在。 -时间复杂度 $O(n \times (\log n + \log m))$,其中 $n$ 是数组 `nums` 的长度,而 $m$ 是数组 `nums` 中的最大值与最小值的差值。空间复杂度 $O(1)$。 +时间复杂度 $O(n \times (\log n + \log m))$,其中 $n$ 是数组 $\textit{nums}$ 的长度,而 $m$ 是数组 $\textit{nums}$ 中的最大值与最小值的差值。空间复杂度 $O(1)$。 @@ -176,6 +176,73 @@ func minimizeMax(nums []int, p int) int { } ``` +#### TypeScript + +```ts +function minimizeMax(nums: number[], p: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let l = 0, + r = nums[n - 1] - nums[0] + 1; + const check = (diff: number): boolean => { + let cnt = 0; + for (let i = 0; i < n - 1; ++i) { + if (nums[i + 1] - nums[i] <= diff) { + ++cnt; + ++i; + } + } + return cnt >= p; + }; + while (l < r) { + const mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn minimize_max(mut nums: Vec , p: i32) -> i32 { + nums.sort(); + let n = nums.len(); + let (mut l, mut r) = (0, nums[n - 1] - nums[0] + 1); + + let check = |diff: i32| -> bool { + let mut cnt = 0; + let mut i = 0; + while i < n - 1 { + if nums[i + 1] - nums[i] <= diff { + cnt += 1; + i += 2; + } else { + i += 1; + } + } + cnt >= p + }; + + while l < r { + let mid = (l + r) / 2; + if check(mid) { + r = mid; + } else { + l = mid + 1; + } + } + + l + } +} +``` + diff --git a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md index 5cc179665dfd8..f853062cb3f20 100644 --- a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md +++ b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md @@ -59,15 +59,15 @@ The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, -### Solution 1: Binary search + Greedy +### Solution 1: Binary Search + Greedy -We find that the maximum difference has the monotonicity, that is, if the maximum difference $x$ satisfies the condition, then $x-1$ must also satisfy the condition. Therefore, we can use the binary search method to find the smallest maximum difference that satisfies the condition. +We notice that the maximum difference has monotonicity: if a maximum difference $x$ is feasible, then $x-1$ is also feasible. Therefore, we can use binary search to find the minimal feasible maximum difference. -We can sort the array `nums`, then enumerate the maximum difference $x$, and determine whether there are $p$ index pairs, where each index pair corresponds to the maximum value of the difference of the corresponding value. If it exists, we can reduce $x$, otherwise we can increase $x$. +First, sort the array $\textit{nums}$. Then, for a given maximum difference $x$, check whether it is possible to form $p$ pairs of indices such that the maximum difference in each pair does not exceed $x$. If possible, we can try a smaller $x$; otherwise, we need to increase $x$. -Determine whether there are $p$ index pairs, where each index pair corresponds to the maximum value of the difference of the corresponding value, which can be achieved by using the greedy method. We traverse the array `nums` from left to right, and for the current traversed index $i$, if the difference between the number at the $i+1$ position and the number at the $i$ position is no more than $x$, then we can take the number at the $i$ and $i+1$ positions as an index pair, update the number of index pairs $cnt$, and then increase the value of $i$ by $2$. Otherwise, we will increase the value of $i$ by $1$. When the traversal is over, if the value of $cnt$ is greater than or equal to $p$, then it means that there are $p$ index pairs, where each index pair corresponds to the maximum value of the difference of the corresponding value, otherwise it means that it does not exist. +To check whether $p$ such pairs exist with maximum difference at most $x$, we can use a greedy approach. Traverse the sorted array $\textit{nums}$ from left to right. For the current index $i$, if the difference between $\textit{nums}[i+1]$ and $\textit{nums}[i]$ does not exceed $x$, we can form a pair with $i$ and $i+1$, increment the pair count $cnt$, and increase $i$ by $2$. Otherwise, increase $i$ by $1$. After traversing, if $cnt \geq p$, then such $p$ pairs exist; otherwise, they do not. -The time complexity is $O(n \times (\log n + \log m))$, where $n$ is the length of the array `nums`, and $m$ is the difference between the maximum value and the minimum value in the array `nums`. The space complexity is $O(1)$. +The time complexity is $O(n \times (\log n + \log m))$, where $n$ is the length of $\textit{nums}$ and $m$ is the difference between the maximum and minimum values in $\textit{nums}$. The space complexity is $O(1)$. @@ -174,6 +174,73 @@ func minimizeMax(nums []int, p int) int { } ``` +#### TypeScript + +```ts +function minimizeMax(nums: number[], p: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let l = 0, + r = nums[n - 1] - nums[0] + 1; + const check = (diff: number): boolean => { + let cnt = 0; + for (let i = 0; i < n - 1; ++i) { + if (nums[i + 1] - nums[i] <= diff) { + ++cnt; + ++i; + } + } + return cnt >= p; + }; + while (l < r) { + const mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn minimize_max(mut nums: Vec , p: i32) -> i32 { + nums.sort(); + let n = nums.len(); + let (mut l, mut r) = (0, nums[n - 1] - nums[0] + 1); + + let check = |diff: i32| -> bool { + let mut cnt = 0; + let mut i = 0; + while i < n - 1 { + if nums[i + 1] - nums[i] <= diff { + cnt += 1; + i += 2; + } else { + i += 1; + } + } + cnt >= p + }; + + while l < r { + let mid = (l + r) / 2; + if check(mid) { + r = mid; + } else { + l = mid + 1; + } + } + + l + } +} +``` + diff --git a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/Solution.rs b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/Solution.rs new file mode 100644 index 0000000000000..8a96ae5c777f3 --- /dev/null +++ b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/Solution.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn minimize_max(mut nums: Vec , p: i32) -> i32 { + nums.sort(); + let n = nums.len(); + let (mut l, mut r) = (0, nums[n - 1] - nums[0] + 1); + + let check = |diff: i32| -> bool { + let mut cnt = 0; + let mut i = 0; + while i < n - 1 { + if nums[i + 1] - nums[i] <= diff { + cnt += 1; + i += 2; + } else { + i += 1; + } + } + cnt >= p + }; + + while l < r { + let mid = (l + r) / 2; + if check(mid) { + r = mid; + } else { + l = mid + 1; + } + } + + l + } +} diff --git a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/Solution.ts b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/Solution.ts new file mode 100644 index 0000000000000..0895239385de8 --- /dev/null +++ b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/Solution.ts @@ -0,0 +1,25 @@ +function minimizeMax(nums: number[], p: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let l = 0, + r = nums[n - 1] - nums[0] + 1; + const check = (diff: number): boolean => { + let cnt = 0; + for (let i = 0; i < n - 1; ++i) { + if (nums[i + 1] - nums[i] <= diff) { + ++cnt; + ++i; + } + } + return cnt >= p; + }; + while (l < r) { + const mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; +} diff --git a/solution/2600-2699/2621.Sleep/README.md b/solution/2600-2699/2621.Sleep/README.md index 88f995e11453a..5f782abfc976f 100644 --- a/solution/2600-2699/2621.Sleep/README.md +++ b/solution/2600-2699/2621.Sleep/README.md @@ -18,6 +18,8 @@ tags: 请你编写一个异步函数,它接收一个正整数参数
+millis
,并休眠millis
毫秒。要求此函数可以解析任何值。请注意,实际睡眠持续时间与
+millis
之间的微小偏差是可以接受的。
示例 1:
diff --git a/solution/2600-2699/2621.Sleep/README_EN.md b/solution/2600-2699/2621.Sleep/README_EN.md index e90b69edc9ba3..4f8484d8dc0a0 100644 --- a/solution/2600-2699/2621.Sleep/README_EN.md +++ b/solution/2600-2699/2621.Sleep/README_EN.md @@ -18,6 +18,8 @@ tags:Given a positive integer
+millis
, write an asynchronous function that sleeps formillis
milliseconds. It can resolve any value.Note that minor deviation from
+millis
in the actual sleep duration is acceptable.
Example 1:
diff --git a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md index 640abb4822276..30137409dfe21 100644 --- a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md +++ b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md @@ -18,39 +18,47 @@ tags: -给你一个下标从 0 开始、长度为
+n
的数组nums
。一开始,所有元素都是 未染色 (值为0
)的。给定一个整数
-n
表示一个长度为n
的数组colors
,初始所有元素均为 0 ,表示是 未染色 的。同时给定一个二维整数数组queries
,其中queries[i] = [indexi, colori]
。对于第i
个 查询:给你一个二维整数数组
+queries
,其中queries[i] = [indexi, colori]
。+
-- 将
+colors[indexi]
染色为colori
。- 统计
+colors
中颜色相同的相邻对的数量(无论colori
)。对于每个操作,你需要将数组
+nums
中下标为indexi
的格子染色为colori
。请你返回一个长度与
-queries
相等的数组answer
,其中answer[i]
是前i
个操作的答案。请你返回一个长度与
+queries
相等的数组answer
,其中answer[i]
是前i
个操作 之后 ,相邻元素颜色相同的数目。-
更正式的,
+answer[i]
是执行完前i
个操作后,0 <= j < n - 1
的下标j
中,满足nums[j] == nums[j + 1]
且nums[j] != 0
的数目。示例 1:
-+
++ +输入:n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]
+ +输出:[0,1,1,0,2]
+ +解释:
+ ++
+- 一开始 colors = [0,0,0,0],其中 0 表示数组中未染色的元素。
+- 在第 1 次查询后 colors = [2,0,0,0]。颜色相同的相邻对的数量是 0。
+- 在第 2 次查询后 colors = [2,2,0,0]。颜色相同的相邻对的数量是 1。
+- 在第 3 次查询后 colors = [2,2,0,1]。颜色相同的相邻对的数量是 1。
+- 在第 4 次查询后 colors = [2,1,0,1]。颜色相同的相邻对的数量是 0。
+- 在第 5 次查询后 colors = [2,1,1,1]。颜色相同的相邻对的数量是 2。
+示例 2:
+ ++输入:n = 1, queries = [[0,100000]]
+ +输出:[0]
+ +解释:
-示例 1:
- --输入:n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]] -输出:[0,1,1,0,2] -解释:一开始数组 nums = [0,0,0,0] ,0 表示数组中还没染色的元素。 -- 第 1 个操作后,nums = [2,0,0,0] 。相邻元素颜色相同的数目为 0 。 -- 第 2 个操作后,nums = [2,2,0,0] 。相邻元素颜色相同的数目为 1 。 -- 第 3 个操作后,nums = [2,2,0,1] 。相邻元素颜色相同的数目为 1 。 -- 第 4 个操作后,nums = [2,1,0,1] 。相邻元素颜色相同的数目为 0 。 -- 第 5 个操作后,nums = [2,1,1,1] 。相邻元素颜色相同的数目为 2 。 -- -示例 2:
- --输入:n = 1, queries = [[0,100000]] -输出:[0] -解释:一开始数组 nums = [0] ,0 表示数组中还没染色的元素。 -- 第 1 个操作后,nums = [100000] 。相邻元素颜色相同的数目为 0 。 -+在第一次查询后 colors = [100000]。颜色相同的相邻对的数量是 0。
+diff --git a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md index 1206255526b57..e949a71eecaf4 100644 --- a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md +++ b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md @@ -22,7 +22,7 @@ tags:
- Set
-colors[indexi]
tocolori
.- Count adjacent pairs in
+colors
set to the same color (regardless ofcolori
).- Count the number of adjacent pairs in
colors
which have the same color (regardless ofcolori
).Return an array
diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.rs b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.rs new file mode 100644 index 0000000000000..fa60ca6265f1d --- /dev/null +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/Solution.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn difference_of_sums(n: i32, m: i32) -> i32 { + let mut ans = 0; + for i in 1..=n { + if i % m != 0 { + ans += i; + } else { + ans -= i; + } + } + ans + } +} diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md index b48e43453d133..2146caa7a4a22 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md @@ -21,13 +21,13 @@ tags: -answer
of the same length asqueries
whereanswer[i]
is the answer to theith
query.给你一个下标从 0 开始的字符串数组
+words
,和一个下标从 0 开始的 二进制 数组groups
,两个数组长度都是n
。给定一个字符串数组
-words
,和一个 二进制 数组groups
,两个数组长度都是n
。你需要从
+words
中选出 最长子序列。如果对于序列中的任何两个连续串,二进制数组groups
中它们的对应元素不同,则words
的子序列是不同的。如果
-words
的一个 子序列 是交替的,那么对于序列中的任意两个连续字符串,它们在groups
中相同索引的对应元素是 不同 的(也就是说,不能有连续的 0 或 1),正式来说,你需要从下标
+[0, 1, ..., n - 1]
中选出一个 最长子序列 ,将这个子序列记作长度为k
的[i0, i1, ..., ik - 1]
,对于所有满足0 <= j < k - 1
的j
都有groups[ij] != groups[ij + 1]
。你需要从
-words
中选出 最长交替子序列。请你返回一个字符串数组,它是下标子序列 依次 对应
+words
数组中的字符串连接形成的字符串数组。如果有多个答案,返回 任意 一个。返回选出的子序列。如果有多个答案,返回 任意 一个。
注意:
@@ -87,9 +87,7 @@ tags: ```python class Solution: - def getWordsInLongestSubsequence( - self, n: int, words: List[str], groups: List[int] - ) -> List[str]: + def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: return [words[i] for i, x in enumerate(groups) if i == 0 or x != groups[i - 1]] ``` @@ -97,7 +95,8 @@ class Solution: ```java class Solution { - public Listwords
中的元素是不同的 。getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + public List getLongestSubsequence(String[] words, int[] groups) { + int n = groups.length; List ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { @@ -114,7 +113,8 @@ class Solution { ```cpp class Solution { public: - vector getWordsInLongestSubsequence(int n, vector & words, vector & groups) { + vector getLongestSubsequence(vector & words, vector & groups) { + int n = groups.size(); vector ans; for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { @@ -129,7 +129,7 @@ public: #### Go ```go -func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []string) { +func getLongestSubsequence(words []string, groups []int) (ans []string) { for i, x := range groups { if i == 0 || x != groups[i-1] { ans = append(ans, words[i]) @@ -142,9 +142,9 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []st #### TypeScript ```ts -function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { +function getLongestSubsequence(words: string[], groups: number[]): string[] { const ans: string[] = []; - for (let i = 0; i < n; ++i) { + for (let i = 0; i < groups.length; ++i) { if (i === 0 || groups[i] !== groups[i - 1]) { ans.push(words[i]); } @@ -157,19 +157,13 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number ```rust impl Solution { - pub fn get_words_in_longest_subsequence( - n: i32, - words: Vec , - groups: Vec , - ) -> Vec { - let mut ans = vec![]; - - for i in 0..n { - if i == 0 || groups[i as usize] != groups[(i - 1) as usize] { - ans.push(words[i as usize].clone()); + pub fn get_longest_subsequence(words: Vec , groups: Vec ) -> Vec { + let mut ans = Vec::new(); + for (i, &g) in groups.iter().enumerate() { + if i == 0 || g != groups[i - 1] { + ans.push(words[i].clone()); } } - ans } } diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md index 913cdda134f56..859576754bba7 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md @@ -21,11 +21,11 @@ tags: - You are given a string array
+words
and a binary arraygroups
both of lengthn
, wherewords[i]
is associated withgroups[i]
.You are given a string array
-words
and a binary arraygroups
both of lengthn
.Your task is to select the longest alternating subsequence from
+words
. A subsequence ofwords
is alternating if for any two consecutive strings in the sequence, their corresponding elements in the binary arraygroups
differ. Essentially, you are to choose strings such that adjacent elements have non-matching corresponding bits in thegroups
array.A subsequence of
-words
is alternating if for any two consecutive strings in the sequence, their corresponding elements at the same indices ingroups
are different (that is, there cannot be consecutive 0 or 1).Formally, you need to find the longest subsequence of an array of indices
+[0, 1, ..., n - 1]
denoted as[i0, i1, ..., ik-1]
, such thatgroups[ij] != groups[ij+1]
for each0 <= j < k - 1
and then find the words corresponding to these indices.Your task is to select the longest alternating subsequence from
words
.Return the selected subsequence. If there are multiple answers, return any of them.
@@ -111,9 +111,7 @@ The time complexity is $O(n)$, where $n$ is the length of the array $groups$. Th ```python class Solution: - def getWordsInLongestSubsequence( - self, n: int, words: List[str], groups: List[int] - ) -> List[str]: + def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: return [words[i] for i, x in enumerate(groups) if i == 0 or x != groups[i - 1]] ``` @@ -121,7 +119,8 @@ class Solution: ```java class Solution { - public ListgetWordsInLongestSubsequence(int n, String[] words, int[] groups) { + public List getLongestSubsequence(String[] words, int[] groups) { + int n = groups.length; List ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { @@ -138,7 +137,8 @@ class Solution { ```cpp class Solution { public: - vector getWordsInLongestSubsequence(int n, vector & words, vector & groups) { + vector getLongestSubsequence(vector & words, vector & groups) { + int n = groups.size(); vector ans; for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { @@ -153,7 +153,7 @@ public: #### Go ```go -func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []string) { +func getLongestSubsequence(words []string, groups []int) (ans []string) { for i, x := range groups { if i == 0 || x != groups[i-1] { ans = append(ans, words[i]) @@ -166,9 +166,9 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []st #### TypeScript ```ts -function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { +function getLongestSubsequence(words: string[], groups: number[]): string[] { const ans: string[] = []; - for (let i = 0; i < n; ++i) { + for (let i = 0; i < groups.length; ++i) { if (i === 0 || groups[i] !== groups[i - 1]) { ans.push(words[i]); } @@ -181,19 +181,13 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number ```rust impl Solution { - pub fn get_words_in_longest_subsequence( - n: i32, - words: Vec , - groups: Vec , - ) -> Vec { - let mut ans = vec![]; - - for i in 0..n { - if i == 0 || groups[i as usize] != groups[(i - 1) as usize] { - ans.push(words[i as usize].clone()); + pub fn get_longest_subsequence(words: Vec , groups: Vec ) -> Vec { + let mut ans = Vec::new(); + for (i, &g) in groups.iter().enumerate() { + if i == 0 || g != groups[i - 1] { + ans.push(words[i].clone()); } } - ans } } diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.cpp b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.cpp index c686de7e6c4d1..177cf71800f51 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.cpp +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.cpp @@ -1,6 +1,7 @@ class Solution { public: - vector getWordsInLongestSubsequence(int n, vector & words, vector & groups) { + vector getLongestSubsequence(vector & words, vector & groups) { + int n = groups.size(); vector ans; for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.go b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.go index 0fbd97a384c83..6acc292202785 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.go +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.go @@ -1,4 +1,4 @@ -func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []string) { +func getLongestSubsequence(words []string, groups []int) (ans []string) { for i, x := range groups { if i == 0 || x != groups[i-1] { ans = append(ans, words[i]) diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.java b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.java index 9e3b87d016e6d..4427ba33b47cf 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.java +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.java @@ -1,5 +1,6 @@ class Solution { - public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + public List getLongestSubsequence(String[] words, int[] groups) { + int n = groups.length; List ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.py b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.py index 250331a458490..bde890e899558 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.py +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.py @@ -1,5 +1,3 @@ class Solution: - def getWordsInLongestSubsequence( - self, n: int, words: List[str], groups: List[int] - ) -> List[str]: + def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: return [words[i] for i, x in enumerate(groups) if i == 0 or x != groups[i - 1]] diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.rs b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.rs index 66c780a2540ba..66b874fa2b1f8 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.rs +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.rs @@ -1,17 +1,11 @@ impl Solution { - pub fn get_words_in_longest_subsequence( - n: i32, - words: Vec , - groups: Vec , - ) -> Vec { - let mut ans = vec![]; - - for i in 0..n { - if i == 0 || groups[i as usize] != groups[(i - 1) as usize] { - ans.push(words[i as usize].clone()); + pub fn get_longest_subsequence(words: Vec , groups: Vec ) -> Vec { + let mut ans = Vec::new(); + for (i, &g) in groups.iter().enumerate() { + if i == 0 || g != groups[i - 1] { + ans.push(words[i].clone()); } } - ans } } diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.ts b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.ts index 71386aa0ab21c..b59277df43595 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.ts +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/Solution.ts @@ -1,6 +1,6 @@ -function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { +function getLongestSubsequence(words: string[], groups: number[]): string[] { const ans: string[] = []; - for (let i = 0; i < n; ++i) { + for (let i = 0; i < groups.length; ++i) { if (i === 0 || groups[i] !== groups[i - 1]) { ans.push(words[i]); } diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md index 4758e78c64610..c61c784a7b002 100644 --- a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md @@ -20,7 +20,7 @@ tags: - 给你一个整数
+n
和一个下标从 0 开始的字符串数组words
,和一个下标从 0 开始的数组groups
,两个数组长度都是n
。给定一个字符串数组
words
,和一个数组groups
,两个数组长度都是n
。两个长度相等字符串的 汉明距离 定义为对应位置字符 不同 的数目。
@@ -42,7 +42,7 @@ tags:示例 1:
-输入:n = 3, words = ["bab","dab","cab"], groups = [1,2,2] +输入:words = ["bab","dab","cab"], groups = [1,2,2] 输出:["bab","cab"] 解释:一个可行的子序列是 [0,2] 。 - groups[0] != groups[2] @@ -57,7 +57,7 @@ tags:示例 2:
-输入:n = 4, words = ["a","b","c","d"], groups = [1,2,3,4] +输入:words = ["a","b","c","d"], groups = [1,2,3,4] 输出:["a","b","c","d"] 解释:我们选择子序列 [0,1,2,3] 。 它同时满足两个条件。 @@ -103,11 +103,12 @@ tags: ```python class Solution: def getWordsInLongestSubsequence( - self, n: int, words: List[str], groups: List[int] + self, words: List[str], groups: List[int] ) -> List[str]: def check(s: str, t: str) -> bool: return len(s) == len(t) and sum(a != b for a, b in zip(s, t)) == 1 + n = len(groups) f = [1] * n g = [-1] * n mx = 1 @@ -132,7 +133,8 @@ class Solution: ```java class Solution { - public ListgetWordsInLongestSubsequence(int n, String[] words, int[] groups) { + public List getWordsInLongestSubsequence(String[] words, int[] groups) { + int n = groups.length; int[] f = new int[n]; int[] g = new int[n]; Arrays.fill(f, 1); @@ -180,7 +182,7 @@ class Solution { ```cpp class Solution { public: - vector getWordsInLongestSubsequence(int n, vector & words, vector & groups) { + vector getWordsInLongestSubsequence(vector & words, vector & groups) { auto check = [](string& s, string& t) { if (s.size() != t.size()) { return false; @@ -191,6 +193,7 @@ public: } return cnt == 1; }; + int n = groups.size(); vector f(n, 1); vector g(n, -1); int mx = 1; @@ -221,7 +224,7 @@ public: #### Go ```go -func getWordsInLongestSubsequence(n int, words []string, groups []int) []string { +func getWordsInLongestSubsequence(words []string, groups []int) []string { check := func(s, t string) bool { if len(s) != len(t) { return false @@ -234,6 +237,7 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) []string } return cnt == 1 } + n := len(groups) f := make([]int, n) g := make([]int, n) for i := range f { @@ -261,9 +265,7 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) []string break } } - for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { - ans[i], ans[j] = ans[j], ans[i] - } + slices.Reverse(ans) return ans } ``` @@ -271,7 +273,8 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) []string #### TypeScript ```ts -function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { +function getWordsInLongestSubsequence(words: string[], groups: number[]): string[] { + const n = groups.length; const f: number[] = Array(n).fill(1); const g: number[] = Array(n).fill(-1); let mx = 1; @@ -313,16 +316,12 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number ```rust impl Solution { - pub fn get_words_in_longest_subsequence( - n: i32, - words: Vec , - groups: Vec , - ) -> Vec { + pub fn get_words_in_longest_subsequence(words: Vec , groups: Vec ) -> Vec