diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index 380f6a59f18be..9cbadf57631dc 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -1,6 +1,7 @@
name: deploy
on:
+ workflow_dispatch:
push:
branches:
- main
@@ -12,86 +13,118 @@ on:
- lcof/**
- lcci/**
- basic/**
- workflow_dispatch:
-
-env:
- MKDOCS_API_KEYS: ${{ secrets.MKDOCS_API_KEYS }}
-
-permissions:
- contents: write
concurrency:
- group: ${{github.workflow}} - ${{github.ref}}
+ group: ${{ github.workflow }} - ${{ github.ref }}
cancel-in-progress: true
jobs:
- deploy:
+ build:
runs-on: ubuntu-latest
- if: github.repository == 'doocs/leetcode'
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
+ 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: Deploy
- uses: peaceiris/actions-gh-pages@v4
+ - 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:
- github_token: ${{ secrets.GITHUB_TOKEN }}
- publish_dir: ./site
- cname: leetcode.doocs.org
-
- # sync:
- # runs-on: ubuntu-latest
- # needs: deploy
- # if: github.repository == 'doocs/leetcode'
- # steps:
- # - name: Sync to gitee.com
- # uses: wearerequired/git-mirror-action@master
- # env:
- # SSH_PRIVATE_KEY: ${{ secrets.RSA_PRIVATE_KEY }}
- # with:
- # source-repo: git@github.com:doocs/leetcode.git
- # destination-repo: git@gitee.com:Doocs/leetcode.git
-
- # - name: Build Gitee Pages
- # uses: yanglbme/gitee-pages-action@main
- # with:
- # gitee-username: yanglbme
- # gitee-password: ${{ secrets.GITEE_PASSWORD }}
- # gitee-repo: doocs/leetcode
- # branch: gh-pages
+ path: ./site
+
+ deploy:
+ needs: build
+ runs-on: ubuntu-latest
+ permissions:
+ pages: write
+ id-token: write
+ environment:
+ name: github_pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.github/workflows/pr-add-label.yml b/.github/workflows/pr-add-label.yml
new file mode 100644
index 0000000000000..82661e9eb237e
--- /dev/null
+++ b/.github/workflows/pr-add-label.yml
@@ -0,0 +1,25 @@
+name: pr-add-label
+
+on:
+ pull_request_target:
+ types: [opened, edited, reopened, synchronize]
+
+jobs:
+ add-label:
+ permissions:
+ contents: read
+ pull-requests: write
+ runs-on: ubuntu-latest
+ if: github.repository == 'doocs/leetcode'
+ steps:
+ - name: Check PR number
+ id: pr_number
+ run: echo "PR_NUMBER=${{ github.event.pull_request.number }}" >> $GITHUB_ENV
+
+ - name: Run add-label Action
+ uses: actionv/pr-label-action@master
+ with:
+ github_token: ${{ secrets.DOOCS_BOT_ACTION_TOKEN }}
+ pr_number: ${{ env.PR_NUMBER }}
+ organize_name: "doocs"
+ team_name: "leetcode-algorithm"
diff --git a/.gitignore b/.gitignore
index e8ebbedd5ad1e..521323b59d92d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,10 +3,13 @@
.vscode
.temp
.vitepress
-.cache
*.iml
__pycache__
/node_modules
/solution/result.json
/solution/__pycache__
/solution/.env
+.cache
+!.cache/plugin/
+!.cache/plugin/git-committers/
+!.cache/plugin/git-committers/page-authors.json
\ No newline at end of file
diff --git a/README.md b/README.md
index 761cfcad81eae..aa8c9b92c5efa 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,8 @@
-
+
+
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
-@@ -555,6 +555,48 @@ class Solution { } ``` +#### C + +```c +char* d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + +char** letterCombinations(char* digits, int* returnSize) { + if (!*digits) { + *returnSize = 0; + return NULL; + } + + int size = 1; + char** ans = (char**) malloc(sizeof(char*)); + ans[0] = strdup(""); + + for (int x = 0; digits[x]; ++x) { + char* s = d[digits[x] - '2']; + int len = strlen(s); + char** t = (char**) malloc(sizeof(char*) * size * len); + int tSize = 0; + + for (int i = 0; i < size; ++i) { + for (int j = 0; j < len; ++j) { + int oldLen = strlen(ans[i]); + char* tmp = (char*) malloc(oldLen + 2); + strcpy(tmp, ans[i]); + tmp[oldLen] = s[j]; + tmp[oldLen + 1] = '\0'; + t[tSize++] = tmp; + } + free(ans[i]); + } + free(ans); + ans = t; + size = tSize; + } + + *returnSize = size; + return ans; +} +``` + diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md b/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md index ffad07737163e..dba840d7bd8ee 100644 --- a/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md @@ -551,6 +551,48 @@ class Solution { } ``` +#### C + +```c +char* d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + +char** letterCombinations(char* digits, int* returnSize) { + if (!*digits) { + *returnSize = 0; + return NULL; + } + + int size = 1; + char** ans = (char**) malloc(sizeof(char*)); + ans[0] = strdup(""); + + for (int x = 0; digits[x]; ++x) { + char* s = d[digits[x] - '2']; + int len = strlen(s); + char** t = (char**) malloc(sizeof(char*) * size * len); + int tSize = 0; + + for (int i = 0; i < size; ++i) { + for (int j = 0; j < len; ++j) { + int oldLen = strlen(ans[i]); + char* tmp = (char*) malloc(oldLen + 2); + strcpy(tmp, ans[i]); + tmp[oldLen] = s[j]; + tmp[oldLen + 1] = '\0'; + t[tSize++] = tmp; + } + free(ans[i]); + } + free(ans); + ans = t; + size = tSize; + } + + *returnSize = size; + return ans; +} +``` + diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.c b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.c new file mode 100644 index 0000000000000..e02c971a3a8c6 --- /dev/null +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.c @@ -0,0 +1,37 @@ +char* d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + +char** letterCombinations(char* digits, int* returnSize) { + if (!*digits) { + *returnSize = 0; + return NULL; + } + + int size = 1; + char** ans = (char**) malloc(sizeof(char*)); + ans[0] = strdup(""); + + for (int x = 0; digits[x]; ++x) { + char* s = d[digits[x] - '2']; + int len = strlen(s); + char** t = (char**) malloc(sizeof(char*) * size * len); + int tSize = 0; + + for (int i = 0; i < size; ++i) { + for (int j = 0; j < len; ++j) { + int oldLen = strlen(ans[i]); + char* tmp = (char*) malloc(oldLen + 2); + strcpy(tmp, ans[i]); + tmp[oldLen] = s[j]; + tmp[oldLen + 1] = '\0'; + t[tSize++] = tmp; + } + free(ans[i]); + } + free(ans); + ans = t; + size = tSize; + } + + *returnSize = size; + return ans; +} diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/1200px-telephone-keypad2svg.png b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/1200px-telephone-keypad2svg.png new file mode 100644 index 0000000000000..cbf69ae96598d Binary files /dev/null and b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/1200px-telephone-keypad2svg.png differ diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/1752723054-mfIHZs-image.png b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/1752723054-mfIHZs-image.png new file mode 100644 index 0000000000000..e4d9a76bfe05c Binary files /dev/null and b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/1752723054-mfIHZs-image.png differ diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/17_telephone_keypad.png b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/17_telephone_keypad.png deleted file mode 100644 index ef7a0bffee3e2..0000000000000 Binary files a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/17_telephone_keypad.png and /dev/null differ diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/200px-Telephone-keypad2.svg.png b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/200px-Telephone-keypad2.svg.png deleted file mode 100644 index 38764028d1835..0000000000000 Binary files a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/200px-Telephone-keypad2.svg.png and /dev/null differ diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/200px-telephone-keypad2svg.png b/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/200px-telephone-keypad2svg.png deleted file mode 100644 index 38764028d1835..0000000000000 Binary files a/solution/0000-0099/0017.Letter Combinations of a Phone Number/images/200px-telephone-keypad2svg.png and /dev/null differ diff --git a/solution/0000-0099/0020.Valid Parentheses/README.md b/solution/0000-0099/0020.Valid Parentheses/README.md index e4c364fe798a6..d09f9eda8a015 100644 --- a/solution/0000-0099/0020.Valid Parentheses/README.md +++ b/solution/0000-0099/0020.Valid Parentheses/README.md @@ -61,6 +61,14 @@ tags:
输出:true
+示例 5:
+ +输入:s = "([)]"
+ +输出:false
+
提示:
diff --git a/solution/0000-0099/0020.Valid Parentheses/README_EN.md b/solution/0000-0099/0020.Valid Parentheses/README_EN.md index cf0fc8a16deba..24c94a545cabb 100644 --- a/solution/0000-0099/0020.Valid Parentheses/README_EN.md +++ b/solution/0000-0099/0020.Valid Parentheses/README_EN.md @@ -60,6 +60,14 @@ tags:Output: true
+Example 5:
+ +Input: s = "([)]"
+ +Output: false
+
Constraints:
diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md b/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md index e7e07e00330c5..787342715e2e0 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md +++ b/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md @@ -35,7 +35,7 @@ tags: 1->3->4, 2->6 ] -merging them into one sorted list: +merging them into one sorted linked list: 1->1->2->3->4->4->5->6 diff --git a/solution/0000-0099/0049.Group Anagrams/README.md b/solution/0000-0099/0049.Group Anagrams/README.md index 404f965482ca4..20255463c7d4d 100644 --- a/solution/0000-0099/0049.Group Anagrams/README.md +++ b/solution/0000-0099/0049.Group Anagrams/README.md @@ -19,30 +19,41 @@ tags: -给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
- -字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
+给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
示例 1:
-
-输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
-输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
+输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
+ +输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
+ +解释:
+ +"bat"
。"nat"
和 "tan"
是字母异位词,因为它们可以重新排列以形成彼此。"ate"
,"eat"
和 "tea"
是字母异位词,因为它们可以重新排列以形成彼此。示例 2:
-
-输入: strs = [""]
-输出: [[""]]
-
+输入: strs = [""]
+ +输出: [[""]]
+示例 3:
-
-输入: strs = ["a"]
-输出: [["a"]]
+输入: strs = ["a"]
+ +输出: [["a"]]
+diff --git a/solution/0000-0099/0066.Plus One/README.md b/solution/0000-0099/0066.Plus One/README.md index 6c48f063bb6d3..a63a22c802037 100644 --- a/solution/0000-0099/0066.Plus One/README.md +++ b/solution/0000-0099/0066.Plus One/README.md @@ -17,11 +17,9 @@ tags: -
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
+给定一个表示 大整数 的整数数组 digits
,其中 digits[i]
是整数的第 i
位数字。这些数字按从左到右,从最高位到最低位排列。这个大整数不包含任何前导 0
。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
- -你可以假设除了整数 0 之外,这个整数不会以零开头。
+将大整数加 1,并返回结果的数字数组。
@@ -31,6 +29,8 @@ tags: 输入:digits = [1,2,3] 输出:[1,2,4] 解释:输入数组表示数字 123。 +加 1 后得到 123 + 1 = 124。 +因此,结果应该是 [1,2,4]。
示例 2:
@@ -39,6 +39,8 @@ tags: 输入:digits = [4,3,2,1] 输出:[4,3,2,2] 解释:输入数组表示数字 4321。 +加 1 后得到 4321 + 1 = 4322。 +因此,结果应该是 [4,3,2,2]。示例 3:
@@ -58,6 +60,7 @@ tags:1 <= digits.length <= 100
0 <= digits[i] <= 9
digits
不包含任何前导 0
。给你两个字符串 s
和 t
,统计并返回在 s
的 子序列 中 t
出现的个数,结果需要对 109 + 7 取模。
给你两个字符串 s
和 t
,统计并返回在 s
的 子序列 中 t
出现的个数。
测试用例保证结果在 32 位有符号整数范围内。
diff --git a/solution/0100-0199/0134.Gas Station/README.md b/solution/0100-0199/0134.Gas Station/README.md index 3ae6856d3f254..b350fca1ed379 100644 --- a/solution/0100-0199/0134.Gas Station/README.md +++ b/solution/0100-0199/0134.Gas Station/README.md @@ -57,10 +57,10 @@ tags:
提示:
gas.length == n
cost.length == n
n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
n == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
-
查询 Employee
表中第 n
高的工资。如果没有第 n
个最高工资,查询结果应该为 null
。
编写一个解决方案查询 Employee
表中第 n
高的 不同 工资。如果少于 n
个不同工资,查询结果应该为 null
。
查询结果格式如下所示。
diff --git a/solution/0100-0199/0177.Nth Highest Salary/README_EN.md b/solution/0100-0199/0177.Nth Highest Salary/README_EN.md index 37c056f9d75ef..3373a1cd68980 100644 --- a/solution/0100-0199/0177.Nth Highest Salary/README_EN.md +++ b/solution/0100-0199/0177.Nth Highest Salary/README_EN.md @@ -31,7 +31,7 @@ Each row of this table contains information about the salary of an employee.-
Write a solution to find the nth
highest salary from the Employee
table. If there is no nth
highest salary, return null
.
Write a solution to find the nth
highest distinct salary from the Employee
table. If there are less than n
distinct salaries, return null
.
The result format is in the following example.
diff --git a/solution/0100-0199/0184.Department Highest Salary/README.md b/solution/0100-0199/0184.Department Highest Salary/README.md index f22679744afbb..fe36aca302cbb 100644 --- a/solution/0100-0199/0184.Department Highest Salary/README.md +++ b/solution/0100-0199/0184.Department Highest Salary/README.md @@ -114,6 +114,31 @@ WHERE ); ``` +### Pandas + +```python +import pandas as pd + + +def department_highest_salary( + employee: pd.DataFrame, department: pd.DataFrame +) -> pd.DataFrame: + # Merge the two tables on departmentId and department id + merged = employee.merge(department, left_on='departmentId', right_on='id') + + # Find the maximum salary for each department + max_salaries = merged.groupby('departmentId')['salary'].transform('max') + + # Filter employees who have the highest salary in their department + top_earners = merged[merged['salary'] == max_salaries] + + # Select required columns and rename them + result = top_earners[['name_y', 'name_x', 'salary']].copy() + result.columns = ['Department', 'Employee', 'Salary'] + + return result +``` + diff --git a/solution/0100-0199/0184.Department Highest Salary/README_EN.md b/solution/0100-0199/0184.Department Highest Salary/README_EN.md index 68aad979846ff..48725a31b1208 100644 --- a/solution/0100-0199/0184.Department Highest Salary/README_EN.md +++ b/solution/0100-0199/0184.Department Highest Salary/README_EN.md @@ -116,6 +116,31 @@ WHERE ); ``` +### Pandas + +```python +import pandas as pd + + +def department_highest_salary( + employee: pd.DataFrame, department: pd.DataFrame +) -> pd.DataFrame: + # Merge the two tables on departmentId and department id + merged = employee.merge(department, left_on='departmentId', right_on='id') + + # Find the maximum salary for each department + max_salaries = merged.groupby('departmentId')['salary'].transform('max') + + # Filter employees who have the highest salary in their department + top_earners = merged[merged['salary'] == max_salaries] + + # Select required columns and rename them + result = top_earners[['name_y', 'name_x', 'salary']].copy() + result.columns = ['Department', 'Employee', 'Salary'] + + return result +``` + diff --git a/solution/0100-0199/0184.Department Highest Salary/Solution.py b/solution/0100-0199/0184.Department Highest Salary/Solution.py new file mode 100644 index 0000000000000..5b661d76ea904 --- /dev/null +++ b/solution/0100-0199/0184.Department Highest Salary/Solution.py @@ -0,0 +1,20 @@ +import pandas as pd + + +def department_highest_salary( + employee: pd.DataFrame, department: pd.DataFrame +) -> pd.DataFrame: + # Merge the two tables on departmentId and department id + merged = employee.merge(department, left_on='departmentId', right_on='id') + + # Find the maximum salary for each department + max_salaries = merged.groupby('departmentId')['salary'].transform('max') + + # Filter employees who have the highest salary in their department + top_earners = merged[merged['salary'] == max_salaries] + + # Select required columns and rename them + result = top_earners[['name_y', 'name_x', 'salary']].copy() + result.columns = ['Department', 'Employee', 'Salary'] + + return result diff --git a/solution/0100-0199/0190.Reverse Bits/README.md b/solution/0100-0199/0190.Reverse Bits/README.md index e151edf982a68..4538936385624 100644 --- a/solution/0100-0199/0190.Reverse Bits/README.md +++ b/solution/0100-0199/0190.Reverse Bits/README.md @@ -28,28 +28,67 @@ tags:-
示例 1:
- --输入:n = 00000010100101000001111010011100 -输出:964176192 (00111001011110000010100101000000) -解释:输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596, - 因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。- -
示例 2:
- --输入:n = 11111111111111111111111111111101 -输出:3221225471 (10111111111111111111111111111111) -解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293, - 因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。+
示例 1:
+ +输入:n = 43261596
+ +输出:964176192
+ +解释:
+ +整数 | +二进制 | +
---|---|
43261596 | +00000010100101000001111010011100 | +
964176192 | +00111001011110000010100101000000 | +
示例 2:
+ +输入:n = 2147483644
+ +输出:1073741822
+ +解释:
+ +整数 | +二进制 | +
---|---|
2147483644 | +01111111111111111111111111111100 | +
1073741822 | +00111111111111111111111111111110 | +
提示:
32
的二进制字符串0 <= n <= 231 - 2
n
为偶数diff --git a/solution/0100-0199/0190.Reverse Bits/README_EN.md b/solution/0100-0199/0190.Reverse Bits/README_EN.md index c9cb6f63778a4..3e84004956967 100644 --- a/solution/0100-0199/0190.Reverse Bits/README_EN.md +++ b/solution/0100-0199/0190.Reverse Bits/README_EN.md @@ -23,31 +23,70 @@ tags:
-3
and the output represents the signed integer -1073741825
.-3
and the output represents the signed integer -1073741825
.
Example 1:
--Input: n = 00000010100101000001111010011100 -Output: 964176192 (00111001011110000010100101000000) -Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. -+
Input: n = 43261596
+ +Output: 964176192
+ +Explanation:
+ +Integer | +Binary | +
---|---|
43261596 | +00000010100101000001111010011100 | +
964176192 | +00111001011110000010100101000000 | +
Example 2:
--Input: n = 11111111111111111111111111111101 -Output: 3221225471 (10111111111111111111111111111111) -Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111. -+
Input: n = 2147483644
+ +Output: 1073741822
+ +Explanation:
+ +Integer | +Binary | +
---|---|
2147483644 | +01111111111111111111111111111100 | +
1073741822 | +00111111111111111111111111111110 | +
Constraints:
32
0 <= n <= 231 - 2
n
is even.diff --git a/solution/0100-0199/0195.Tenth Line/README_EN.md b/solution/0100-0199/0195.Tenth Line/README_EN.md index 7ca9f7187d210..69bdfb2395242 100644 --- a/solution/0100-0199/0195.Tenth Line/README_EN.md +++ b/solution/0100-0199/0195.Tenth Line/README_EN.md @@ -23,26 +23,41 @@ tags:
Assume that file.txt
has the following content:
+ Line 1 + Line 2 + Line 3 + Line 4 + Line 5 + Line 6 + Line 7 + Line 8 + Line 9 + Line 10 +
Your script should output the tenth line, which is:
+ Line 10 +
给定一个 无重复元素 的 有序 整数数组 nums
。
返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说,nums
的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums
的数字 x
。
区间 [a,b]
是从 a
到 b
(包含)的所有整数的集合。
返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说,nums
的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个区间但不属于 nums
的数字 x
。
列表中的每个区间范围 [a,b]
应该按如下格式输出:
给定一个二叉树,统计该二叉树数值相同的子树个数。
+给定一个二叉树,统计该二叉树数值相同的 子树 个数。
同值子树是指该子树的所有节点都拥有相同的数值。
-示例:
++
示例 1:
+-输入: root = [5,1,5,5,5,null,5] +输入:root = [5,1,5,5,5,null,5] +输出:4 +- 5 - / \ - 1 5 - / \ \ - 5 5 5 +
示例 2:
-输出: 4 ++输入:root = [] +输出:0+
示例 3:
+ ++输入:root = [5,5,5,5,5,null,5] +输出:6 ++ +
+ +
提示:
+ +[0, 1000]
范围内-1000 <= Node.val <= 1000
-
表:Users
-
取消率 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数)。
编写解决方案找出 "2013-10-01"
至 "2013-10-03"
期间有 至少 一次行程的非禁止用户(乘客和司机都必须未被禁止)的 取消率。非禁止用户即 banned 为 No 的用户,禁止用户即 banned 为 Yes 的用户。其中取消率 Cancellation Rate
需要四舍五入保留 两位小数 。
+
Table: Users
+
The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.
@@ -59,7 +59,7 @@ banned is an ENUM (category) type of ('Yes', 'No').Return the result table in any order.
-The result format is in the following example.
+The result format is in the following example.
Example 1:
diff --git a/solution/0200-0299/0269.Alien Dictionary/README.md b/solution/0200-0299/0269.Alien Dictionary/README.md index b1185f65b06a0..308a96369b8e8 100644 --- a/solution/0200-0299/0269.Alien Dictionary/README.md +++ b/solution/0200-0299/0269.Alien Dictionary/README.md @@ -288,6 +288,87 @@ public: }; ``` +#### Go + +```go +func alienOrder(words []string) string { + g := [26][26]bool{} + s := [26]bool{} + cnt := 0 + n := len(words) + for i := 0; i < n-1; i++ { + for _, c := range words[i] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + m := len(words[i]) + for j := 0; j < m; j++ { + if j >= len(words[i+1]) { + return "" + } + c1, c2 := words[i][j]-'a', words[i+1][j]-'a' + if c1 == c2 { + continue + } + if g[c2][c1] { + return "" + } + g[c1][c2] = true + break + } + } + for _, c := range words[n-1] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + + inDegree := [26]int{} + for _, out := range g { + for i, v := range out { + if v { + inDegree[i]++ + } + } + } + q := []int{} + for i, in := range inDegree { + if in == 0 && s[i] { + q = append(q, i) + } + } + ans := "" + for len(q) > 0 { + t := q[0] + q = q[1:] + ans += string(t + 'a') + for i, v := range g[t] { + if v { + inDegree[i]-- + if inDegree[i] == 0 && s[i] { + q = append(q, i) + } + } + } + } + if len(ans) < cnt { + return "" + } + return ans +} +``` + diff --git a/solution/0200-0299/0269.Alien Dictionary/README_EN.md b/solution/0200-0299/0269.Alien Dictionary/README_EN.md index 9677cf9f30970..24d8925dfb9a6 100644 --- a/solution/0200-0299/0269.Alien Dictionary/README_EN.md +++ b/solution/0200-0299/0269.Alien Dictionary/README_EN.md @@ -269,6 +269,87 @@ public: }; ``` +#### Go + +```go +func alienOrder(words []string) string { + g := [26][26]bool{} + s := [26]bool{} + cnt := 0 + n := len(words) + for i := 0; i < n-1; i++ { + for _, c := range words[i] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + m := len(words[i]) + for j := 0; j < m; j++ { + if j >= len(words[i+1]) { + return "" + } + c1, c2 := words[i][j]-'a', words[i+1][j]-'a' + if c1 == c2 { + continue + } + if g[c2][c1] { + return "" + } + g[c1][c2] = true + break + } + } + for _, c := range words[n-1] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + + inDegree := [26]int{} + for _, out := range g { + for i, v := range out { + if v { + inDegree[i]++ + } + } + } + q := []int{} + for i, in := range inDegree { + if in == 0 && s[i] { + q = append(q, i) + } + } + ans := "" + for len(q) > 0 { + t := q[0] + q = q[1:] + ans += string(t + 'a') + for i, v := range g[t] { + if v { + inDegree[i]-- + if inDegree[i] == 0 && s[i] { + q = append(q, i) + } + } + } + } + if len(ans) < cnt { + return "" + } + return ans +} +``` + diff --git a/solution/0200-0299/0269.Alien Dictionary/Solution.go b/solution/0200-0299/0269.Alien Dictionary/Solution.go new file mode 100644 index 0000000000000..b49abee4bad20 --- /dev/null +++ b/solution/0200-0299/0269.Alien Dictionary/Solution.go @@ -0,0 +1,76 @@ +func alienOrder(words []string) string { + g := [26][26]bool{} + s := [26]bool{} + cnt := 0 + n := len(words) + for i := 0; i < n-1; i++ { + for _, c := range words[i] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + m := len(words[i]) + for j := 0; j < m; j++ { + if j >= len(words[i+1]) { + return "" + } + c1, c2 := words[i][j]-'a', words[i+1][j]-'a' + if c1 == c2 { + continue + } + if g[c2][c1] { + return "" + } + g[c1][c2] = true + break + } + } + for _, c := range words[n-1] { + if cnt == 26 { + break + } + c -= 'a' + if !s[c] { + cnt++ + s[c] = true + } + } + + inDegree := [26]int{} + for _, out := range g { + for i, v := range out { + if v { + inDegree[i]++ + } + } + } + q := []int{} + for i, in := range inDegree { + if in == 0 && s[i] { + q = append(q, i) + } + } + ans := "" + for len(q) > 0 { + t := q[0] + q = q[1:] + ans += string(t + 'a') + for i, v := range g[t] { + if v { + inDegree[i]-- + if inDegree[i] == 0 && s[i] { + q = append(q, i) + } + } + } + } + if len(ans) < cnt { + return "" + } + return ans +} diff --git a/solution/0200-0299/0275.H-Index II/README.md b/solution/0200-0299/0275.H-Index II/README.md index 546a3242358e5..47b3a5e04dfb9 100644 --- a/solution/0200-0299/0275.H-Index II/README.md +++ b/solution/0200-0299/0275.H-Index II/README.md @@ -17,7 +17,7 @@ tags: -给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数,citations
已经按照 升序排列 。计算并返回该研究者的 h 指数。
给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数,citations
已经按照 非降序排列 。计算并返回该研究者的 h 指数。
h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h
指数是指他(她)的 (n
篇论文中)至少 有 h
篇论文分别被引用了至少 h
次。
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper and citations
is sorted in ascending order, return the researcher's h-index.
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper and citations
is sorted in non-descending order, return the researcher's h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h
such that the given researcher has published at least h
papers that have each been cited at least h
times.
给定一个仅包含数字 0-9
的字符串 num
和一个目标值整数 target
,在 num
的数字之间添加 二元 运算符(不是一元)+
、-
或 *
,返回 所有 能够得到 target
的表达式。
给定一个仅包含数字 0-9
的字符串 num
和一个目标值整数 target
,在 num
的数字之间添加 二元 运算符(不是一元)+
、-
或 *
,返回 所有 能够得到 target
的表达式。
注意,返回表达式中的操作数 不应该 包含前导零。
+注意,一个数字可以包含多个数位。
+
示例 1:
diff --git a/solution/0200-0299/0282.Expression Add Operators/README_EN.md b/solution/0200-0299/0282.Expression Add Operators/README_EN.md index 083949924e34b..7b0d14c5eba93 100644 --- a/solution/0200-0299/0282.Expression Add Operators/README_EN.md +++ b/solution/0200-0299/0282.Expression Add Operators/README_EN.md @@ -22,6 +22,8 @@ tags:Note that operands in the returned expressions should not contain leading zeros.
+Note that a number can contain multiple digits.
+
Example 1:
diff --git a/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md b/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md index a41c44f4a91dc..b533ce8d0056f 100644 --- a/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md +++ b/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md @@ -32,8 +32,6 @@ tags:总旅行距离 是朋友们家到聚会地点的距离之和。
-使用 曼哈顿距离 计算距离,其中距离 (p1, p2) = |p2.x - p1.x | + | p2.y - p1.y |
。
示例 1:
diff --git a/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md b/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md index 816bbabef6c3d..edd540c52e03d 100644 --- a/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md +++ b/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md @@ -32,8 +32,6 @@ tags:The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
-The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.
Example 1:
给定单链表的头节点 head
,将所有索引为奇数的节点和索引为偶数的节点分别组合在一起,然后返回重新排序的列表。
给定单链表的头节点 head
,将所有索引为奇数的节点和索引为偶数的节点分别分组,保持它们原有的相对顺序,然后把偶数索引节点分组连接到奇数索引节点分组之后,返回重新排序的链表。
第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。
diff --git a/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md b/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md index c3bdea5faf274..a9b134fb52acd 100644 --- a/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md +++ b/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md @@ -20,7 +20,7 @@ tags: -请在 n × n 的棋盘上,实现一个判定井字棋(Tic-Tac-Toe)胜负的神器,判断每一次玩家落子后,是否有胜出的玩家。
+请在 n × n 的棋盘上,实现一个判定井字棋(Tic-Tac-Toe)胜负的神器,判断每一次玩家落子后,是否有胜出的玩家。
在这个井字棋游戏中,会有 2 名玩家,他们将轮流在棋盘上放置自己的棋子。
@@ -34,7 +34,8 @@ tags:示例:
-给定棋盘边长 n = 3, 玩家 1 的棋子符号是 "X",玩家 2 的棋子符号是 "O"。 ++给定棋盘边长 n = 3, 玩家 1 的棋子符号是 "X",玩家 2 的棋子符号是 "O"。 TicTacToe toe = new TicTacToe(3); @@ -76,7 +77,17 @@ toe.move(2, 1, 1); -> 函数返回 1 (此时,玩家 1 赢得了该场比赛-
进阶:
+提示:
+ +
2 <= n <= 100
1
或 2
。0 <= row, col < n
move
时 (row, col)
都是不同的。move
n2
次。进阶:
您有没有可能将每一步的 move()
操作优化到比 O(n2) 更快吗?
给你一个整数 n
,找出从 1
到 n
各个整数的 Fizz Buzz 表示,并用字符串数组 answer
(下标从 1 开始)返回结果,其中:
给你一个整数 n
,返回一个字符串数组 answer
(下标从 1 开始),其中:
answer[i] == "FizzBuzz"
如果 i
同时是 3
和 5
的倍数。示例 3:
-输入:sentence = ["I", "had", "apple", "pie"], rows = 4, cols = 5 +输入:sentence = ["i", "had", "apple", "pie"], rows = 4, cols = 5 输出:1 解释: -I-had +i-had apple -pie-I +pie-i had-- 字符 '-' 表示屏幕上的一个空白位置。diff --git a/solution/0400-0499/0437.Path Sum III/README.md b/solution/0400-0499/0437.Path Sum III/README.md index 193150e562e0f..bf2f873d8f8f2 100644 --- a/solution/0400-0499/0437.Path Sum III/README.md +++ b/solution/0400-0499/0437.Path Sum III/README.md @@ -59,18 +59,18 @@ tags: ### 方法一:哈希表 + 前缀和 + 递归 -我们可以运用前缀和的思想,对二叉树进行递归遍历,同时用哈希表 $cnt$ 统计从根节点到当前节点的路径上各个前缀和出现的次数。 +我们可以运用前缀和的思想,对二叉树进行递归遍历,同时用哈希表 $\textit{cnt}$ 统计从根节点到当前节点的路径上各个前缀和出现的次数。 -我们设计一个递归函数 $dfs(node, s)$,表示当前遍历到的节点为 $node$,从根节点到当前节点的路径上的前缀和为 $s$。函数的返回值是统计以 $node$ 节点及其子树节点作为路径终点且路径和为 $targetSum$ 的路径数目。那么答案就是 $dfs(root, 0)$。 +我们设计一个递归函数 $\textit{dfs(node, s)}$,表示当前遍历到的节点为 $\textit{node}$,从根节点到当前节点的路径上的前缀和为 $s$。函数的返回值是统计以 $\textit{node}$ 节点及其子树节点作为路径终点且路径和为 $\textit{targetSum}$ 的路径数目。那么答案就是 $\textit{dfs(root, 0)}$。 -函数 $dfs(node, s)$ 的递归过程如下: +函数 $\textit{dfs(node, s)}$ 的递归过程如下: -- 如果当前节点 $node$ 为空,则返回 $0$。 +- 如果当前节点 $\textit{node}$ 为空,则返回 $0$。 - 计算从根节点到当前节点的路径上的前缀和 $s$。 -- 用 $cnt[s - targetSum]$ 表示以当前节点为路径终点且路径和为 $targetSum$ 的路径数目,其中 $cnt[s - targetSum]$ 即为 $cnt$ 中前缀和为 $s - targetSum$ 的个数。 -- 将前缀和 $s$ 的计数值加 $1$,即 $cnt[s] = cnt[s] + 1$。 -- 递归地遍历当前节点的左右子节点,即调用函数 $dfs(node.left, s)$ 和 $dfs(node.right, s)$,并将它们的返回值相加。 -- 在返回值计算完成以后,需要将当前节点的前缀和 $s$ 的计数值减 $1$,即执行 $cnt[s] = cnt[s] - 1$。 +- 用 $\textit{cnt}[s - \textit{targetSum}]$ 表示以当前节点为路径终点且路径和为 $\textit{targetSum}$ 的路径数目,其中 $\textit{cnt}[s - \textit{targetSum}]$ 即为 $\textit{cnt}$ 中前缀和为 $s - \textit{targetSum}$ 的个数。 +- 将前缀和 $s$ 的计数值加 $1$,即 $\textit{cnt}[s] = \textit{cnt}[s] + 1$。 +- 递归地遍历当前节点的左右子节点,即调用函数 $\textit{dfs(node.left, s)}$ 和 $\textit{dfs(node.right, s)}$,并将它们的返回值相加。 +- 在返回值计算完成以后,需要将当前节点的前缀和 $s$ 的计数值减 $1$,即执行 $\textit{cnt}[s] = \textit{cnt}[s] - 1$。 - 最后返回答案。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 @@ -163,10 +163,12 @@ class Solution { class Solution { public: int pathSum(TreeNode* root, int targetSum) { - unordered_map
"USA"
。"leetcode"
。"Google"
。"leetcode"
。"Google"
。给你一个字符串 word
。如果大写用法正确,返回 true
;否则,返回 false
。
- -
编写解决方案,报告在首次登录的第二天再次登录的玩家的 比率,四舍五入到小数点后两位。换句话说,你需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。
+编写解决方案,报告在首次登录的第二天再次登录的玩家的 比率,四舍五入到小数点后两位。换句话说,你需要计算从首次登录后的第二天登录的玩家数量,并将其除以总玩家数。
结果格式如下所示:
diff --git a/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md b/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md index 75774152565b6..3612f647d84ed 100644 --- a/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md +++ b/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md @@ -32,11 +32,11 @@ This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. -+
-
Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
+Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to determine the number of players who logged in on the day immediately following their initial login, and divide it by the number of total players.
-The result format is in the following example.
+The result format is in the following example.
Example 1:
diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md index 6d3765e61f6cb..2cf6f98195019 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md @@ -173,32 +173,20 @@ function findUnsortedSubarray(nums: number[]): number { ```rust impl Solution { pub fn find_unsorted_subarray(nums: Vec找出那些 没有被 id = 2
的客户 推荐 的客户的姓名。
找出以下客户的姓名:
+ +id != 2
的用户推荐。以 任意顺序 返回结果表。
diff --git a/solution/0500-0599/0584.Find Customer Referee/README_EN.md b/solution/0500-0599/0584.Find Customer Referee/README_EN.md index d6810684bb34e..0bd8a5c948aff 100644 --- a/solution/0500-0599/0584.Find Customer Referee/README_EN.md +++ b/solution/0500-0599/0584.Find Customer Referee/README_EN.md @@ -32,7 +32,12 @@ Each row of this table indicates the id of a customer, their name, and the id of-
Find the names of the customer that are not referred by the customer with id = 2
.
Find the names of the customer that are either:
+ +id != 2
.Return the result table in any order.
diff --git a/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md b/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md index 06b75b6a92e88..faf66f120bb69 100644 --- a/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md +++ b/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md @@ -174,6 +174,28 @@ function findLHS(nums: number[]): number { } ``` +#### Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn find_lhs(nums: Vec假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。
+给定两个字符串数组 list1
和 list2
,找到 索引和最小的公共字符串。
你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设答案总是存在。
+公共字符串 是同时出现在 list1
和 list2
中的字符串。
具有 最小索引和的公共字符串 是指,如果它在 list1[i]
和 list2[j]
中出现,那么 i + j
应该是所有其他 公共字符串 中的最小值。
返回所有 具有最小索引和的公共字符串。以 任何顺序 返回答案。
@@ -29,7 +33,7 @@ tags:
输入: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] 输出: ["Shogun"] -解释: 他们唯一共同喜爱的餐厅是“Shogun”。 +解释: 唯一的公共字符串是 “Shogun”。
示例 2:
@@ -37,9 +41,20 @@ tags:输入:list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["KFC", "Shogun", "Burger King"] 输出: ["Shogun"] -解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。 +解释: 具有最小索引和的公共字符串是 “Shogun”,它有最小的索引和 = (0 + 1) = 1。+
示例 3:
+ ++输入:list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] +输出:["sad","happy"] +解释:有三个公共字符串: +"happy" 索引和 = (0 + 1) = 1. +"sad" 索引和 = (1 + 0) = 1. +"good" 索引和 = (2 + 2) = 4. +最小索引和的字符串是 "sad" 和 "happy"。+
提示:
diff --git a/solution/0600-0699/0604.Design Compressed String Iterator/README.md b/solution/0600-0699/0604.Design Compressed String Iterator/README.md index 9d8866ead6b51..49ed7490b6fa8 100644 --- a/solution/0600-0699/0604.Design Compressed String Iterator/README.md +++ b/solution/0600-0699/0604.Design Compressed String Iterator/README.md @@ -267,6 +267,53 @@ func (this *StringIterator) HasNext() bool { */ ``` +#### TypeScript + +```ts +class StringIterator { + private d: [string, number][] = []; + private p: number = 0; + + constructor(compressedString: string) { + const n = compressedString.length; + let i = 0; + while (i < n) { + const c = compressedString[i]; + let x = 0; + i++; + while (i < n && !isNaN(Number(compressedString[i]))) { + x = x * 10 + Number(compressedString[i]); + i++; + } + this.d.push([c, x]); + } + } + + next(): string { + if (!this.hasNext()) { + return ' '; + } + const ans = this.d[this.p][0]; + this.d[this.p][1]--; + if (this.d[this.p][1] === 0) { + this.p++; + } + return ans; + } + + hasNext(): boolean { + return this.p < this.d.length && this.d[this.p][1] > 0; + } +} + +/** + * Your StringIterator object will be instantiated and called as such: + * var obj = new StringIterator(compressedString) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + diff --git a/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md b/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md index cc5512a0be612..b5c23f018d70e 100644 --- a/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md +++ b/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md @@ -67,7 +67,13 @@ stringIterator.hasNext(); // return True -### Solution 1 +### Solution 1: Parsing and Storing + +Parse the `compressedString` into characters $c$ and their corresponding repetition counts $x$, and store them in an array or list $d$. Use $p$ to point to the current character. + +Then perform operations in `next` and `hasNext`. + +The initialization time complexity is $O(n)$, and the time complexity of the other operations is $O(1)$. Here, $n$ is the length of `compressedString`. @@ -260,6 +266,53 @@ func (this *StringIterator) HasNext() bool { */ ``` +#### TypeScript + +```ts +class StringIterator { + private d: [string, number][] = []; + private p: number = 0; + + constructor(compressedString: string) { + const n = compressedString.length; + let i = 0; + while (i < n) { + const c = compressedString[i]; + let x = 0; + i++; + while (i < n && !isNaN(Number(compressedString[i]))) { + x = x * 10 + Number(compressedString[i]); + i++; + } + this.d.push([c, x]); + } + } + + next(): string { + if (!this.hasNext()) { + return ' '; + } + const ans = this.d[this.p][0]; + this.d[this.p][1]--; + if (this.d[this.p][1] === 0) { + this.p++; + } + return ans; + } + + hasNext(): boolean { + return this.p < this.d.length && this.d[this.p][1] > 0; + } +} + +/** + * Your StringIterator object will be instantiated and called as such: + * var obj = new StringIterator(compressedString) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + diff --git a/solution/0600-0699/0604.Design Compressed String Iterator/Solution.ts b/solution/0600-0699/0604.Design Compressed String Iterator/Solution.ts new file mode 100644 index 0000000000000..6313052a68374 --- /dev/null +++ b/solution/0600-0699/0604.Design Compressed String Iterator/Solution.ts @@ -0,0 +1,42 @@ +class StringIterator { + private d: [string, number][] = []; + private p: number = 0; + + constructor(compressedString: string) { + const n = compressedString.length; + let i = 0; + while (i < n) { + const c = compressedString[i]; + let x = 0; + i++; + while (i < n && !isNaN(Number(compressedString[i]))) { + x = x * 10 + Number(compressedString[i]); + i++; + } + this.d.push([c, x]); + } + } + + next(): string { + if (!this.hasNext()) { + return ' '; + } + const ans = this.d[this.p][0]; + this.d[this.p][1]--; + if (this.d[this.p][1] === 0) { + this.p++; + } + return ans; + } + + hasNext(): boolean { + return this.p < this.d.length && this.d[this.p][1] > 0; + } +} + +/** + * Your StringIterator object will be instantiated and called as such: + * var obj = new StringIterator(compressedString) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ diff --git a/solution/0600-0699/0630.Course Schedule III/README.md b/solution/0600-0699/0630.Course Schedule III/README.md index 6375a17781381..0892c7c3ea024 100644 --- a/solution/0600-0699/0630.Course Schedule III/README.md +++ b/solution/0600-0699/0630.Course Schedule III/README.md @@ -179,13 +179,13 @@ func (h *hp) pop() int { return heap.Pop(h).(int) } ```ts function scheduleCourse(courses: number[][]): number { courses.sort((a, b) => a[1] - b[1]); - const pq = new MaxPriorityQueue(); + const pq = new MaxPriorityQueue1 <= n <= 100
1 <= logs.length <= 500
2 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
1 <= n <= 100
1 <= logs.length <= 500
2 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
树可以看成是一个连通且 无环 的 无向 图。
-给定往一棵 n
个节点 (节点值 1~n
) 的树中添加一条边后的图。添加的边的两个顶点包含在 1
到 n
中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n
的二维数组 edges
,edges[i] = [ai, bi]
表示图中在 ai
和 bi
之间存在一条边。
给定一个图,该图从一棵 n
个节点 (节点值 1~n
) 的树中添加一条边后获得。添加的边的两个不同顶点编号在 1
到 n
中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n
的二维数组 edges
,edges[i] = [ai, bi]
表示图中在 ai
和 bi
之间存在一条边。
请找出一条可以删去的边,删除后可使得剩余部分是一个有着 n
个节点的树。如果有多个答案,则返回数组 edges
中最后出现的那个。
示例 2:
diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md index 4f842e5001bae..3d1fb0e0c7da3 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md @@ -5,6 +5,8 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0600-0699/0689.Ma tags: - Array - Dynamic Programming + - Prefix Sum + - Sliding Window --- @@ -28,7 +30,7 @@ tags: Input: nums = [1,2,1,2,6,7,5,1], k = 2 Output: [0,3,5] Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. -We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically smaller. +We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.Example 2:
diff --git a/solution/0700-0799/0704.Binary Search/README.md b/solution/0700-0799/0704.Binary Search/README.md index 293c01438e03b..e58c3aed1d10e 100644 --- a/solution/0700-0799/0704.Binary Search/README.md +++ b/solution/0700-0799/0704.Binary Search/README.md @@ -17,19 +17,23 @@ tags: -给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果 target
存在返回下标,否则返回 -1
。
+
你必须编写一个具有 O(log n)
时间复杂度的算法。
示例 1:
输入:nums
= [-1,0,3,5,9,12],target
= 9 ++输入:nums
= [-1,0,3,5,9,12],target
= 9 输出: 4 解释: 9 出现在nums
中并且下标为 4示例 2:
-输入:-nums
= [-1,0,3,5,9,12],target
= 2 ++输入:diff --git a/solution/0700-0799/0720.Longest Word in Dictionary/README.md b/solution/0700-0799/0720.Longest Word in Dictionary/README.md index bf15fcb915ab3..3a80e81888f9e 100644 --- a/solution/0700-0799/0720.Longest Word in Dictionary/README.md +++ b/solution/0700-0799/0720.Longest Word in Dictionary/README.md @@ -20,7 +20,7 @@ tags: -nums
= [-1,0,3,5,9,12],target
= 2 输出: -1 解释: 2 不存在nums
中因此返回 -1给出一个字符串数组
+words
组成的一本英语词典。返回words
中最长的一个单词,该单词是由words
词典中其他单词逐步添加一个字母组成。给出一个字符串数组
words
组成的一本英语词典。返回能够通过words
中其它单词逐步添加一个字母来构造得到的words
中最长的单词。若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
diff --git a/solution/0700-0799/0752.Open the Lock/Solution.py b/solution/0700-0799/0752.Open the Lock/Solution.py index 650d7757d7db7..76e24b06bb1ce 100644 --- a/solution/0700-0799/0752.Open the Lock/Solution.py +++ b/solution/0700-0799/0752.Open the Lock/Solution.py @@ -17,7 +17,7 @@ def next(s): s = set(deadends) if '0000' in s: return -1 - q = deque([('0000')]) + q = deque(['0000']) s.add('0000') ans = 0 while q: diff --git a/solution/0700-0799/0752.Open the Lock/Solution2.py b/solution/0700-0799/0752.Open the Lock/Solution2.py index 6a623bcf80b3b..87d7e03b99365 100644 --- a/solution/0700-0799/0752.Open the Lock/Solution2.py +++ b/solution/0700-0799/0752.Open the Lock/Solution2.py @@ -27,7 +27,7 @@ def extend(m1, m2, q): def bfs(): m1, m2 = {"0000": 0}, {target: 0} - q1, q2 = deque([('0000')]), deque([(target)]) + q1, q2 = deque(['0000']), deque([target]) while q1 and q2: t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) if t != -1: diff --git a/solution/0700-0799/0759.Employee Free Time/README.md b/solution/0700-0799/0759.Employee Free Time/README.md index cf8212b6bb7f5..e422bbd125252 100644 --- a/solution/0700-0799/0759.Employee Free Time/README.md +++ b/solution/0700-0799/0759.Employee Free Time/README.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0700-0799/0759.Em tags: - 数组 - 排序 + - 扫描线 - 堆(优先队列) --- diff --git a/solution/0700-0799/0759.Employee Free Time/README_EN.md b/solution/0700-0799/0759.Employee Free Time/README_EN.md index 9543d4e2e9379..7c0a64ed0b949 100644 --- a/solution/0700-0799/0759.Employee Free Time/README_EN.md +++ b/solution/0700-0799/0759.Employee Free Time/README_EN.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0700-0799/0759.Em tags: - Array - Sorting + - Line Sweep - Heap (Priority Queue) --- diff --git a/solution/0700-0799/0773.Sliding Puzzle/Solution.py b/solution/0700-0799/0773.Sliding Puzzle/Solution.py index 897f9d185a622..9fe4e105727a7 100644 --- a/solution/0700-0799/0773.Sliding Puzzle/Solution.py +++ b/solution/0700-0799/0773.Sliding Puzzle/Solution.py @@ -29,7 +29,7 @@ def f(): if start == end: return 0 vis = {start} - q = deque([(start)]) + q = deque([start]) ans = 0 while q: ans += 1 diff --git a/solution/0700-0799/0778.Swim in Rising Water/README_EN.md b/solution/0700-0799/0778.Swim in Rising Water/README_EN.md index 8212558afeb12..6f71d19110991 100644 --- a/solution/0700-0799/0778.Swim in Rising Water/README_EN.md +++ b/solution/0700-0799/0778.Swim in Rising Water/README_EN.md @@ -24,9 +24,11 @@ tags:You are given an
-n x n
integer matrixgrid
where each valuegrid[i][j]
represents the elevation at that point(i, j)
.The rain starts to fall. At time
+t
, the depth of the water everywhere ist
. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at mostt
. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.It starts raining, and water gradually rises over time. At time
-t
, the water level ist
, meaning any cell with elevation less than equal tot
is submerged or reachable.Return the least time until you can reach the bottom right square
+(n - 1, n - 1)
if you start at the top left square(0, 0)
.You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most
+ +t
. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.Return the minimum time until you can reach the bottom right square
(n - 1, n - 1)
if you start at the top left square(0, 0)
.
Example 1:
diff --git a/solution/0700-0799/0781.Rabbits in Forest/README.md b/solution/0700-0799/0781.Rabbits in Forest/README.md index a3cdab7dc9fe3..e0deffabd8ff3 100644 --- a/solution/0700-0799/0781.Rabbits in Forest/README.md +++ b/solution/0700-0799/0781.Rabbits in Forest/README.md @@ -159,4 +159,52 @@ function numRabbits(answers: number[]): number { +### Solution 2: Greedy + Hash Map + + + +#### TypeScript + +```ts +function numRabbits(answers: number[]): number { + const cnt: Record= {}; + let ans = 0; + + for (const x of answers) { + if (cnt[x]) { + cnt[x]--; + } else { + cnt[x] = x; + ans += x + 1; + } + } + + return ans; +} +``` + +#### JavaScript + +```js +function numRabbits(answers) { + const cnt = {}; + let ans = 0; + + for (const x of answers) { + if (cnt[x]) { + cnt[x]--; + } else { + cnt[x] = x; + ans += x + 1; + } + } + + return ans; +} +``` + + + + + diff --git a/solution/0700-0799/0781.Rabbits in Forest/README_EN.md b/solution/0700-0799/0781.Rabbits in Forest/README_EN.md index 64c4163676514..b59b36d70b1a3 100644 --- a/solution/0700-0799/0781.Rabbits in Forest/README_EN.md +++ b/solution/0700-0799/0781.Rabbits in Forest/README_EN.md @@ -157,4 +157,54 @@ function numRabbits(answers: number[]): number { + + +### Solution 2: Greedy + Hash Map + + + +#### TypeScript + +```ts +function numRabbits(answers: number[]): number { + const cnt: Record = {}; + let ans = 0; + + for (const x of answers) { + if (cnt[x]) { + cnt[x]--; + } else { + cnt[x] = x; + ans += x + 1; + } + } + + return ans; +} +``` + +#### JavaScript + +```js +function numRabbits(answers) { + const cnt = {}; + let ans = 0; + + for (const x of answers) { + if (cnt[x]) { + cnt[x]--; + } else { + cnt[x] = x; + ans += x + 1; + } + } + + return ans; +} +``` + + + + + diff --git a/solution/0700-0799/0781.Rabbits in Forest/Solution2.js b/solution/0700-0799/0781.Rabbits in Forest/Solution2.js new file mode 100644 index 0000000000000..24214b0b9c71a --- /dev/null +++ b/solution/0700-0799/0781.Rabbits in Forest/Solution2.js @@ -0,0 +1,15 @@ +function numRabbits(answers) { + const cnt = {}; + let ans = 0; + + for (const x of answers) { + if (cnt[x]) { + cnt[x]--; + } else { + cnt[x] = x; + ans += x + 1; + } + } + + return ans; +} diff --git a/solution/0700-0799/0781.Rabbits in Forest/Solution2.ts b/solution/0700-0799/0781.Rabbits in Forest/Solution2.ts new file mode 100644 index 0000000000000..a87ad1d96eecd --- /dev/null +++ b/solution/0700-0799/0781.Rabbits in Forest/Solution2.ts @@ -0,0 +1,15 @@ +function numRabbits(answers: number[]): number { + const cnt: Record = {}; + let ans = 0; + + for (const x of answers) { + if (cnt[x]) { + cnt[x]--; + } else { + cnt[x] = x; + ans += x + 1; + } + } + + return ans; +} diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/README.md b/solution/0700-0799/0790.Domino and Tromino Tiling/README.md index da30ee9b60a10..9311772e724de 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/README.md +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/README.md @@ -86,7 +86,7 @@ tags: 注意,过程中的状态数值可能会很大,因此需要对 $10^9+7$ 取模。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为面板的列数。 +时间复杂度 $O(n)$,其中 $n$ 为面板的列数。空间复杂度 $O(1)$。 @@ -132,12 +132,11 @@ class Solution { ```cpp class Solution { public: - const int mod = 1e9 + 7; - int numTilings(int n) { - long f[4] = {1, 0, 0, 0}; + const int mod = 1e9 + 7; + long long f[4] = {1, 0, 0, 0}; for (int i = 1; i <= n; ++i) { - long g[4] = {0, 0, 0, 0}; + long long g[4]; g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; g[1] = (f[2] + f[3]) % mod; g[2] = (f[1] + f[3]) % mod; @@ -168,6 +167,46 @@ func numTilings(n int) int { } ``` +#### TypeScript + +```ts +function numTilings(n: number): number { + const mod = 1_000_000_007; + let f: number[] = [1, 0, 0, 0]; + + for (let i = 1; i <= n; ++i) { + const g: number[] = Array(4); + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; + g[1] = (f[2] + f[3]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[0] % mod; + f = g; + } + + return f[0]; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_tilings(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut f: [i64; 4] = [1, 0, 0, 0]; + for _ in 1..=n { + let mut g = [0i64; 4]; + g[0] = (f[0] + f[1] + f[2] + f[3]) % MOD; + g[1] = (f[2] + f[3]) % MOD; + g[2] = (f[1] + f[3]) % MOD; + g[3] = f[0] % MOD; + f = g; + } + f[0] as i32 + } +} +``` + diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md b/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md index 04f89b3e86cd6..9d5dc63b7ff65 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md @@ -28,7 +28,7 @@ tags: Input: n = 3 Output: 5 -Explanation: The five different ways are show above. +Explanation: The five different ways are shown above.Example 2:
@@ -126,12 +126,11 @@ class Solution { ```cpp class Solution { public: - const int mod = 1e9 + 7; - int numTilings(int n) { - long f[4] = {1, 0, 0, 0}; + const int mod = 1e9 + 7; + long long f[4] = {1, 0, 0, 0}; for (int i = 1; i <= n; ++i) { - long g[4] = {0, 0, 0, 0}; + long long g[4]; g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; g[1] = (f[2] + f[3]) % mod; g[2] = (f[1] + f[3]) % mod; @@ -162,6 +161,46 @@ func numTilings(n int) int { } ``` +#### TypeScript + +```ts +function numTilings(n: number): number { + const mod = 1_000_000_007; + let f: number[] = [1, 0, 0, 0]; + + for (let i = 1; i <= n; ++i) { + const g: number[] = Array(4); + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; + g[1] = (f[2] + f[3]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[0] % mod; + f = g; + } + + return f[0]; +} +``` + +#### Rust + +```rust +impl Solution { + pub fn num_tilings(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut f: [i64; 4] = [1, 0, 0, 0]; + for _ in 1..=n { + let mut g = [0i64; 4]; + g[0] = (f[0] + f[1] + f[2] + f[3]) % MOD; + g[1] = (f[2] + f[3]) % MOD; + g[2] = (f[1] + f[3]) % MOD; + g[3] = f[0] % MOD; + f = g; + } + f[0] as i32 + } +} +``` + diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp index 7dee343d57916..835d82ee5f184 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.cpp @@ -1,11 +1,10 @@ class Solution { public: - const int mod = 1e9 + 7; - int numTilings(int n) { - long f[4] = {1, 0, 0, 0}; + const int mod = 1e9 + 7; + long long f[4] = {1, 0, 0, 0}; for (int i = 1; i <= n; ++i) { - long g[4] = {0, 0, 0, 0}; + long long g[4]; g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; g[1] = (f[2] + f[3]) % mod; g[2] = (f[1] + f[3]) % mod; diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.rs b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.rs new file mode 100644 index 0000000000000..fa193c65eb056 --- /dev/null +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn num_tilings(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut f: [i64; 4] = [1, 0, 0, 0]; + for _ in 1..=n { + let mut g = [0i64; 4]; + g[0] = (f[0] + f[1] + f[2] + f[3]) % MOD; + g[1] = (f[2] + f[3]) % MOD; + g[2] = (f[1] + f[3]) % MOD; + g[3] = f[0] % MOD; + f = g; + } + f[0] as i32 + } +} diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.ts b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.ts new file mode 100644 index 0000000000000..1550567f5375c --- /dev/null +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/Solution.ts @@ -0,0 +1,15 @@ +function numTilings(n: number): number { + const mod = 1_000_000_007; + let f: number[] = [1, 0, 0, 0]; + + for (let i = 1; i <= n; ++i) { + const g: number[] = Array(4); + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod; + g[1] = (f[2] + f[3]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[0] % mod; + f = g; + } + + return f[0]; +} diff --git a/solution/0700-0799/0797.All Paths From Source to Target/README.md b/solution/0700-0799/0797.All Paths From Source to Target/README.md index 4deb1aa603807..1d36139c345de 100644 --- a/solution/0700-0799/0797.All Paths From Source to Target/README.md +++ b/solution/0700-0799/0797.All Paths From Source to Target/README.md @@ -19,7 +19,7 @@ tags: -给你一个有
+n
个节点的 有向无环图(DAG),请你找出所有从节点0
到节点n-1
的路径并输出(不要求按特定顺序)给你一个有
n
个节点的 有向无环图(DAG),请你找出从节点0
到节点n-1
的所有路径并输出(不要求按特定顺序)diff --git a/solution/0700-0799/0799.Champagne Tower/README_EN.md b/solution/0700-0799/0799.Champagne Tower/README_EN.md index 7c1df1e554754..c04fa21334900 100644 --- a/solution/0700-0799/0799.Champagne Tower/README_EN.md +++ b/solution/0700-0799/0799.Champagne Tower/README_EN.md @@ -27,35 +27,51 @@ tags:
graph[i]
是一个从节点i
可以访问的所有节点的列表(即从节点i
到节点graph[i][j]
存在一条有向边)。Now after pouring some non-negative integer cups of champagne, return how full the
jth
glass in theith
row is (bothi
andj
are 0-indexed.)+
Example 1:
+ Input: poured = 1, query_row = 1, query_glass = 1 + Output: 0.00000 + Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. +Example 2:
+ Input: poured = 2, query_row = 1, query_glass = 1 + Output: 0.50000 + Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. +Example 3:
+ Input: poured = 100000009, query_row = 33, query_glass = 17 + Output: 1.00000 ++
Constraints:
-
diff --git a/solution/0800-0899/0802.Find Eventual Safe States/README.md b/solution/0800-0899/0802.Find Eventual Safe States/README.md index efac1c82f3f3f..fe644d4423d8d 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/README.md +++ b/solution/0800-0899/0802.Find Eventual Safe States/README.md @@ -21,7 +21,7 @@ tags:- -
0 <= poured <= 109
- + +
0 <= query_glass <= query_row < 100
- + +
0 <= poured <= 109
- +
0 <= query_glass <= query_row < 100
有一个有
-n
个节点的有向图,节点按0
到n - 1
编号。图由一个 索引从 0 开始 的 2D 整数数组graph
表示,graph[i]
是与节点i
相邻的节点的整数数组,这意味着从节点i
到graph[i]
中的每个节点都有一条边。如果一个节点没有连出的有向边,则该节点是 终端节点 。如果从该节点开始的所有可能路径都通向 终端节点 ,则该节点为 安全节点 。
+如果一个节点没有连出的有向边,则该节点是 终端节点 。如果从该节点开始的所有可能路径都通向 终端节点(或另一个安全节点),则该节点为 安全节点。
返回一个由图中所有 安全节点 组成的数组作为答案。答案数组中的元素应当按 升序 排列。
diff --git a/solution/0800-0899/0819.Most Common Word/README.md b/solution/0800-0899/0819.Most Common Word/README.md index f3adddcb4620e..20a453ae26ab5 100644 --- a/solution/0800-0899/0819.Most Common Word/README.md +++ b/solution/0800-0899/0819.Most Common Word/README.md @@ -23,6 +23,8 @@ tags:+
paragraph
中的单词 不区分大小写 ,答案应以 小写 形式返回。注意 单词不包含标点符号。
+
示例 1:
diff --git a/solution/0800-0899/0819.Most Common Word/README_EN.md b/solution/0800-0899/0819.Most Common Word/README_EN.md index ebcacda3c5c8e..2aae27ab03f78 100644 --- a/solution/0800-0899/0819.Most Common Word/README_EN.md +++ b/solution/0800-0899/0819.Most Common Word/README_EN.md @@ -23,6 +23,8 @@ tags:The words in
+paragraph
are case-insensitive and the answer should be returned in lowercase.Note that words can not contain punctuation symbols.
+
Example 1:
diff --git a/solution/0800-0899/0838.Push Dominoes/README.md b/solution/0800-0899/0838.Push Dominoes/README.md index e6f79c7abba0b..d37d4feea673e 100644 --- a/solution/0800-0899/0838.Push Dominoes/README.md +++ b/solution/0800-0899/0838.Push Dominoes/README.md @@ -68,7 +68,30 @@ tags: -### 方法一 +### 方法一:多源 BFS + +把所有初始受到推力的骨牌(`L` 或 `R`)视作 **源点**,它们会同时向外扩散各自的力。用队列按时间层级(0, 1, 2 …)进行 BFS: + +我们定义 $\text{time[i]}$ 记录第 *i* 张骨牌第一次受力的时刻,`-1` 表示尚未受力,定义 $\text{force[i]}$ 是一个长度可变的列表,存放该骨牌在同一时刻收到的方向(`'L'`、`'R'`)。初始时把所有 `L/R` 的下标压入队列,并将它们的时间置 0。 + +当弹出下标 *i* 时,若 $\text{force[i]}$ 只有一个方向,骨牌就会倒向该方向 $f$。设下一张骨牌下标为 + +$$ +j = +\begin{cases} +i - 1, & f = L,\\ +i + 1, & f = R. +\end{cases} +$$ + +若 $0 \leq j < n$: + +- 若 $\text{time[j]}=-1$,说明 *j* 从未受力,记录 $\text{time[j]}=\text{time[i]}+1$ 并入队,同时把 $f$ 写入 $\text{force[j]}$。 +- 若 $\text{time[j]}=\text{time[i]}+1$,说明它在同一“下一刻”已受过另一股力,此时只把 $f$ 追加到 $\text{force[j]}$,形成对冲;后续因 `len(force[j])==2`,它将保持竖直。 + +队列清空后,所有 $\text{force[i]}$ 长度为 1 的位置倒向对应方向;长度为 2 的位置保持 `.`。最终将字符数组拼接为答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是骨牌的数量。 @@ -242,44 +265,40 @@ func pushDominoes(dominoes string) string { ```ts function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } ``` diff --git a/solution/0800-0899/0838.Push Dominoes/README_EN.md b/solution/0800-0899/0838.Push Dominoes/README_EN.md index ce232677d18a7..ec5ef4c80d36c 100644 --- a/solution/0800-0899/0838.Push Dominoes/README_EN.md +++ b/solution/0800-0899/0838.Push Dominoes/README_EN.md @@ -67,7 +67,30 @@ tags: -### Solution 1 +### Solution 1: Multi-Source BFS + +Treat all initially pushed dominoes (`L` or `R`) as **sources**, which simultaneously propagate their forces outward. Use a queue to perform BFS layer by layer (0, 1, 2, ...): + +We define $\text{time[i]}$ to record the first moment when the _i_-th domino is affected by a force, with `-1` indicating it has not been affected yet. We also define $\text{force[i]}$ as a variable-length list that stores the directions (`'L'`, `'R'`) of forces acting on the domino at the same moment. Initially, push all indices of `L/R` dominoes into the queue and set their `time` to 0. + +When dequeuing index _i_, if $\text{force[i]}$ contains only one direction, the domino will fall in that direction $f$. Let the index of the next domino be: + +$$ +j = +\begin{cases} +i - 1, & f = L,\\ +i + 1, & f = R. +\end{cases} +$$ + +If $0 \leq j < n$: + +- If $\text{time[j]} = -1$, it means _j_ has not been affected yet. Record $\text{time[j]} = \text{time[i]} + 1$, enqueue it, and append $f$ to $\text{force[j]}$. +- If $\text{time[j]} = \text{time[i]} + 1$, it means _j_ has already been affected by another force at the same "next moment." In this case, append $f$ to $\text{force[j]}$, causing a standoff. Subsequently, since $\text{len(force[j])} = 2$, it will remain upright. + +After the queue is emptied, all positions where $\text{force[i]}$ has a length of 1 will fall in the corresponding direction, while positions with a length of 2 will remain as `.`. Finally, concatenate the character array to form the answer. + +The complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of dominoes. @@ -241,44 +264,40 @@ func pushDominoes(dominoes string) string { ```ts function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } ``` diff --git a/solution/0800-0899/0838.Push Dominoes/Solution.ts b/solution/0800-0899/0838.Push Dominoes/Solution.ts index d9e8412c5d062..0b912d31ca203 100644 --- a/solution/0800-0899/0838.Push Dominoes/Solution.ts +++ b/solution/0800-0899/0838.Push Dominoes/Solution.ts @@ -1,41 +1,37 @@ function pushDominoes(dominoes: string): string { const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; + const q: number[] = []; + const time: number[] = Array(n).fill(-1); + const force: string[][] = Array.from({ length: n }, () => []); + for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; + const f = dominoes[i]; + if (f !== '.') { + q.push(i); + time[i] = 0; + force[i].push(f); } } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); + + const ans: string[] = Array(n).fill('.'); + let head = 0; + while (head < q.length) { + const i = q[head++]; + if (force[i].length === 1) { + const f = force[i][0]; + ans[i] = f; + const j = f === 'L' ? i - 1 : i + 1; + if (j >= 0 && j < n) { + const t = time[i]; + if (time[j] === -1) { + q.push(j); + time[j] = t + 1; + force[j].push(f); + } else if (time[j] === t + 1) { + force[j].push(f); + } } } - queue = nextLevel; } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); + return ans.join(''); } diff --git a/solution/0800-0899/0853.Car Fleet/README.md b/solution/0800-0899/0853.Car Fleet/README.md index fadb1d60e4f77..c8bb9502b2c1e 100644 --- a/solution/0800-0899/0853.Car Fleet/README.md +++ b/solution/0800-0899/0853.Car Fleet/README.md @@ -125,9 +125,7 @@ class Solution { public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> position[j] - position[i]); int ans = 0; double pre = 0; diff --git a/solution/0800-0899/0853.Car Fleet/README_EN.md b/solution/0800-0899/0853.Car Fleet/README_EN.md index baba8b025d9bf..29c9d8eef5cd8 100644 --- a/solution/0800-0899/0853.Car Fleet/README_EN.md +++ b/solution/0800-0899/0853.Car Fleet/README_EN.md @@ -117,9 +117,7 @@ class Solution { public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> position[j] - position[i]); int ans = 0; double pre = 0; diff --git a/solution/0800-0899/0853.Car Fleet/Solution.java b/solution/0800-0899/0853.Car Fleet/Solution.java index c346687da335c..593a14db56bc7 100644 --- a/solution/0800-0899/0853.Car Fleet/Solution.java +++ b/solution/0800-0899/0853.Car Fleet/Solution.java @@ -2,9 +2,7 @@ class Solution { public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } + Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> position[j] - position[i]); int ans = 0; double pre = 0; diff --git a/solution/0800-0899/0854.K-Similar Strings/README.md b/solution/0800-0899/0854.K-Similar Strings/README.md index 901f3eddf2b6e..8c3b0849eb9e6 100644 --- a/solution/0800-0899/0854.K-Similar Strings/README.md +++ b/solution/0800-0899/0854.K-Similar Strings/README.md @@ -4,6 +4,7 @@ difficulty: 困难 edit_url: https://github.com/doocs/leetcode/edit/main/solution/0800-0899/0854.K-Similar%20Strings/README.md tags: - 广度优先搜索 + - 哈希表 - 字符串 --- diff --git a/solution/0800-0899/0854.K-Similar Strings/README_EN.md b/solution/0800-0899/0854.K-Similar Strings/README_EN.md index 793ae5c5199ba..e900f8a5eccd5 100644 --- a/solution/0800-0899/0854.K-Similar Strings/README_EN.md +++ b/solution/0800-0899/0854.K-Similar Strings/README_EN.md @@ -4,6 +4,7 @@ difficulty: Hard edit_url: https://github.com/doocs/leetcode/edit/main/solution/0800-0899/0854.K-Similar%20Strings/README_EN.md tags: - Breadth-First Search + - Hash Table - String --- diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md index 26653f615fa58..aaa16bb1bda2f 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md @@ -106,35 +106,25 @@ class Solution: class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int k) { int n = quality.length; - Pair[] t = new Pair[n]; + Pair[] t = new Pair[n]; for (int i = 0; i < n; ++i) { - t[i] = new Pair(quality[i], wage[i]); + t[i] = new Pair<>((double) wage[i] / quality[i], quality[i]); } - Arrays.sort(t, (a, b) -> Double.compare(a.x, b.x)); + Arrays.sort(t, (a, b) -> Double.compare(a.getKey(), b.getKey())); PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - double ans = 1e9; + double ans = 1e18; int tot = 0; for (var e : t) { - tot += e.q; - pq.offer(e.q); + tot += e.getValue(); + pq.offer(e.getValue()); if (pq.size() == k) { - ans = Math.min(ans, tot * e.x); + ans = Math.min(ans, tot * e.getKey()); tot -= pq.poll(); } } return ans; } } - -class Pair { - double x; - int q; - - Pair(int q, int w) { - this.q = q; - this.x = (double) w / q; - } -} ``` #### C++ @@ -150,7 +140,7 @@ public: } sort(t.begin(), t.end()); priority_queue pq; - double ans = 1e9; + double ans = 1e18; int tot = 0; for (auto& [x, q] : t) { tot += q; @@ -176,7 +166,7 @@ func mincostToHireWorkers(quality []int, wage []int, k int) float64 { } sort.Slice(t, func(i, j int) bool { return t[i].x < t[j].x }) tot := 0 - var ans float64 = 1e9 + var ans float64 = 1e18 pq := hp{} for _, e := range t { tot += e.q diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md index a1218f717f1e0..306df16aee8cc 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md @@ -91,35 +91,25 @@ class Solution: class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int k) { int n = quality.length; - Pair[] t = new Pair[n]; + Pair [] t = new Pair[n]; for (int i = 0; i < n; ++i) { - t[i] = new Pair(quality[i], wage[i]); + t[i] = new Pair<>((double) wage[i] / quality[i], quality[i]); } - Arrays.sort(t, (a, b) -> Double.compare(a.x, b.x)); + Arrays.sort(t, (a, b) -> Double.compare(a.getKey(), b.getKey())); PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - double ans = 1e9; + double ans = 1e18; int tot = 0; for (var e : t) { - tot += e.q; - pq.offer(e.q); + tot += e.getValue(); + pq.offer(e.getValue()); if (pq.size() == k) { - ans = Math.min(ans, tot * e.x); + ans = Math.min(ans, tot * e.getKey()); tot -= pq.poll(); } } return ans; } } - -class Pair { - double x; - int q; - - Pair(int q, int w) { - this.q = q; - this.x = (double) w / q; - } -} ``` #### C++ @@ -135,7 +125,7 @@ public: } sort(t.begin(), t.end()); priority_queue pq; - double ans = 1e9; + double ans = 1e18; int tot = 0; for (auto& [x, q] : t) { tot += q; @@ -161,7 +151,7 @@ func mincostToHireWorkers(quality []int, wage []int, k int) float64 { } sort.Slice(t, func(i, j int) bool { return t[i].x < t[j].x }) tot := 0 - var ans float64 = 1e9 + var ans float64 = 1e18 pq := hp{} for _, e := range t { tot += e.q diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.cpp b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.cpp index e0cd02c4e27b5..940263977b9be 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.cpp +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.cpp @@ -8,7 +8,7 @@ class Solution { } sort(t.begin(), t.end()); priority_queue pq; - double ans = 1e9; + double ans = 1e18; int tot = 0; for (auto& [x, q] : t) { tot += q; diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.go b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.go index cd286f89e00ca..912341e4e9f7c 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.go +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.go @@ -5,7 +5,7 @@ func mincostToHireWorkers(quality []int, wage []int, k int) float64 { } sort.Slice(t, func(i, j int) bool { return t[i].x < t[j].x }) tot := 0 - var ans float64 = 1e9 + var ans float64 = 1e18 pq := hp{} for _, e := range t { tot += e.q diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.java b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.java index 2090d170f8829..84f779425be1e 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.java +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/Solution.java @@ -1,32 +1,22 @@ class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int k) { int n = quality.length; - Pair[] t = new Pair[n]; + Pair [] t = new Pair[n]; for (int i = 0; i < n; ++i) { - t[i] = new Pair(quality[i], wage[i]); + t[i] = new Pair<>((double) wage[i] / quality[i], quality[i]); } - Arrays.sort(t, (a, b) -> Double.compare(a.x, b.x)); + Arrays.sort(t, (a, b) -> Double.compare(a.getKey(), b.getKey())); PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - double ans = 1e9; + double ans = 1e18; int tot = 0; for (var e : t) { - tot += e.q; - pq.offer(e.q); + tot += e.getValue(); + pq.offer(e.getValue()); if (pq.size() == k) { - ans = Math.min(ans, tot * e.x); + ans = Math.min(ans, tot * e.getKey()); tot -= pq.poll(); } } return ans; } } - -class Pair { - double x; - int q; - - Pair(int q, int w) { - this.q = q; - this.x = (double) w / q; - } -} \ No newline at end of file diff --git a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md index 43c01e207b7c6..e1e44eb2e0170 100644 --- a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md +++ b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md @@ -206,14 +206,14 @@ func (h *hp) Pop() any { ```ts function minRefuelStops(target: number, startFuel: number, stations: number[][]): number { - const pq = new MaxPriorityQueue(); + const pq = new MaxPriorityQueue (); let [ans, pre] = [0, 0]; stations.push([target, 0]); for (const [pos, fuel] of stations) { const dist = pos - pre; startFuel -= dist; while (startFuel < 0 && !pq.isEmpty()) { - startFuel += pq.dequeue().element; + startFuel += pq.dequeue(); ans++; } if (startFuel < 0) { diff --git a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md index 630e93b48caff..178656648518c 100644 --- a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md +++ b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md @@ -203,14 +203,14 @@ func (h *hp) Pop() any { ```ts function minRefuelStops(target: number, startFuel: number, stations: number[][]): number { - const pq = new MaxPriorityQueue(); + const pq = new MaxPriorityQueue (); let [ans, pre] = [0, 0]; stations.push([target, 0]); for (const [pos, fuel] of stations) { const dist = pos - pre; startFuel -= dist; while (startFuel < 0 && !pq.isEmpty()) { - startFuel += pq.dequeue().element; + startFuel += pq.dequeue(); ans++; } if (startFuel < 0) { diff --git a/solution/0800-0899/0871.Minimum Number of Refueling Stops/Solution.ts b/solution/0800-0899/0871.Minimum Number of Refueling Stops/Solution.ts index e4a782ed55c25..0ecdf32837785 100644 --- a/solution/0800-0899/0871.Minimum Number of Refueling Stops/Solution.ts +++ b/solution/0800-0899/0871.Minimum Number of Refueling Stops/Solution.ts @@ -1,12 +1,12 @@ function minRefuelStops(target: number, startFuel: number, stations: number[][]): number { - const pq = new MaxPriorityQueue(); + const pq = new MaxPriorityQueue (); let [ans, pre] = [0, 0]; stations.push([target, 0]); for (const [pos, fuel] of stations) { const dist = pos - pre; startFuel -= dist; while (startFuel < 0 && !pq.isEmpty()) { - startFuel += pq.dequeue().element; + startFuel += pq.dequeue(); ans++; } if (startFuel < 0) { diff --git a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md index ed6e907943729..4a4ddd95f3f1f 100644 --- a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md +++ b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md @@ -18,18 +18,18 @@ tags: - 如果序列
+X_1, X_2, ..., X_n
满足下列条件,就说它是 斐波那契式 的:如果序列
x1, x2, ..., x2
满足下列条件,就说它是 斐波那契式 的:-
-- -
n >= 3
- 对于所有
+i + 2 <= n
,都有X_i + X_{i+1} = X_{i+2}
- +
n >= 3
- 对于所有
i + 2 <= n
,都有xi + xi+1 == xi+2
给定一个严格递增的正整数数组形成序列 arr ,找到 arr 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。
+给定一个 严格递增 的正整数数组形成序列
-arr
,找到arr
中最长的斐波那契式的子序列的长度。如果不存在,返回0
。(回想一下,子序列是从原序列 arr 中派生出来的,它从 arr 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如,
+[3, 5, 8]
是[3, 4, 5, 6, 7, 8]
的一个子序列)子序列 是通过从另一个序列
-arr
中删除任意数量的元素(包括删除 0 个元素)得到的,同时不改变剩余元素顺序。例如,[3, 5, 8]
是[3, 4, 5, 6, 7, 8]
的子序列。+
@@ -42,7 +42,7 @@ tags: 解释: 最长的斐波那契式子序列为 [1,2,3,5,8] 。
示例 2:
+示例 2:
输入: arr = [1,3,7,11,12,14,18] @@ -50,14 +50,14 @@ tags: 解释: 最长的斐波那契式子序列有 [1,11,12]、[3,11,14] 以及 [7,11,18] 。-+
提示:
3 <= arr.length <= 1000
3 <= arr.length <= 1000
1 <= arr[i] < arr[i + 1] <= 10^9
1 <= arr[i] < arr[i + 1] <= 109
在 n x n
的网格 grid
中,我们放置了一些与 x,y,z 三轴对齐的 1 x 1 x 1
立方体。
每个值 v = grid[i][j]
表示 v
个正方体叠放在单元格 (i, j)
上。
每个值 v = grid[i][j]
表示有一列 v
个正方体叠放在格子 (i, j)
上。
现在,我们查看这些立方体在 xy
、yz
和 zx
平面上的投影。
输入:nums = [5,2,3,1] 输出:[1,2,3,5] +解释:数组排序后,某些数字的位置没有改变(例如,2 和 3),而其他数字的位置发生了改变(例如,1 和 5)。
示例 2:
@@ -44,6 +45,7 @@ tags:输入:nums = [5,1,1,2,0,0] 输出:[0,0,1,1,2,5] +解释:请注意,nums 的值不一定唯一。
diff --git a/solution/0900-0999/0912.Sort an Array/README_EN.md b/solution/0900-0999/0912.Sort an Array/README_EN.md index 4459f121075b6..fe0d0ef1d3c87 100644 --- a/solution/0900-0999/0912.Sort an Array/README_EN.md +++ b/solution/0900-0999/0912.Sort an Array/README_EN.md @@ -41,7 +41,7 @@ tags:
Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] -Explanation: Note that the values of nums are not necessairly unique. +Explanation: Note that the values of nums are not necessarily unique.
diff --git a/solution/0900-0999/0916.Word Subsets/README.md b/solution/0900-0999/0916.Word Subsets/README.md index 97f9454475748..d6f55da7cb725 100644 --- a/solution/0900-0999/0916.Word Subsets/README.md +++ b/solution/0900-0999/0916.Word Subsets/README.md @@ -214,6 +214,94 @@ func wordSubsets(words1 []string, words2 []string) (ans []string) { } ``` +#### TypeScript + +```ts +function wordSubsets(words1: string[], words2: string[]): string[] { + const cnt: number[] = Array(26).fill(0); + for (const b of words2) { + const t: number[] = Array(26).fill(0); + for (const c of b) { + t[c.charCodeAt(0) - 97]++; + } + for (let i = 0; i < 26; i++) { + cnt[i] = Math.max(cnt[i], t[i]); + } + } + + const ans: string[] = []; + for (const a of words1) { + const t: number[] = Array(26).fill(0); + for (const c of a) { + t[c.charCodeAt(0) - 97]++; + } + + let ok = true; + for (let i = 0; i < 26; i++) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + + if (ok) { + ans.push(a); + } + } + + return ans; +} +``` + +#### JavaScript + +```js +/** + * @param {string[]} words1 + * @param {string[]} words2 + * @return {string[]} + */ +var wordSubsets = function (words1, words2) { + const cnt = Array(26).fill(0); + + for (const b of words2) { + const t = Array(26).fill(0); + + for (const c of b) { + t[c.charCodeAt(0) - 97]++; + } + + for (let i = 0; i < 26; i++) { + cnt[i] = Math.max(cnt[i], t[i]); + } + } + + const ans = []; + + for (const a of words1) { + const t = Array(26).fill(0); + + for (const c of a) { + t[c.charCodeAt(0) - 97]++; + } + + let ok = true; + for (let i = 0; i < 26; i++) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + + if (ok) { + ans.push(a); + } + } + + return ans; +}; +``` + diff --git a/solution/0900-0999/0916.Word Subsets/README_EN.md b/solution/0900-0999/0916.Word Subsets/README_EN.md index ff537e35eb96d..1b326bdfe3c43 100644 --- a/solution/0900-0999/0916.Word Subsets/README_EN.md +++ b/solution/0900-0999/0916.Word Subsets/README_EN.md @@ -209,6 +209,94 @@ func wordSubsets(words1 []string, words2 []string) (ans []string) { } ``` +#### TypeScript + +```ts +function wordSubsets(words1: string[], words2: string[]): string[] { + const cnt: number[] = Array(26).fill(0); + for (const b of words2) { + const t: number[] = Array(26).fill(0); + for (const c of b) { + t[c.charCodeAt(0) - 97]++; + } + for (let i = 0; i < 26; i++) { + cnt[i] = Math.max(cnt[i], t[i]); + } + } + + const ans: string[] = []; + for (const a of words1) { + const t: number[] = Array(26).fill(0); + for (const c of a) { + t[c.charCodeAt(0) - 97]++; + } + + let ok = true; + for (let i = 0; i < 26; i++) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + + if (ok) { + ans.push(a); + } + } + + return ans; +} +``` + +#### JavaScript + +```js +/** + * @param {string[]} words1 + * @param {string[]} words2 + * @return {string[]} + */ +var wordSubsets = function (words1, words2) { + const cnt = Array(26).fill(0); + + for (const b of words2) { + const t = Array(26).fill(0); + + for (const c of b) { + t[c.charCodeAt(0) - 97]++; + } + + for (let i = 0; i < 26; i++) { + cnt[i] = Math.max(cnt[i], t[i]); + } + } + + const ans = []; + + for (const a of words1) { + const t = Array(26).fill(0); + + for (const c of a) { + t[c.charCodeAt(0) - 97]++; + } + + let ok = true; + for (let i = 0; i < 26; i++) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + + if (ok) { + ans.push(a); + } + } + + return ans; +}; +``` + diff --git a/solution/0900-0999/0916.Word Subsets/Solution.js b/solution/0900-0999/0916.Word Subsets/Solution.js new file mode 100644 index 0000000000000..a231afd792875 --- /dev/null +++ b/solution/0900-0999/0916.Word Subsets/Solution.js @@ -0,0 +1,44 @@ +/** + * @param {string[]} words1 + * @param {string[]} words2 + * @return {string[]} + */ +var wordSubsets = function (words1, words2) { + const cnt = Array(26).fill(0); + + for (const b of words2) { + const t = Array(26).fill(0); + + for (const c of b) { + t[c.charCodeAt(0) - 97]++; + } + + for (let i = 0; i < 26; i++) { + cnt[i] = Math.max(cnt[i], t[i]); + } + } + + const ans = []; + + for (const a of words1) { + const t = Array(26).fill(0); + + for (const c of a) { + t[c.charCodeAt(0) - 97]++; + } + + let ok = true; + for (let i = 0; i < 26; i++) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + + if (ok) { + ans.push(a); + } + } + + return ans; +}; diff --git a/solution/0900-0999/0916.Word Subsets/Solution.ts b/solution/0900-0999/0916.Word Subsets/Solution.ts new file mode 100644 index 0000000000000..132e2b7974dfc --- /dev/null +++ b/solution/0900-0999/0916.Word Subsets/Solution.ts @@ -0,0 +1,34 @@ +function wordSubsets(words1: string[], words2: string[]): string[] { + const cnt: number[] = Array(26).fill(0); + for (const b of words2) { + const t: number[] = Array(26).fill(0); + for (const c of b) { + t[c.charCodeAt(0) - 97]++; + } + for (let i = 0; i < 26; i++) { + cnt[i] = Math.max(cnt[i], t[i]); + } + } + + const ans: string[] = []; + for (const a of words1) { + const t: number[] = Array(26).fill(0); + for (const c of a) { + t[c.charCodeAt(0) - 97]++; + } + + let ok = true; + for (let i = 0; i < 26; i++) { + if (cnt[i] > t[i]) { + ok = false; + break; + } + } + + if (ok) { + ans.push(a); + } + } + + return ans; +} diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/README.md b/solution/0900-0999/0923.3Sum With Multiplicity/README.md index 8304f7ca2d34d..88ec551f961a0 100644 --- a/solution/0900-0999/0923.3Sum With Multiplicity/README.md +++ b/solution/0900-0999/0923.3Sum With Multiplicity/README.md @@ -12,7 +12,7 @@ tags: -# [923. 三数之和的多种可能](https://leetcode.cn/problems/3sum-with-multiplicity) +# [923. 多重三数之和](https://leetcode.cn/problems/3sum-with-multiplicity) [English Version](/solution/0900-0999/0923.3Sum%20With%20Multiplicity/README_EN.md) diff --git a/solution/0900-0999/0939.Minimum Area Rectangle/README.md b/solution/0900-0999/0939.Minimum Area Rectangle/README.md index 7a98ebe927790..7925013d4fd67 100644 --- a/solution/0900-0999/0939.Minimum Area Rectangle/README.md +++ b/solution/0900-0999/0939.Minimum Area Rectangle/README.md @@ -20,34 +20,36 @@ tags: -
给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。
+给你一个 X-Y 平面上的点数组 points
,其中 points[i] = [xi, yi]
。
如果没有任何矩形,就返回 0。
+返回由这些点形成的矩形的最小面积,矩形的边与 X 轴和 Y 轴平行。如果不存在这样的矩形,则返回 0
。
-
示例 1:
- -输入:[[1,1],[1,3],[3,1],[3,3],[2,2]] -输出:4 +示例 1:
++
+输入: points = [[1,1],[1,3],[3,1],[3,3],[2,2]] +输出: 4-示例 2:
- -输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] -输出:2 +示例 2:
++
+输入: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] +输出: 2
提示:
-+
+
- -
1 <= points.length <= 500
- -
0 <= points[i][0] <= 40000
- -
0 <= points[i][1] <= 40000
- 所有的点都是不同的。
-
points[i].length == 2
0 <= xi, yi <= 4 * 104
只要经过一定次数的翻转操作后,能使 X 等于 Y,我们就称二叉树 X 翻转 等价 于二叉树 Y。
-这些树由根节点 root1
和 root2
给出。如果两个二叉树是否是翻转 等价 的函数,则返回 true
,否则返回 false
。
这些树由根节点 root1
和 root2
给出。如果两个二叉树是否是翻转 等价 的树,则返回 true
,否则返回 false
。
diff --git a/solution/0900-0999/0963.Minimum Area Rectangle II/README.md b/solution/0900-0999/0963.Minimum Area Rectangle II/README.md index 4f23117a1fb07..95985de7da993 100644 --- a/solution/0900-0999/0963.Minimum Area Rectangle II/README.md +++ b/solution/0900-0999/0963.Minimum Area Rectangle II/README.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/0900-0999/0963.Mi tags: - 几何 - 数组 + - 哈希表 - 数学 --- @@ -18,58 +19,48 @@ tags: -
给定在 xy 平面上的一组点,确定由这些点组成的任何矩形的最小面积,其中矩形的边不一定平行于 x 轴和 y 轴。
+给你一个 X-Y 平面上的点数组 points
,其中 points[i] = [xi, yi]
。
如果没有任何矩形,就返回 0。
+返回由这些点形成的任意矩形的最小面积,矩形的边 不一定 平行于 X 轴和 Y 轴。如果不存在这样的矩形,则返回 0
。
- -
示例 1:
- -输入:[[1,2],[2,1],[1,0],[0,1]] -输出:2.00000 -解释:最小面积的矩形出现在 [1,2],[2,1],[1,0],[0,1] 处,面积为 2。- -
示例 2:
+答案只需在10-5
的误差范围内即可被视作正确答案。
-
输入:[[0,1],[2,1],[1,1],[1,0],[2,0]] -输出:1.00000 -解释:最小面积的矩形出现在 [1,0],[1,1],[2,1],[2,0] 处,面积为 1。 +示例 1:
++
+输入: points = [[1,2],[2,1],[1,0],[0,1]] +输出: 2.00000 +解释: 最小面积矩形由 [1,2]、[2,1]、[1,0]、[0,1] 组成,其面积为 2。-示例 3:
- -- -
输入:[[0,3],[1,2],[3,1],[1,3],[2,1]] -输出:0 -解释:没法从这些点中组成任何矩形。 +示例 2:
++
+输入: points = [[0,1],[2,1],[1,1],[1,0],[2,0]] +输出: 1.00000 +解释: 最小面积矩形由 [1,0]、[1,1]、[2,1]、[2,0] 组成,其面积为 1。-示例 4:
- -- -
输入:[[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]] -输出:2.00000 -解释:最小面积的矩形出现在 [2,1],[2,3],[3,3],[3,1] 处,面积为 2。 +示例 3:
++
+输入: points = [[0,3],[1,2],[3,1],[1,3],[2,1]] +输出: 0 +解释: 无法由这些点组成任何矩形。
提示:
-+
+
- -
1 <= points.length <= 50
- -
0 <= points[i][0] <= 40000
- -
0 <= points[i][1] <= 40000
- 所有的点都是不同的。
-- 与真实值误差不超过
-10^-5
的答案将视为正确结果。
points[i].length == 2
0 <= xi, yi <= 4 * 104
输入:s1 = "parker", s2 = "morris", baseStr = "parser" 输出:"makkek" -解释:根据A
和B 中的等价信息,
我们可以将这些字符分为[m,p]
,[a,o]
,[k,r,s]
,[e,i] 共 4 组
。每组中的字符都是等价的,并按字典序排列。所以答案是"makkek"
。 +解释:根据A
和B
中的等价信息,我们可以将这些字符分为[m,p]
,[a,o]
,[k,r,s]
,[e,i]
共 4 组。每组中的字符都是等价的,并按字典序排列。所以答案是"makkek"
。
示例 2:
@@ -52,7 +52,7 @@ tags:输入:s1 = "hello", s2 = "world", baseStr = "hold" 输出:"hdld" -解释:根据A
和B 中的等价信息,
我们可以将这些字符分为[h,w]
,[d,e,o]
,[l,r] 共 3 组
。所以只有 S 中的第二个字符'o'
变成'd',最后答案为
"hdld"
。 +解释:根据A
和B
中的等价信息,我们可以将这些字符分为[h,w]
,[d,e,o]
,[l,r]
共 3 组。所以只有 S 中的第二个字符'o'
变成'd'
,最后答案为"hdld"
。
示例 3:
@@ -60,7 +60,7 @@ tags:输入:s1 = "leetcode", s2 = "programs", baseStr = "sourcecode" 输出:"aauaaaaada" -解释:我们可以把 A 和 B 中的等价字符分为[a,o,e,r,s,c]
,[l,p]
,[g,t]
和[d,m] 共 4 组
,因此S
中除了'u'
和'd'
之外的所有字母都转化成了'a'
,最后答案为"aauaaaaada"
。 +解释:我们可以把A
和B
中的等价字符分为[a,o,e,r,s,c]
,[l,p]
,[g,t]
和[d,m]
共 4 组,因此S
中除了'u'
和'd'
之外的所有字母都转化成了'a'
,最后答案为"aauaaaaada"
。
@@ -79,7 +79,11 @@ tags: -### 方法一 +### 方法一:并查集 + +我们可以使用并查集来处理等价字符的关系。每个字符可以看作一个节点,等价关系可以看作是连接这些节点的边。通过并查集,我们可以将所有等价的字符归为一类,并且在查询时能够快速找到每个字符的代表元素。我们在进行合并操作时,始终将代表元素设置为字典序最小的字符,这样可以确保最终得到的字符串是按字典序排列的最小等价字符串。 + +时间复杂度 $O((n + m) \times \log |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $n$ 是字符串 $s1$ 和 $s2$ 的长度,而 $m$ 是字符串 $baseStr$ 的长度,而 $|\Sigma|$ 是字符集的大小,本题中 $|\Sigma| = 26$。 @@ -88,54 +92,47 @@ tags: ```python class Solution: def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str: - p = list(range(26)) - - def find(x): + def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] - for i in range(len(s1)): - a, b = ord(s1[i]) - ord('a'), ord(s2[i]) - ord('a') - pa, pb = find(a), find(b) - if pa < pb: - p[pb] = pa + p = list(range(26)) + for a, b in zip(s1, s2): + x, y = ord(a) - ord("a"), ord(b) - ord("a") + px, py = find(x), find(y) + if px < py: + p[py] = px else: - p[pa] = pb - - res = [] - for a in baseStr: - a = ord(a) - ord('a') - res.append(chr(find(a) + ord('a'))) - return ''.join(res) + p[px] = py + return "".join(chr(find(ord(c) - ord("a")) + ord("a")) for c in baseStr) ``` #### Java ```java class Solution { - private int[] p; + private final int[] p = new int[26]; public String smallestEquivalentString(String s1, String s2, String baseStr) { - p = new int[26]; - for (int i = 0; i < 26; ++i) { + for (int i = 0; i < p.length; ++i) { p[i] = i; } for (int i = 0; i < s1.length(); ++i) { - int a = s1.charAt(i) - 'a', b = s2.charAt(i) - 'a'; - int pa = find(a), pb = find(b); - if (pa < pb) { - p[pb] = pa; + int x = s1.charAt(i) - 'a'; + int y = s2.charAt(i) - 'a'; + int px = find(x), py = find(y); + if (px < py) { + p[py] = px; } else { - p[pa] = pb; + p[px] = py; } } - StringBuilder sb = new StringBuilder(); - for (char a : baseStr.toCharArray()) { - char b = (char) (find(a - 'a') + 'a'); - sb.append(b); + char[] s = baseStr.toCharArray(); + for (int i = 0; i < s.length; ++i) { + s[i] = (char) ('a' + find(s[i] - 'a')); } - return sb.toString(); + return String.valueOf(s); } private int find(int x) { @@ -152,32 +149,30 @@ class Solution { ```cpp class Solution { public: - vector
给出 字符串 text
和 字符串列表 words
, 返回所有的索引对 [i, j]
使得在索引对范围内的子字符串 text[i]...text[j]
(包括 i
和 j
)属于字符串列表 words
。
给出 字符串 text
和 字符串列表 words
, 返回所有的索引对 [i, j]
使得子字符串 text[i]...text[j]
(包括 i
和 j
)属于字符串列表 words
。
按顺序返回索引对 [i, j]
(即,按它们的第一个坐标进行排序,如果相同,则按它们的第二个坐标对它们进行排序)。
示例 1:
-输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] ++输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] 输出: [[3,7],[9,13],[10,17]]示例 2:
-输入: text = "ababa", words = ["aba","ab"] ++输入: text = "ababa", words = ["aba","ab"] 输出: [[0,1],[0,2],[2,3],[2,4]] 解释: -注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中 +注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中
提示:
--
+- 所有字符串都只包含小写字母。
-- 保证
+words
中的字符串无重复。
1 <= text.length <= 100
1 <= words.length <= 20
- -
1 <= words[i].length <= 50
- 按序返回索引对
-[i,j]
(即,按照索引对的第一个索引进行排序,当第一个索引对相同时按照第二个索引对排序)。
text
和 words[i]
都只包含小写字母。words
中的字符串无重复。- -
产品表 Product
:
-+--------------+---------+ -| Column Name | Type | -+--------------+---------+ -| product_id | int | -| product_name | varchar | -+--------------+---------+ -product_id 是这张表的主键(具有唯一值的列)。 -这张表的每一行都标识:每个产品的 id 和 产品名称。+
编写解决方案,选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。
-+
product_id
,找到其在Sales表中首次出现的最早年份。编写解决方案,选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。
+返回一张有这些列的表:product_id,first_year,quantity 和 price。
结果表中的条目可以按 任意顺序 排列。
-结果格式如下例所示:
-
示例 1:
@@ -70,14 +60,6 @@ Sales 表: | 2 | 100 | 2009 | 12 | 5000 | | 7 | 200 | 2011 | 15 | 9000 | +---------+------------+------+----------+-------+ -Product 表: -+------------+--------------+ -| product_id | product_name | -+------------+--------------+ -| 100 | Nokia | -| 200 | Apple | -| 300 | Samsung | -+------------+--------------+ 输出: +------------+------------+----------+-------+ | product_id | first_year | quantity | price | diff --git a/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md b/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md index 03c8643cae525..c948fe652735b 100644 --- a/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md +++ b/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md @@ -30,32 +30,25 @@ tags: +-------------+-------+ (sale_id, year) is the primary key (combination of columns with unique values) of this table. product_id is a foreign key (reference column) toProduct
table.
-Each row of this table shows a sale on the product product_id in a certain year.
-Note that the price is per unit.
-
-
-- -
Table: Product
-+--------------+---------+ -| Column Name | Type | -+--------------+---------+ -| product_id | int | -| product_name | varchar | -+--------------+---------+ -product_id is the primary key (column with unique values) of this table. -Each row of this table indicates the product name of each product.-
- -
Write a solution to select the product id, year, quantity, and price for the first year of every product sold.
+Write a solution to find all sales that occurred in the first year each product was sold.
-Return the resulting table in any order.
+For each product_id
, identify the earliest year
it appears in the Sales
table.
Return all sales entries for that product in that year.
+The result format is in the following example.
+Return a table with the following columns: product_id, first_year, quantity, and price.
+Return the result in any order.
Example 1:
@@ -70,14 +63,7 @@ Sales table: | 2 | 100 | 2009 | 12 | 5000 | | 7 | 200 | 2011 | 15 | 9000 | +---------+------------+------+----------+-------+ -Product table: -+------------+--------------+ -| product_id | product_name | -+------------+--------------+ -| 100 | Nokia | -| 200 | Apple | -| 300 | Samsung | -+------------+--------------+ + Output: +------------+------------+----------+-------+ | product_id | first_year | quantity | price | diff --git a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md index d141c92ba6e45..537e7be2aa54c 100644 --- a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md +++ b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md @@ -23,18 +23,29 @@ tags:A defanged IP address replaces every period "."
with "[.]"
.
+
Example 1:
+Input: address = "1.1.1.1" + Output: "1[.]1[.]1[.]1" +
Example 2:
+Input: address = "255.100.50.0" + Output: "255[.]100[.]50[.]0" ++
+
Constraints:
address
is a valid IPv4 address.address
is a valid IPv4 address.A string is a valid parentheses string (denoted VPS) if and only if it consists of "("
and ")"
characters only, and:
AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.We can similarly define the nesting depth depth(S)
of any VPS S
as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.For example, ""
, "()()"
, and "()(()())"
are VPS's (with nesting depths 0, 1, and 2), and ")("
and "(()"
are not VPS's.
We may make the following moves:
'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.(Here, the only positions that exist on the board are positions with letters on them.)
@@ -40,19 +46,31 @@ tags:Return a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
+
Example 1:
+Input: target = "leet" + Output: "DDR!UURRR!!DDD!" +
Example 2:
+Input: target = "code" + Output: "RR!DDRR!UUL!R!" ++
+
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.1 <= target.length <= 100
target
consists only of English lowercase letters.Given a 2D grid
of 0
s and 1
s, return the number of elements in the largest square subgrid that has all 1
s on its border, or 0
if such a subgrid doesn't exist in the grid
.
+
Example 1:
+ Input: grid = [[1,1,1],[1,0,1],[1,1,1]] + Output: 9 +
Example 2:
+ Input: grid = [[1,1,0,0]] + Output: 1 +
+
Constraints:
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
-
请查询出所有浏览过自己文章的作者
+请查询出所有浏览过自己文章的作者。
-结果按照 id
升序排列。
结果按照作者的 id
升序排列。
查询结果的格式如下所示:
diff --git a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md index 5b959a1bb55b8..96da4eb86409c 100644 --- a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md +++ b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md @@ -7,6 +7,7 @@ source: 第 6 场双周赛 Q3 tags: - 数组 - 哈希表 + - 字符串 - 排序 --- diff --git a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md index 068e467a7a42c..11b798982680a 100644 --- a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md +++ b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md @@ -7,6 +7,7 @@ source: Biweekly Contest 6 Q3 tags: - Array - Hash Table + - String - Sorting --- diff --git a/solution/1100-1199/1153.String Transforms Into Another String/README.md b/solution/1100-1199/1153.String Transforms Into Another String/README.md index f2dfb0706cad4..1871225bf341a 100644 --- a/solution/1100-1199/1153.String Transforms Into Another String/README.md +++ b/solution/1100-1199/1153.String Transforms Into Another String/README.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1100-1199/1153.St rating: 1949 source: 第 6 场双周赛 Q4 tags: + - 图 - 哈希表 - 字符串 --- diff --git a/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md b/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md index 01c129fb6f316..d60d629f841a2 100644 --- a/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md +++ b/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md @@ -5,6 +5,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/1100-1199/1153.St rating: 1949 source: Biweekly Contest 6 Q4 tags: + - Graph - Hash Table - String --- diff --git a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md index 6b9897e53caa4..d39c633d50950 100644 --- a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md +++ b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md @@ -21,13 +21,11 @@ tags: -给你一份『词汇表』(字符串数组) words
和一张『字母表』(字符串) chars
。
给定一个字符串数组 words
和一个字符串 chars
。
假如你可以用 chars
中的『字母』(字符)拼写出 words
中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
如果字符串可以由 chars
中的字符组成(每个字符在 每个 words
中只能使用一次),则认为它是好的。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars
中的每个字母都只能用一次。
返回词汇表 words
中你掌握的所有单词的 长度之和。
返回 words
中所有好的字符串的长度之和。
@@ -56,7 +54,7 @@ tags:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
words[i]
和 chars
中都仅包含小写英文字母You are given an array of strings words
and a string chars
.
A string is good if it can be formed by characters from chars
(each character can only be used once).
A string is good if it can be formed by characters from chars
(each character can only be used once for each word in words
).
Return the sum of lengths of all good strings in words.
diff --git a/solution/1100-1199/1164.Product Price at a Given Date/README.md b/solution/1100-1199/1164.Product Price at a Given Date/README.md index 7f0478aa0b08d..9506824a43bed 100644 --- a/solution/1100-1199/1164.Product Price at a Given Date/README.md +++ b/solution/1100-1199/1164.Product Price at a Given Date/README.md @@ -29,9 +29,9 @@ tags: (product_id, change_date) 是此表的主键(具有唯一值的列组合)。 这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。 -+
一开始,所有产品价格都为 10。
-编写一个解决方案,找出在 2019-08-16
时全部产品的价格,假设所有产品在修改前的价格都是 10
。
编写一个解决方案,找出在 2019-08-16
所有产品的价格。
以 任意顺序 返回结果表。
diff --git a/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md b/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md index 9e6ffa8caf273..0f8436fcb8040 100644 --- a/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md +++ b/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md @@ -29,13 +29,13 @@ tags: (product_id, change_date) is the primary key (combination of columns with unique values) of this table. Each row of this table indicates that the price of some product was changed to a new price at some date. -+
Initially, all products have price 10.
-Write a solution to find the prices of all products on 2019-08-16
. Assume the price of all products before any change is 10
.
Write a solution to find the prices of all products on the date 2019-08-16
.
Return the result table in any order.
-The result format is in the following example.
+The result format is in the following example.
Example 1:
diff --git a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md index d947861120f5a..b4e5e94f2f0f6 100644 --- a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md +++ b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md @@ -25,13 +25,17 @@ tags:Return the shortest distance between the given start
and destination
stops.
+
Example 1:
+ Input: distance = [1,2,3,4], start = 0, destination = 1 + Output: 1 + Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
@@ -41,9 +45,13 @@ tags:
+ Input: distance = [1,2,3,4], start = 0, destination = 2 + Output: 3 + Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3. +
@@ -53,19 +61,29 @@ tags:
+ Input: distance = [1,2,3,4], start = 0, destination = 3 + Output: 4 + Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4. +
+
Constraints:
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
给定一个链接 startUrl
和一个接口 HtmlParser
,请你实现一个网络爬虫,以实现爬取同 startUrl
拥有相同 主机名 的全部链接。
给定一个网址 startUrl
和一个接口 HtmlParser
,请你实现一个网络爬虫,以实现爬取同 startUrl
拥有相同 主机名 的全部链接。
该爬虫得到的全部链接可以 任何顺序 返回结果。
+该爬虫得到的全部网址可以 任何顺序 返回结果。
你的网络爬虫应当按照如下模式工作:
startUrl
开始爬取HtmlParser.getUrls(url)
来获得链接url
页面中的全部链接startUrl
开始爬取HtmlParser.getUrls(url)
来获得给定 url
网址中的全部链接startUrl
相同 的链接集合startUrl
相同 的链接集合如上所示的一个链接,其域名为 example.org
。简单起见,你可以假设所有的链接都采用 http协议 并没有指定 端口。例如,链接 http://leetcode.com/problems
和 http://leetcode.com/contest
是同一个域名下的,而链接 http://example.org/test
和 http://example.com/abc
是不在同一域名下的。
如上所示的一个网址,其域名为 example.org
。简单起见,你可以假设所有的网址都采用 http协议 并没有指定 端口。例如,网址 http://leetcode.com/problems
和 http://leetcode.com/contest
是同一个域名下的,而网址 http://example.org/test
和 http://example.com/abc
是不在同一域名下的。
HtmlParser
接口定义如下:
下面是两个实例,用以解释该问题的设计功能,对于自定义测试,你可以使用三个变量 urls
, edges
和 startUrl
。注意在代码实现中,你只可以访问 startUrl
,而 urls
和 edges
不可以在你的代码中被直接访问。
注意:将尾随斜线“/”的相同 URL 视为不同的 URL。例如,“http://news.yahoo.com” 和 “http://news.yahoo.com/” 是不同的域名。
+注意:将尾随斜线“/”的相同网址视为不同的网址。例如,“http://news.yahoo.com” 和 “http://news.yahoo.com/” 是不同的网址。
diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py index 5ded8ceac1b32..55795052d710e 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution.py @@ -1,11 +1,11 @@ """ - This is the custom function interface. - You should not implement it, or speculate about its implementation - class CustomFunction: - # Returns f(x, y) for any given positive integers x and y. - # Note that f(x, y) is increasing with respect to both x and y. - # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - def f(self, x, y): +This is the custom function interface. +You should not implement it, or speculate about its implementation +class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): """ diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py index 424c1376a9106..c6c5774e3fe87 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/Solution2.py @@ -1,11 +1,11 @@ """ - This is the custom function interface. - You should not implement it, or speculate about its implementation - class CustomFunction: - # Returns f(x, y) for any given positive integers x and y. - # Note that f(x, y) is increasing with respect to both x and y. - # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - def f(self, x, y): +This is the custom function interface. +You should not implement it, or speculate about its implementation +class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): """ diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md index 57a0b48ed9325..f3d3a209aa212 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md @@ -23,35 +23,53 @@ tags:
Given 2 integers n
and start
. Your task is return any permutation p
of (0,1,2.....,2^n -1)
such that :
p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.+
Example 1:
+ Input: n = 2, start = 3 + Output: [3,2,0,1] + Explanation: The binary representation of the permutation is (11,10,00,01). + All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2] +
Example 2:
+ Input: n = 3, start = 2 + Output: [2,6,7,5,4,0,1,3] + Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011). +
+
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n
1 <= n <= 16
0 <= start < 2 ^ n
+
Example 1:
+ Input: num = 23 + Output: "1000" +
Example 2:
+ Input: num = 107 + Output: "101100" +
+
Constraints:
0 <= num <= 10^9
0 <= num <= 10^9
给你一些区域列表 regions
,每个列表的第一个区域都包含这个列表内所有其他区域。
给你一些区域列表 regions
,每个列表的第一个区域都 直接 包含这个列表内所有其他区域。
如果一个区域 x
直接包含区域 y
,并且区域 y
直接包含区域 z
,那么说区域 x
间接 包含区域 z
。请注意,区域 x
也 间接 包含所有在 y
中 间接 包含的区域。
很自然地,如果区域 x
包含区域 y
,那么区域 x
比区域 y
大。同时根据定义,区域 x
包含自身。
给定两个区域 region1
和 region2
,找到同时包含这两个区域的 最小 区域。
如果给定区域 r1
,r2
和 r3
,使得 r1
包含 r3
,那么数据保证 r2
不会包含 r3
。
数据同样保证最小区域一定存在。
diff --git a/solution/1200-1299/1257.Smallest Common Region/README_EN.md b/solution/1200-1299/1257.Smallest Common Region/README_EN.md index d5b52f58e36c7..2085a7c0a74a4 100644 --- a/solution/1200-1299/1257.Smallest Common Region/README_EN.md +++ b/solution/1200-1299/1257.Smallest Common Region/README_EN.md @@ -23,13 +23,13 @@ tags: -
You are given some lists of regions
where the first region of each list includes all other regions in that list.
You are given some lists of regions
where the first region of each list directly contains all other regions in that list.
Naturally, if a region x
contains another region y
then x
is bigger than y
. Also, by definition, a region x
contains itself.
If a region x
contains a region y
directly, and region y
contains region z
directly, then region x
is said to contain region z
indirectly. Note that region x
also indirectly contains all regions indirectly containd in y
.
Given two regions: region1
and region2
, return the smallest region that contains both of them.
Naturally, if a region x
contains (either directly or indirectly) another region y
, then x
is bigger than or equal to y
in size. Also, by definition, a region x
contains itself.
If you are given regions r1
, r2
, and r3
such that r1
includes r3
, it is guaranteed there is no r2
such that r2
includes r3
.
Given two regions: region1
and region2
, return the smallest region that contains both of them.
It is guaranteed the smallest region exists.
@@ -65,6 +65,7 @@ region2 = "New York"region1 != region2
regions[i][j]
, region1
, and region2
consist of English letters.请你返回该链表所表示数字的 十进制值 。
+最高位 在链表的头部。
+
示例 1:
-输入:head = [1,0,1] ++输入:head = [1,0,1] 输出:5 解释:二进制数 (101) 转化为十进制数 (5)示例 2:
-输入:head = [0] -输出:0 -- -示例 3:
- -输入:head = [1] -输出:1 -- -示例 4:
- -输入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] -输出:18880 -- -示例 5:
- -输入:head = [0,0] ++输入:head = [0] 输出:0@@ -76,11 +62,11 @@ tags: ### 方法一:遍历链表 -我们用变量 `ans` 记录当前的十进制值,初始值为 $0$。 +我们用变量 $\textit{ans}$ 记录当前的十进制值,初始值为 $0$。 -遍历链表,对于每个结点,将 `ans` 左移一位,然后再或上当前结点的值。遍历结束后,`ans` 即为十进制值。 +遍历链表,对于每个结点,将 $\textit{ans}$ 左移一位,然后再或上当前结点的值。遍历结束后,$\textit{ans}$ 即为十进制值。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为链表的长度。 +时间复杂度 $O(n)$,其中 $n$ 为链表的长度。空间复杂度 $O(1)$。 @@ -212,12 +198,11 @@ function getDecimalValue(head: ListNode | null): number { // } // } impl Solution { - pub fn get_decimal_value(head: Option>) -> i32 { + pub fn get_decimal_value(mut head: Option >) -> i32 { let mut ans = 0; - let mut cur = &head; - while let Some(node) = cur { + while let Some(node) = head { ans = (ans << 1) | node.val; - cur = &node.next; + head = node.next; } ans } @@ -247,6 +232,31 @@ var getDecimalValue = function (head) { }; ``` +#### C# + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public int GetDecimalValue(ListNode head) { + int ans = 0; + for (; head != null; head = head.next) { + ans = ans << 1 | head.val; + } + return ans; + } +} +``` + #### PHP ```php @@ -267,13 +277,12 @@ class Solution { * @return Integer */ function getDecimalValue($head) { - $rs = []; - while ($head != null) { - array_push($rs, $head->val); + $ans = 0; + while ($head !== null) { + $ans = ($ans << 1) | $head->val; $head = $head->next; } - $rsStr = implode($rs); - return bindec($rsStr); + return $ans; } } ``` diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md index 3e49f84db6367..5d6aaab02c5ac 100644 --- a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md @@ -56,7 +56,13 @@ tags: -### Solution 1 +### Solution 1: Traverse the Linked List + +We use a variable $\textit{ans}$ to record the current decimal value, with an initial value of $0$. + +Traverse the linked list. For each node, left-shift $\textit{ans}$ by one bit, then perform a bitwise OR with the current node's value. After traversal, $\textit{ans}$ is the decimal value. + +The time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$. @@ -188,12 +194,11 @@ function getDecimalValue(head: ListNode | null): number { // } // } impl Solution { - pub fn get_decimal_value(head: Option >) -> i32 { + pub fn get_decimal_value(mut head: Option >) -> i32 { let mut ans = 0; - let mut cur = &head; - while let Some(node) = cur { + while let Some(node) = head { ans = (ans << 1) | node.val; - cur = &node.next; + head = node.next; } ans } @@ -223,6 +228,31 @@ var getDecimalValue = function (head) { }; ``` +#### C# + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public int GetDecimalValue(ListNode head) { + int ans = 0; + for (; head != null; head = head.next) { + ans = ans << 1 | head.val; + } + return ans; + } +} +``` + #### PHP ```php @@ -243,13 +273,12 @@ class Solution { * @return Integer */ function getDecimalValue($head) { - $rs = []; - while ($head != null) { - array_push($rs, $head->val); + $ans = 0; + while ($head !== null) { + $ans = ($ans << 1) | $head->val; $head = $head->next; } - $rsStr = implode($rs); - return bindec($rsStr); + return $ans; } } ``` diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.cs b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.cs new file mode 100644 index 0000000000000..bbfcf9dbff062 --- /dev/null +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.cs @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public int GetDecimalValue(ListNode head) { + int ans = 0; + for (; head != null; head = head.next) { + ans = ans << 1 | head.val; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.php b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.php index 7ddaf720fe6ae..514bc47573ca4 100644 --- a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.php +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.php @@ -15,12 +15,11 @@ class Solution { * @return Integer */ function getDecimalValue($head) { - $rs = []; - while ($head != null) { - array_push($rs, $head->val); + $ans = 0; + while ($head !== null) { + $ans = ($ans << 1) | $head->val; $head = $head->next; } - $rsStr = implode($rs); - return bindec($rsStr); + return $ans; } } \ No newline at end of file diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.rs b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.rs index 7c122a66fc0df..b3f205ea5f95c 100644 --- a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.rs +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/Solution.rs @@ -15,12 +15,11 @@ // } // } impl Solution { - pub fn get_decimal_value(head: Option >) -> i32 { + pub fn get_decimal_value(mut head: Option >) -> i32 { let mut ans = 0; - let mut cur = &head; - while let Some(node) = cur { + while let Some(node) = head { ans = (ans << 1) | node.val; - cur = &node.next; + head = node.next; } ans } diff --git a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md index 6a05d1729477a..f8c826b083334 100644 --- a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md +++ b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md @@ -19,7 +19,7 @@ tags: - 给你一个整数数组
+nums
,请你返回其中位数为 偶数 的数字的个数。给你一个整数数组
nums
,请你返回其中包含 偶数 个数位的数字的个数。@@ -131,6 +131,16 @@ function findNumbers(nums: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_numbers(nums: Vec
) -> i32 { + nums.iter().filter(|&x| x.to_string().len() % 2 == 0).count() as i32 + } +} +``` + #### JavaScript ```js @@ -143,6 +153,16 @@ var findNumbers = function (nums) { }; ``` +#### C# + +```cs +public class Solution { + public int FindNumbers(int[] nums) { + return nums.Count(x => x.ToString().Length % 2 == 0); + } +} +``` + diff --git a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md index 85b2b1a18b99c..9c6351d5539df 100644 --- a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md +++ b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md @@ -129,6 +129,16 @@ function findNumbers(nums: number[]): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn find_numbers(nums: Vec ) -> i32 { + nums.iter().filter(|&x| x.to_string().len() % 2 == 0).count() as i32 + } +} +``` + #### JavaScript ```js @@ -141,6 +151,16 @@ var findNumbers = function (nums) { }; ``` +#### C# + +```cs +public class Solution { + public int FindNumbers(int[] nums) { + return nums.Count(x => x.ToString().Length % 2 == 0); + } +} +``` + diff --git a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/Solution.rs b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/Solution.rs new file mode 100644 index 0000000000000..26d91b28a550d --- /dev/null +++ b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/Solution.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn find_numbers(nums: Vec ) -> i32 { + nums.iter() + .filter(|&x| x.to_string().len() % 2 == 0) + .count() as i32 + } +} diff --git a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/Soluton.cs b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/Soluton.cs new file mode 100644 index 0000000000000..4a98e37e739fe --- /dev/null +++ b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/Soluton.cs @@ -0,0 +1,5 @@ +public class Solution { + public int FindNumbers(int[] nums) { + return nums.Count(x => x.ToString().Length % 2 == 0); + } +} \ No newline at end of file diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md index d974408e38dbb..d3430a8b06093 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md @@ -29,7 +29,7 @@ tags: 内含的盒子 -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