diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000000..9397c04a1ad15 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# REF: https://spec.editorconfig.org/#supported-pairs + +root = true + +[*] +indent_style = space +indent_size = 4 +# tab_width = 4 +# end_of_line = lf +charset = utf-8 +# spelling_language = en-US +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{md}] +trim_trailing_whitespace = false + +[*.{go}] +indent_style = tab + +[*.{yml,yaml}] +indent_size = 2 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 048f35f94c4d9..75f2788abda2e 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,13 +1,11 @@ name: deploy on: + workflow_dispatch: push: branches: - main - - docs paths: - - package.json - - requirements.txt - solution/** - lcs/** - lcp/** @@ -15,22 +13,14 @@ on: - lcof/** - lcci/** - basic/** - workflow_dispatch: - -env: - MKDOCS_API_KEYS: ${{ secrets.MKDOCS_API_KEYS }} - -permissions: - contents: write concurrency: 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 @@ -65,35 +55,36 @@ jobs: python3 -m pip install -r requirements.txt python3 -m pip install "mkdocs-material[imaging]" sudo apt-get install pngquant + + - name: Set MKDOCS_API_KEYS environment variable + run: echo "MKDOCS_API_KEYS=${{ secrets.MKDOCS_API_KEYS }}" >> $GITHUB_ENV - run: | python3 main.py mkdocs build -f mkdocs.yml mkdocs build -f mkdocs-en.yml - - name: Deploy - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./site + - name: Generate CNAME file + run: echo "leetcode.doocs.org" > ./site/CNAME - # 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: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: ./site - # - 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 \ No newline at end of file + # Deployment job + deploy: + needs: build + permissions: + pages: write + id-token: write + environment: + name: github_pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pr-add-label.yml b/.github/workflows/pr-add-label.yml index aeadb540a0666..82661e9eb237e 100644 --- a/.github/workflows/pr-add-label.yml +++ b/.github/workflows/pr-add-label.yml @@ -4,23 +4,20 @@ on: pull_request_target: types: [opened, edited, reopened, synchronize] -concurrency: - group: ${{github.workflow}} - ${{github.event_name}} - cancel-in-progress: true - 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: thinkasany/pr-label-action@master + uses: actionv/pr-label-action@master with: github_token: ${{ secrets.DOOCS_BOT_ACTION_TOKEN }} pr_number: ${{ env.PR_NUMBER }} diff --git a/.github/workflows/prettier.yml b/.github/workflows/prettier.yml index 3487fa7874225..3cc69b529c371 100644 --- a/.github/workflows/prettier.yml +++ b/.github/workflows/prettier.yml @@ -29,7 +29,7 @@ jobs: - name: Run prettier run: | git config --global core.quotepath off - changed_files=$(git diff --name-only "${{ github.event.pull_request.base.sha }}" | grep -E '\.js$|\.ts$|\.php$|\.sql$|\.rs$|\.md$' || true) + changed_files=$(git diff --name-only "${{ github.event.pull_request.base.sha }}" | grep -E '\.js$|\.ts$|\.php$|\.sql$|\.md$' || true) if [ -n "$changed_files" ]; then echo "Running prettier on the changed files" echo "$changed_files" | xargs -d '\n' npx prettier --write diff --git a/.gitignore b/.gitignore index 474929a437363..e8ebbedd5ad1e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,10 +2,11 @@ .DS_Store .vscode .temp +.vitepress .cache *.iml __pycache__ /node_modules /solution/result.json /solution/__pycache__ -/solution/.env \ No newline at end of file +/solution/.env diff --git a/.husky/_/husky.sh b/.husky/_/husky.sh index cec959a6b9d84..e69de29bb2d1d 100644 --- a/.husky/_/husky.sh +++ b/.husky/_/husky.sh @@ -1,36 +0,0 @@ -#!/usr/bin/env sh -if [ -z "$husky_skip_init" ]; then - debug () { - if [ "$HUSKY_DEBUG" = "1" ]; then - echo "husky (debug) - $1" - fi - } - - readonly hook_name="$(basename -- "$0")" - debug "starting $hook_name..." - - if [ "$HUSKY" = "0" ]; then - debug "HUSKY env variable is set to 0, skipping hook" - exit 0 - fi - - if [ -f ~/.huskyrc ]; then - debug "sourcing ~/.huskyrc" - . ~/.huskyrc - fi - - readonly husky_skip_init=1 - export husky_skip_init - sh -e "$0" "$@" - exitCode="$?" - - if [ $exitCode != 0 ]; then - echo "husky - $hook_name hook exited with code $exitCode (error)" - fi - - if [ $exitCode = 127 ]; then - echo "husky - command not found in PATH=$PATH" - fi - - exit $exitCode -fi diff --git a/.husky/commit-msg b/.husky/commit-msg old mode 100755 new mode 100644 index e810522282d3e..823cbaa47f802 --- a/.husky/commit-msg +++ b/.husky/commit-msg @@ -1,4 +1,3 @@ -#!/usr/bin/env sh -. "$(dirname -- "$0")/_/husky.sh" +#!/bin/sh npx --no -- commitlint --edit $1 diff --git a/.husky/pre-commit b/.husky/pre-commit old mode 100755 new mode 100644 index 98092e259194e..b915ae7603b09 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,3 @@ -#!/usr/bin/env sh -. "$(dirname -- "$0")/_/husky.sh" +#!/bin/sh npx lint-staged --allow-empty $1 diff --git a/.prettierignore b/.prettierignore index 761a3209faa0b..47b55e9bdf606 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,11 +16,14 @@ node_modules/ /solution/0100-0199/0177.Nth Highest Salary/Solution.sql /solution/0100-0199/0178.Rank Scores/Solution2.sql /solution/0500-0599/0586.Customer Placing the Largest Number of Orders/Solution2.sql -/solution/1400-1499/1454.Active Users/Solution.sql /solution/1600-1699/1635.Hopper Company Queries I/Solution.sql /solution/2100-2199/2118.Build the Equation/Solution.sql /solution/2100-2199/2175.The Change in Global Rankings/Solution.sql /solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/Solution.sql /solution/2200-2299/2230.The Users That Are Eligible for Discount/Solution.sql /solution/2200-2299/2252.Dynamic Pivoting of a Table/Solution.sql -/solution/2200-2299/2253.Dynamic Unpivoting of a Table/Solution.sql \ No newline at end of file +/solution/2200-2299/2253.Dynamic Unpivoting of a Table/Solution.sql +/solution/3100-3199/3150.Invalid Tweets II/Solution.sql +/solution/3100-3199/3198.Find Cities in Each State/Solution.sql +/solution/3300-3399/3328.Find Cities in Each State II/Solution.sql +/solution/3400-3499/3451.Find Invalid IP Addresses/Solution.sql diff --git a/.prettierrc b/.prettierrc index 292808f200d93..47eab9be9a8a3 100644 --- a/.prettierrc +++ b/.prettierrc @@ -11,10 +11,12 @@ "braceStyle": "1tbs", "endOfLine": "lf", "sqlKeywordCase": "upper", + "sqlCanonicalSyntax": false, "overrides": [ { "files": ["*.sql"], "options": { "parser": "mysql" } } - ] + ], + "plugins": ["prettier-plugin-sql-cst", "@prettier/plugin-php"] } diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000..2fc343b9c9600 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +# Use Node.js version 14 as the base image +FROM node:14 + +# Set the working directory inside the container +WORKDIR /app + +# Copy package.json and package-lock.json (if present) to the working directory +COPY package*.json ./ + +# Install npm dependencies +RUN npm install + +# Copy all files from the current directory to the working directory in the container +COPY . . + +# Expose port 80 to allow communication to/from the container +EXPOSE 80 + +# Specify the command to run the application +CMD ["npm", "start"] diff --git a/README.md b/README.md index 8431bfcb6e5fe..761cfcad81eae 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@
## 介绍 @@ -20,7 +20,7 @@ ## 站点 -https://doocs.github.io/leetcode +https://leetcode.doocs.org ## 算法全解 @@ -191,21 +191,32 @@ https://doocs.github.io/leetcode 1. 将你的变更以 PR 的形式提交过来,项目的维护人员会在第一时间对你的变更进行 review! 1. 你也可以参考帮助文档 https://help.github.com/cn 了解更多细节。 - +实现一个算法,确定一个字符串 s
的所有字符是否全都不同。
示例 1:
输入: s = "leetcode" -输出: false +输出: false
示例 2:
@@ -25,8 +34,12 @@Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
Example 1:
@@ -32,8 +42,12 @@0 <= len(s) <= 100
给定两个字符串 s1
和 s2
,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
示例 1:
@@ -26,8 +35,12 @@0 <= len(s2) <= 100
Given two strings,write a method to decide if one is a permutation of the other.
Example 1:
@@ -32,8 +42,12 @@0 <= len(s2) <= 100
URL化。编写一种方法,将字符串中的空格全部替换为%20
。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java
实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
@@ -25,8 +34,12 @@Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)
Example 1:
@@ -38,8 +48,12 @@ The missing numbers are [5,6,8,...], hence the third missing number is 8.0 <= S.length <= 500000
给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。
回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。
@@ -21,8 +30,12 @@+ + ## 解法 + + ### 方法一:哈希表 我们用哈希表 $cnt$ 存储每个字符出现的次数。若次数为奇数的字符超过 $1$ 个,则不是回文排列。 @@ -31,6 +44,8 @@ +#### Python3 + ```python class Solution: def canPermutePalindrome(self, s: str) -> bool: @@ -38,6 +53,8 @@ class Solution: return sum(v & 1 for v in cnt.values()) < 2 ``` +#### Java + ```java class Solution { public boolean canPermutePalindrome(String s) { @@ -54,6 +71,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -71,55 +90,52 @@ public: }; ``` +#### Go + ```go func canPermutePalindrome(s string) bool { - vis := map[rune]bool{} - cnt := 0 + cnt := map[rune]int{} for _, c := range s { - if vis[c] { - vis[c] = false - cnt-- - } else { - vis[c] = true - cnt++ - } + cnt[c]++ + } + sum := 0 + for _, v := range cnt { + sum += v & 1 } - return cnt < 2 + return sum < 2 } ``` +#### TypeScript + ```ts function canPermutePalindrome(s: string): boolean { - const set = new Set
Given a string, write a function to check if it is a permutation of a palin drome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
@@ -18,8 +28,12 @@ + + ## Solutions + + ### Solution 1: Hash Table We use a hash table $cnt$ to store the occurrence count of each character. If more than $1$ character has an odd count, then it is not a palindrome permutation. @@ -28,6 +42,8 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is +#### Python3 + ```python class Solution: def canPermutePalindrome(self, s: str) -> bool: @@ -35,6 +51,8 @@ class Solution: return sum(v & 1 for v in cnt.values()) < 2 ``` +#### Java + ```java class Solution { public boolean canPermutePalindrome(String s) { @@ -51,6 +69,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -68,55 +88,52 @@ public: }; ``` +#### Go + ```go func canPermutePalindrome(s string) bool { - vis := map[rune]bool{} - cnt := 0 + cnt := map[rune]int{} for _, c := range s { - if vis[c] { - vis[c] = false - cnt-- - } else { - vis[c] = true - cnt++ - } + cnt[c]++ + } + sum := 0 + for _, v := range cnt { + sum += v & 1 } - return cnt < 2 + return sum < 2 } ``` +#### TypeScript + ```ts function canPermutePalindrome(s: string): boolean { - const set = new Set
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
@@ -26,22 +35,28 @@ second = "pal" 输出: False + + ## 解法 + + ### 方法一:分情况讨论 + 双指针 -我们将字符串 $first$ 和 $second$ 的长度记为 $m$ 和 $n$,不妨设 $m \geq n$。 +我们将字符串 $\textit{first}$ 和 $\textit{second}$ 的长度记为 $m$ 和 $n$,不妨设 $m \geq n$。 接下来分情况讨论: -- 当 $m - n \gt 1$ 时,$first$ 和 $second$ 无法通过一次编辑得到,返回 `false`; -- 当 $m = n$ 时,$first$ 和 $second$ 只有在且仅在有且仅有一个字符不同的情况下才能通过一次编辑得到; -- 当 $m - n = 1$ 时,$first$ 和 $second$ 只有在且仅在 $second$ 是 $first$ 删除一个字符后得到的情况下才能通过一次编辑得到,我们可以使用双指针来实现。 +- 当 $m - n \gt 1$ 时,$\textit{first}$ 和 $\textit{second}$ 无法通过一次编辑得到,返回 `false`; +- 当 $m = n$ 时,$\textit{first}$ 和 $\textit{second}$ 只有在且仅在有且仅有一个字符不同的情况下才能通过一次编辑得到; +- 当 $m - n = 1$ 时,$\textit{first}$ 和 $\textit{second}$ 只有在且仅在 $\textit{second}$ 是 $\textit{first}$ 删除一个字符后得到的情况下才能通过一次编辑得到,我们可以使用双指针来实现。 时间复杂度 $O(n)$,其中 $n$ 为字符串长度。空间复杂度 $O(1)$。 +#### Python3 + ```python class Solution: def oneEditAway(self, first: str, second: str) -> bool: @@ -62,6 +77,8 @@ class Solution: return cnt < 2 ``` +#### Java + ```java class Solution { public boolean oneEditAway(String first, String second) { @@ -95,6 +112,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -129,6 +148,8 @@ public: }; ``` +#### Go + ```go func oneEditAway(first string, second string) bool { m, n := len(first), len(second) @@ -160,6 +181,8 @@ func oneEditAway(first string, second string) bool { } ``` +#### TypeScript + ```ts function oneEditAway(first: string, second: string): boolean { let m: number = first.length; @@ -194,6 +217,8 @@ function oneEditAway(first: string, second: string): boolean { } ``` +#### Rust + ```rust impl Solution { pub fn one_edit_away(first: String, second: String) -> bool { @@ -223,6 +248,8 @@ impl Solution { } ``` +#### Swift + ```swift class Solution { func oneEditAway(_ first: String, _ second: String) -> Bool { @@ -267,4 +294,6 @@ class Solution { - + + + diff --git a/lcci/01.05.One Away/README_EN.md b/lcci/01.05.One Away/README_EN.md index fe45ae237b16e..98a164c97d143 100644 --- a/lcci/01.05.One Away/README_EN.md +++ b/lcci/01.05.One Away/README_EN.md @@ -1,9 +1,19 @@ +--- +comments: true +difficulty: Medium +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/01.05.One%20Away/README_EN.md +--- + + + # [01.05. One Away](https://leetcode.cn/problems/one-away-lcci) [中文文档](/lcci/01.05.One%20Away/README.md) ## Description + +
There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
Example 1:
@@ -34,22 +44,28 @@ second = "pal" + + ## Solutions -### Solution 1: Case Discussion + Two Pointers + -We denote the lengths of strings $first$ and $second$ as $m$ and $n$, respectively, where $m \geq n$. +### Solution 1: Case Analysis + Two Pointers -Next, we discuss different cases: +Let the lengths of the strings $\textit{first}$ and $\textit{second}$ be $m$ and $n$, respectively. Assume $m \geq n$. -- When $m - n > 1$, $first$ and $second$ cannot be obtained through a single edit, so we return `false`. -- When $m = n$, $first$ and $second$ can only be obtained through a single edit if and only if exactly one character is different. -- When $m - n = 1$, $first$ and $second$ can only be obtained through a single edit if and only if $second$ is obtained by deleting one character from $first$. We can use two pointers to implement this. +Next, we discuss the following cases: + +- When $m - n \gt 1$, $\textit{first}$ and $\textit{second}$ cannot be made equal with one edit, so return `false`; +- When $m = n$, $\textit{first}$ and $\textit{second}$ can be made equal with one edit only if there is exactly one different character; +- When $m - n = 1$, $\textit{first}$ and $\textit{second}$ can be made equal with one edit only if $\textit{second}$ is obtained by deleting one character from $\textit{first}$. We can use two pointers to achieve this. The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. +#### Python3 + ```python class Solution: def oneEditAway(self, first: str, second: str) -> bool: @@ -70,6 +86,8 @@ class Solution: return cnt < 2 ``` +#### Java + ```java class Solution { public boolean oneEditAway(String first, String second) { @@ -103,6 +121,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -137,6 +157,8 @@ public: }; ``` +#### Go + ```go func oneEditAway(first string, second string) bool { m, n := len(first), len(second) @@ -168,6 +190,8 @@ func oneEditAway(first string, second string) bool { } ``` +#### TypeScript + ```ts function oneEditAway(first: string, second: string): boolean { let m: number = first.length; @@ -202,6 +226,8 @@ function oneEditAway(first: string, second: string): boolean { } ``` +#### Rust + ```rust impl Solution { pub fn one_edit_away(first: String, second: String) -> bool { @@ -231,6 +257,8 @@ impl Solution { } ``` +#### Swift + ```swift class Solution { func oneEditAway(_ first: String, _ second: String) -> Bool { @@ -275,4 +303,6 @@ class Solution { - + + + diff --git a/lcci/01.06.Compress String/README.md b/lcci/01.06.Compress String/README.md index 6c7ad202b717b..2a08b263e8ae5 100644 --- a/lcci/01.06.Compress String/README.md +++ b/lcci/01.06.Compress String/README.md @@ -1,10 +1,19 @@ +--- +comments: true +difficulty: 简单 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/01.06.Compress%20String/README.md +--- + + + # [面试题 01.06. 字符串压缩](https://leetcode.cn/problems/compress-string-lcci) [English Version](/lcci/01.06.Compress%20String/README_EN.md) ## 题目描述 - + +字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa
会变为a2b1c5a3
。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
示例1:
@@ -28,8 +37,12 @@Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
Example 1:
@@ -34,8 +44,12 @@ The compressed string is "a1b2c2d1", which is longer than the original - `0 <= S.length <= 50000` + + ## Solutions + + ### Solution 1: Two Pointers We can use two pointers to find the start and end positions of each consecutive character, calculate the length of the consecutive characters, and then append the character and length to the string $t$. @@ -46,6 +60,8 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is +#### Python3 + ```python class Solution: def compressString(self, S: str) -> str: @@ -53,19 +69,7 @@ class Solution: return min(S, t, key=len) ``` -```python -class Solution: - def compressString(self, S: str) -> str: - t = [] - i, n = 0, len(S) - while i < n: - j = i + 1 - while j < n and S[j] == S[i]: - j += 1 - t.append(S[i] + str(j - i)) - i = j - return min(S, "".join(t), key=len) -``` +#### Java ```java class Solution { @@ -86,6 +90,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -106,6 +112,8 @@ public: }; ``` +#### Go + ```go func compressString(S string) string { n := len(S) @@ -126,6 +134,8 @@ func compressString(S string) string { } ``` +#### Rust + ```rust impl Solution { pub fn compress_string(s: String) -> String { @@ -153,6 +163,8 @@ impl Solution { } ``` +#### JavaScript + ```js /** * @param {string} S @@ -173,6 +185,8 @@ var compressString = function (S) { }; ``` +#### Swift + ```swift class Solution { func compressString(_ S: String) -> String { @@ -197,4 +211,6 @@ class Solution { - + + + diff --git a/lcci/01.06.Compress String/Solution2.py b/lcci/01.06.Compress String/Solution2.py deleted file mode 100644 index d3bc1c1aab18d..0000000000000 --- a/lcci/01.06.Compress String/Solution2.py +++ /dev/null @@ -1,11 +0,0 @@ -class Solution: - def compressString(self, S: str) -> str: - t = [] - i, n = 0, len(S) - while i < n: - j = i + 1 - while j < n and S[j] == S[i]: - j += 1 - t.append(S[i] + str(j - i)) - i = j - return min(S, "".join(t), key=len) diff --git a/lcci/01.07.Rotate Matrix/README.md b/lcci/01.07.Rotate Matrix/README.md index f12e2efe8cd1e..d9b2763c2a520 100644 --- a/lcci/01.07.Rotate Matrix/README.md +++ b/lcci/01.07.Rotate Matrix/README.md @@ -1,10 +1,19 @@ +--- +comments: true +difficulty: 中等 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/01.07.Rotate%20Matrix/README.md +--- + + + # [面试题 01.07. 旋转矩阵](https://leetcode.cn/problems/rotate-matrix-lcci) [English Version](/lcci/01.07.Rotate%20Matrix/README_EN.md) ## 题目描述 - + +给定一幅由N × N矩阵表示的图像,其中每个像素的大小为4字节,编写一种方法,将图像旋转90度。
不占用额外内存空间能否做到?
@@ -47,18 +56,24 @@ ] + + ## 解法 + + ### 方法一:原地翻转 -根据题目要求,我们实际上需要将 $matrix[i][j]$ 旋转至 $matrix[j][n - i - 1]$。 +根据题目要求,我们实际上需要将 $\text{matrix}[i][j]$ 旋转至 $\text{matrix}[j][n - i - 1]$。 -我们可以先对矩阵进行上下翻转,即 $matrix[i][j]$ 和 $matrix[n - i - 1][j]$ 进行交换,然后再对矩阵进行主对角线翻转,即 $matrix[i][j]$ 和 $matrix[j][i]$ 进行交换。这样就能将 $matrix[i][j]$ 旋转至 $matrix[j][n - i - 1]$ 了。 +我们可以先对矩阵进行上下翻转,即 $\text{matrix}[i][j]$ 和 $\text{matrix}[n - i - 1][j]$ 进行交换,然后再对矩阵进行主对角线翻转,即 $\text{matrix}[i][j]$ 和 $\text{matrix}[j][i]$ 进行交换。这样就能将 $\text{matrix}[i][j]$ 旋转至 $\text{matrix}[j][n - i - 1]$ 了。 时间复杂度 $O(n^2)$,其中 $n$ 是矩阵的边长。空间复杂度 $O(1)$。 +#### Python3 + ```python class Solution: def rotate(self, matrix: List[List[int]]) -> None: @@ -71,6 +86,8 @@ class Solution: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] ``` +#### Java + ```java class Solution { public void rotate(int[][] matrix) { @@ -93,6 +110,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -112,6 +131,8 @@ public: }; ``` +#### Go + ```go func rotate(matrix [][]int) { n := len(matrix) @@ -128,6 +149,8 @@ func rotate(matrix [][]int) { } ``` +#### TypeScript + ```ts /** Do not return anything, modify matrix in-place instead. @@ -144,6 +167,8 @@ function rotate(matrix: number[][]): void { } ``` +#### Rust + ```rust impl Solution { pub fn rotate(matrix: &mut VecGiven an image represented by an N x N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
@@ -76,18 +86,24 @@ Rotate the matrix in place. It becomes: + + ## Solutions -### Solution 1: In-place Rotation + -According to the problem requirements, we actually need to rotate $matrix[i][j]$ to $matrix[j][n - i - 1]$. +### Solution 1: In-Place Rotation -We can first flip the matrix upside down, that is, swap $matrix[i][j]$ and $matrix[n - i - 1][j]$, and then flip the matrix along the main diagonal, that is, swap $matrix[i][j]$ and $matrix[j][i]$. This way, we can rotate $matrix[i][j]$ to $matrix[j][n - i - 1]$. +According to the problem requirements, we need to rotate $\text{matrix}[i][j]$ to $\text{matrix}[j][n - i - 1]$. + +We can first flip the matrix upside down, i.e., swap $\text{matrix}[i][j]$ with $\text{matrix}[n - i - 1][j]$, and then flip the matrix along the main diagonal, i.e., swap $\text{matrix}[i][j]$ with $\text{matrix}[j][i]$. This will rotate $\text{matrix}[i][j]$ to $\text{matrix}[j][n - i - 1]$. The time complexity is $O(n^2)$, where $n$ is the side length of the matrix. The space complexity is $O(1)$. +#### Python3 + ```python class Solution: def rotate(self, matrix: List[List[int]]) -> None: @@ -100,6 +116,8 @@ class Solution: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] ``` +#### Java + ```java class Solution { public void rotate(int[][] matrix) { @@ -122,6 +140,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -141,6 +161,8 @@ public: }; ``` +#### Go + ```go func rotate(matrix [][]int) { n := len(matrix) @@ -157,6 +179,8 @@ func rotate(matrix [][]int) { } ``` +#### TypeScript + ```ts /** Do not return anything, modify matrix in-place instead. @@ -173,6 +197,8 @@ function rotate(matrix: number[][]): void { } ``` +#### Rust + ```rust impl Solution { pub fn rotate(matrix: &mut Vec
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
@@ -41,8 +50,12 @@ ] + + ## 解法 + + ### 方法一:数组标记 我们分别用数组 `rows` 和 `cols` 标记待清零的行和列。 @@ -53,6 +66,8 @@ +#### Python3 + ```python class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: @@ -69,6 +84,8 @@ class Solution: matrix[i][j] = 0 ``` +#### Java + ```java class Solution { public void setZeroes(int[][] matrix) { @@ -94,6 +111,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -120,6 +139,8 @@ public: }; ``` +#### Go + ```go func setZeroes(matrix [][]int) { m, n := len(matrix), len(matrix[0]) @@ -143,6 +164,8 @@ func setZeroes(matrix [][]int) { } ``` +#### TypeScript + ```ts /** Do not return anything, modify matrix in-place instead. @@ -170,6 +193,8 @@ function setZeroes(matrix: number[][]): void { } ``` +#### Rust + ```rust impl Solution { pub fn set_zeroes(matrix: &mut Vec
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
@@ -68,8 +78,12 @@ + + ## Solutions + + ### Solution 1: Array Marking We use arrays `rows` and `cols` to mark the rows and columns to be zeroed. @@ -80,6 +94,8 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m + n)$. +#### Python3 + ```python class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: @@ -96,6 +112,8 @@ class Solution: matrix[i][j] = 0 ``` +#### Java + ```java class Solution { public void setZeroes(int[][] matrix) { @@ -121,6 +139,8 @@ class Solution { } ``` +#### C++ + ```cpp class Solution { public: @@ -147,6 +167,8 @@ public: }; ``` +#### Go + ```go func setZeroes(matrix [][]int) { m, n := len(matrix), len(matrix[0]) @@ -170,6 +192,8 @@ func setZeroes(matrix [][]int) { } ``` +#### TypeScript + ```ts /** Do not return anything, modify matrix in-place instead. @@ -197,6 +221,8 @@ function setZeroes(matrix: number[][]): void { } ``` +#### Rust + ```rust impl Solution { pub fn set_zeroes(matrix: &mut Vec
字符串轮转。给定两个字符串s1
和s2
,请编写代码检查s2
是否为s1
旋转而成(比如,waterbottle
是erbottlewat
旋转后的字符串)。
示例1:
@@ -34,8 +43,12 @@Given two strings, s1
and s2
, write code to check if s2
is a rotation of s1
(e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another?
Example 1:
@@ -34,8 +44,12 @@0 <= s1.length, s1.length <= 100000
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
@@ -32,8 +41,12 @@如果不得使用临时缓冲区,该怎么解决?
+ + ## 解法 + + ### 方法一:哈希表 我们创建一个哈希表 $vis$,用于记录已经访问过的节点的值。 @@ -48,6 +61,8 @@ +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -69,6 +84,8 @@ class Solution: return head ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -94,6 +111,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -121,6 +140,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -144,6 +165,8 @@ func removeDuplicateNodes(head *ListNode) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -172,6 +195,8 @@ function removeDuplicateNodes(head: ListNode | null): ListNode | null { } ``` +#### Rust + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -211,6 +236,8 @@ impl Solution { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -238,6 +265,8 @@ var removeDuplicateNodes = function (head) { }; ``` +#### Swift + ```swift /** * Definition for singly-linked list. @@ -272,4 +301,6 @@ class Solution { - + + + diff --git a/lcci/02.01.Remove Duplicate Node/README_EN.md b/lcci/02.01.Remove Duplicate Node/README_EN.md index 1dbf94c8f0c2f..d155fd3e4e551 100644 --- a/lcci/02.01.Remove Duplicate Node/README_EN.md +++ b/lcci/02.01.Remove Duplicate Node/README_EN.md @@ -1,9 +1,19 @@ +--- +comments: true +difficulty: Easy +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.01.Remove%20Duplicate%20Node/README_EN.md +--- + + + # [02.01. Remove Duplicate Node](https://leetcode.cn/problems/remove-duplicate-node-lcci) [中文文档](/lcci/02.01.Remove%20Duplicate%20Node/README.md) ## Description + +Write code to remove duplicates from an unsorted linked list.
Example1:
@@ -37,8 +47,12 @@How would you solve this problem if a temporary buffer is not allowed?
+ + ## Solutions + + ### Solution 1: Hash Table We create a hash table $vis$ to record the values of the nodes that have been visited. @@ -53,6 +67,8 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -74,6 +90,8 @@ class Solution: return head ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -99,6 +117,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -126,6 +146,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -149,6 +171,8 @@ func removeDuplicateNodes(head *ListNode) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -177,6 +201,8 @@ function removeDuplicateNodes(head: ListNode | null): ListNode | null { } ``` +#### Rust + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -216,6 +242,8 @@ impl Solution { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -243,6 +271,8 @@ var removeDuplicateNodes = function (head) { }; ``` +#### Swift + ```swift /** * Definition for singly-linked list. @@ -277,4 +307,6 @@ class Solution { - + + + diff --git a/lcci/02.02.Kth Node From End of List/README.md b/lcci/02.02.Kth Node From End of List/README.md index 8b013264d05a0..3d10483e2a0e6 100644 --- a/lcci/02.02.Kth Node From End of List/README.md +++ b/lcci/02.02.Kth Node From End of List/README.md @@ -1,10 +1,19 @@ +--- +comments: true +difficulty: 简单 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.02.Kth%20Node%20From%20End%20of%20List/README.md +--- + + + # [面试题 02.02. 返回倒数第 k 个节点](https://leetcode.cn/problems/kth-node-from-end-of-list-lcci) [English Version](/lcci/02.02.Kth%20Node%20From%20End%20of%20List/README_EN.md) ## 题目描述 - + +实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
注意:本题相对原题稍作改动
@@ -18,8 +27,12 @@给定的 k 保证是有效的。
+ + ## 解法 + + ### 方法一:快慢指针 我们定义两个指针 `slow` 和 `fast`,初始时都指向链表头节点 `head`。然后 `fast` 指针先向前移动 $k$ 步,然后 `slow` 和 `fast` 指针同时向前移动,直到 `fast` 指针指向链表末尾。此时 `slow` 指针指向的节点就是倒数第 $k$ 个节点。 @@ -28,6 +41,8 @@ +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -47,6 +62,8 @@ class Solution: return slow.val ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -71,6 +88,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -97,6 +116,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -118,6 +139,8 @@ func kthToLast(head *ListNode, k int) int { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -144,6 +167,8 @@ function kthToLast(head: ListNode | null, k: number): number { } ``` +#### Rust + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -177,6 +202,8 @@ impl Solution { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -203,6 +230,8 @@ var kthToLast = function (head, k) { }; ``` +#### Swift + ```swift /** * Definition for singly-linked list. @@ -239,4 +268,6 @@ class Solution { - + + + diff --git a/lcci/02.02.Kth Node From End of List/README_EN.md b/lcci/02.02.Kth Node From End of List/README_EN.md index 785b3fb5a598b..3ad666e90fc46 100644 --- a/lcci/02.02.Kth Node From End of List/README_EN.md +++ b/lcci/02.02.Kth Node From End of List/README_EN.md @@ -1,9 +1,19 @@ +--- +comments: true +difficulty: Easy +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.02.Kth%20Node%20From%20End%20of%20List/README_EN.md +--- + + + # [02.02. Kth Node From End of List](https://leetcode.cn/problems/kth-node-from-end-of-list-lcci) [中文文档](/lcci/02.02.Kth%20Node%20From%20End%20of%20List/README.md) ## Description + +Implement an algorithm to find the kth to last element of a singly linked list. Return the value of the element.
Note: This problem is slightly different from the original one in the book.
@@ -20,8 +30,12 @@k is always valid.
+ + ## Solutions + + ### Solution 1: Two Pointers We define two pointers `slow` and `fast`, both initially pointing to the head node `head`. Then the `fast` pointer moves forward $k$ steps first, and then the `slow` and `fast` pointers move forward together until the `fast` pointer points to the end of the list. At this point, the node pointed to by the `slow` pointer is the $k$-th node from the end of the list. @@ -30,6 +44,8 @@ The time complexity is $O(n)$, where $n$ is the length of the list. The space co +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -49,6 +65,8 @@ class Solution: return slow.val ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -73,6 +91,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -99,6 +119,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -120,6 +142,8 @@ func kthToLast(head *ListNode, k int) int { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -146,6 +170,8 @@ function kthToLast(head: ListNode | null, k: number): number { } ``` +#### Rust + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -179,6 +205,8 @@ impl Solution { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -205,6 +233,8 @@ var kthToLast = function (head, k) { }; ``` +#### Swift + ```swift /** * Definition for singly-linked list. @@ -241,4 +271,6 @@ class Solution { - + + + diff --git a/lcci/02.03.Delete Middle Node/README.md b/lcci/02.03.Delete Middle Node/README.md index 2f5ec297274aa..f364e78673c15 100644 --- a/lcci/02.03.Delete Middle Node/README.md +++ b/lcci/02.03.Delete Middle Node/README.md @@ -1,10 +1,18 @@ +--- +comments: true +difficulty: 简单 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.03.Delete%20Middle%20Node/README.md +--- + + + # [面试题 02.03. 删除中间节点](https://leetcode.cn/problems/delete-middle-node-lcci) [English Version](/lcci/02.03.Delete%20Middle%20Node/README_EN.md) ## 题目描述 - +若链表中的某个节点,既不是链表头节点,也不是链表尾节点,则称其为该链表的「中间节点」。
@@ -23,8 +31,12 @@+ + ## 解法 + + ### 方法一:节点赋值 我们可以将当前节点的值替换为下一个节点的值,然后删除下一个节点。这样就可以达到删除当前节点的目的。 @@ -33,6 +45,8 @@ +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -47,6 +61,8 @@ class Solution: node.next = node.next.next ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -64,6 +80,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -82,6 +100,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -96,6 +116,8 @@ func deleteNode(node *ListNode) { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -114,6 +136,8 @@ var deleteNode = function (node) { }; ``` +#### Swift + ```swift /** * public class ListNode { @@ -136,4 +160,6 @@ class Solution { - + + + diff --git a/lcci/02.03.Delete Middle Node/README_EN.md b/lcci/02.03.Delete Middle Node/README_EN.md index d66096e43aaae..20edd71820a18 100644 --- a/lcci/02.03.Delete Middle Node/README_EN.md +++ b/lcci/02.03.Delete Middle Node/README_EN.md @@ -1,9 +1,19 @@ +--- +comments: true +difficulty: Easy +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.03.Delete%20Middle%20Node/README_EN.md +--- + + + # [02.03. Delete Middle Node](https://leetcode.cn/problems/delete-middle-node-lcci) [中文文档](/lcci/02.03.Delete%20Middle%20Node/README.md) ## Description + +
Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
@@ -18,8 +28,12 @@ + + ## Solutions + + ### Solution 1: Node Assignment We can replace the value of the current node with the value of the next node, and then delete the next node. This way, we can achieve the purpose of deleting the current node. @@ -28,6 +42,8 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -42,6 +58,8 @@ class Solution: node.next = node.next.next ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -59,6 +77,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -77,6 +97,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -91,6 +113,8 @@ func deleteNode(node *ListNode) { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -109,6 +133,8 @@ var deleteNode = function (node) { }; ``` +#### Swift + ```swift /** * public class ListNode { @@ -131,4 +157,6 @@ class Solution { - + + + diff --git a/lcci/02.04.Partition List/README.md b/lcci/02.04.Partition List/README.md index a0094f6180ce9..0295f353a03a7 100644 --- a/lcci/02.04.Partition List/README.md +++ b/lcci/02.04.Partition List/README.md @@ -1,10 +1,18 @@ +--- +comments: true +difficulty: 中等 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.04.Partition%20List/README.md +--- + + + # [面试题 02.04. 分割链表](https://leetcode.cn/problems/partition-list-lcci) [English Version](/lcci/02.04.Partition%20List/README_EN.md) ## 题目描述 - +
给你一个链表的头节点 head
和一个特定值 x
,请你对链表进行分隔,使得所有 小于 x
的节点都出现在 大于或等于 x
的节点之前。
-200 <= x <= 200
Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.
Example:
@@ -16,8 +26,12 @@ + + ## Solutions + + ### Solution 1: Concatenating Lists We create two lists, `left` and `right`, to store nodes that are less than `x` and nodes that are greater than or equal to `x`, respectively. @@ -34,6 +48,8 @@ The time complexity is $O(n)$, where $n$ is the length of the list. The space co +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -59,6 +75,8 @@ class Solution: return left.next ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -90,6 +108,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -122,6 +142,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -148,6 +170,8 @@ func partition(head *ListNode, x int) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -179,6 +203,8 @@ function partition(head: ListNode | null, x: number): ListNode | null { } ``` +#### Swift + ```swift /** public class ListNode { * var val: Int @@ -219,4 +245,6 @@ class Solution { - + + + diff --git a/lcci/02.05.Sum Lists/README.md b/lcci/02.05.Sum Lists/README.md index 703ddc5ef7975..27b004db13c68 100644 --- a/lcci/02.05.Sum Lists/README.md +++ b/lcci/02.05.Sum Lists/README.md @@ -1,10 +1,19 @@ +--- +comments: true +difficulty: 中等 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.05.Sum%20Lists/README.md +--- + + + # [面试题 02.05. 链表求和](https://leetcode.cn/problems/sum-lists-lcci) [English Version](/lcci/02.05.Sum%20Lists/README_EN.md) ## 题目描述 - + +给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
@@ -27,8 +36,12 @@ 输出:9 -> 1 -> 2,即912 + + ## 解法 + + ### 方法一:模拟 我们同时遍历两个链表 $l_1$ 和 $l_2$,并使用变量 $carry$ 表示当前是否有进位。 @@ -41,6 +54,8 @@ +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -63,6 +78,8 @@ class Solution: return dummy.next ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -90,6 +107,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -118,6 +137,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -147,6 +168,8 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -191,11 +214,13 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` +#### Rust + ```rust impl Solution { pub fn add_two_numbers( mut l1: OptionYou have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
@@ -30,8 +40,12 @@ + + ## Solutions + + ### Solution 1: Simulation We traverse two linked lists $l_1$ and $l_2$ simultaneously, and use a variable $carry$ to indicate whether there is a carry-over currently. @@ -44,6 +58,8 @@ The time complexity is $O(\max(m, n))$, where $m$ and $n$ are the lengths of the +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -66,6 +82,8 @@ class Solution: return dummy.next ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -93,6 +111,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -121,6 +141,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -150,6 +172,8 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -194,11 +218,13 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` +#### Rust + ```rust impl Solution { pub fn add_two_numbers( mut l1: Option
编写一个函数,检查输入的链表是否是回文的。
@@ -26,8 +35,12 @@
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
Implement a function to check if a linked list is a palindrome.
@@ -34,8 +44,12 @@ Could you do it in O(n) time and O(1) space? + + ## Solutions + + ### Solution 1: Fast and Slow Pointers + Reverse List First, we check if the list is empty. If it is, we return `true` directly. @@ -50,6 +64,8 @@ The time complexity is $O(n)$, where $n$ is the length of the list. The space co +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -81,6 +97,8 @@ class Solution: return True ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -123,6 +141,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -166,6 +186,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -203,6 +225,8 @@ func isPalindrome(head *ListNode) bool { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -247,6 +271,8 @@ function isPalindrome(head: ListNode | null): boolean { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -290,6 +316,8 @@ var isPalindrome = function (head) { }; ``` +#### C# + ```cs /** * Definition for singly-linked list. @@ -332,6 +360,8 @@ public class Solution { } ``` +#### Swift + ```swift /** * public class ListNode { @@ -385,4 +415,6 @@ class Solution { - + + + diff --git a/lcci/02.07.Intersection of Two Linked Lists/README.md b/lcci/02.07.Intersection of Two Linked Lists/README.md index 677f0cd932bf1..b6643ffd26e08 100644 --- a/lcci/02.07.Intersection of Two Linked Lists/README.md +++ b/lcci/02.07.Intersection of Two Linked Lists/README.md @@ -1,14 +1,27 @@ +--- +comments: true +difficulty: 简单 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.07.Intersection%20of%20Two%20Linked%20Lists/README.md +--- + + + # [面试题 02.07. 链表相交](https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci) [English Version](/lcci/02.07.Intersection%20of%20Two%20Linked%20Lists/README_EN.md) ## 题目描述 - + +
给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
示例 2:
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
示例 3:
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。
注意:
null
。Given two (singly) linked lists, determine if the two lists intersect. Return the inter secting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.
Example 1:
@@ -45,8 +55,12 @@ - You may assume there are no cycles anywhere in the entire linked structure. - Your code should preferably run in O(n) time and use only O(1) memory. + + ## Solutions + + ### Solution 1: Two Pointers We use two pointers $a$ and $b$ to point to two linked lists $headA$ and $headB$ respectively. @@ -59,6 +73,8 @@ The time complexity is $O(m+n)$, where $m$ and $n$ are the lengths of the linked +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -76,6 +92,8 @@ class Solution: return a ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -100,6 +118,8 @@ public class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -122,6 +142,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -148,6 +170,8 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -172,6 +196,8 @@ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): Li } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -197,6 +223,8 @@ var getIntersectionNode = function (headA, headB) { }; ``` +#### Swift + ```swift /** * Definition for singly-linked list. @@ -225,4 +253,6 @@ class Solution { - + + + diff --git a/lcci/02.08.Linked List Cycle/README.md b/lcci/02.08.Linked List Cycle/README.md index 4bdacbd682de3..facce4bf87406 100644 --- a/lcci/02.08.Linked List Cycle/README.md +++ b/lcci/02.08.Linked List Cycle/README.md @@ -1,15 +1,27 @@ +--- +comments: true +difficulty: 中等 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/02.08.Linked%20List%20Cycle/README.md +--- + + + # [面试题 02.08. 环路检测](https://leetcode.cn/problems/linked-list-cycle-lcci) [English Version](/lcci/02.08.Linked%20List%20Cycle/README_EN.md) ## 题目描述 - +给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的next元素指向在它前面出现过的节点,则表明该链表存在环路。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
进阶:
你是否可以不用额外空间解决此题?
Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop.
Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list.
@@ -36,8 +46,12 @@ Can you solve it without using additional space? + + ## Solutions + + ### Solution 1: Two Pointers We first use the fast and slow pointers to judge whether the linked list has a ring. If there is a ring, the fast and slow pointers will definitely meet, and the meeting node must be in the ring. @@ -60,6 +74,8 @@ The time complexity is $O(n)$, where $n$ is the number of nodes in the linked li +#### Python3 + ```python # Definition for singly-linked list. # class ListNode: @@ -82,6 +98,8 @@ class Solution: return ans ``` +#### Java + ```java /** * Definition for singly-linked list. @@ -114,6 +132,8 @@ public class Solution { } ``` +#### C++ + ```cpp /** * Definition for singly-linked list. @@ -145,6 +165,8 @@ public: }; ``` +#### Go + ```go /** * Definition for singly-linked list. @@ -171,6 +193,8 @@ func detectCycle(head *ListNode) *ListNode { } ``` +#### TypeScript + ```ts /** * Definition for singly-linked list. @@ -202,6 +226,8 @@ function detectCycle(head: ListNode | null): ListNode | null { } ``` +#### JavaScript + ```js /** * Definition for singly-linked list. @@ -233,6 +259,8 @@ var detectCycle = function (head) { }; ``` +#### Swift + ```swift /* * public class ListNode { @@ -269,4 +297,6 @@ class Solution { - + + + diff --git a/lcci/03.01.Three in One/README.md b/lcci/03.01.Three in One/README.md index 4c467e926ee85..3a2604f22caf0 100644 --- a/lcci/03.01.Three in One/README.md +++ b/lcci/03.01.Three in One/README.md @@ -1,10 +1,19 @@ +--- +comments: true +difficulty: 简单 +edit_url: https://github.com/doocs/leetcode/edit/main/lcci/03.01.Three%20in%20One/README.md +--- + + + # [面试题 03.01. 三合一](https://leetcode.cn/problems/three-in-one-lcci) [English Version](/lcci/03.01.Three%20in%20One/README_EN.md) ## 题目描述 - + +三合一。描述如何只用一个数组来实现三个栈。
你应该实现push(stackNum, value)
、pop(stackNum)
、isEmpty(stackNum)
、peek(stackNum)
方法。stackNum
表示栈下标,value
表示压入的值。
Describe how you could use a single array to implement three stacks.
Yout should implement push(stackNum, value)
、pop(stackNum)
、isEmpty(stackNum)
、peek(stackNum)
methods. stackNum
is the index of the stack. value
is the value that pushed to the stack.
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();+ + ## 解法 + + ### 方法一:双栈 我们用两个栈来实现,其中`stk1` 用来存储数据,`stk2` 用来存储当前栈中的最小值。初始时,`stk2` 中存储一个极大值。 @@ -22,6 +35,8 @@ +#### Python3 + ```python class MinStack: def __init__(self): @@ -54,6 +69,8 @@ class MinStack: # param_4 = obj.getMin() ``` +#### Java + ```java class MinStack { private Deque
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
Example:
@@ -26,8 +36,12 @@ minStack.top(); --> return 0. minStack.getMin(); --> return -2. + + ## Solutions + + ### Solution 1: Double Stack We use two stacks to implement this, where `stk1` is used to store data, and `stk2` is used to store the current minimum value in the stack. Initially, `stk2` stores a very large value. @@ -41,6 +55,8 @@ For each operation, the time complexity is $O(1)$, and the space complexity is $ +#### Python3 + ```python class MinStack: def __init__(self): @@ -73,6 +89,8 @@ class MinStack: # param_4 = obj.getMin() ``` +#### Java + ```java class MinStack { private Deque堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks
,模拟这种行为。SetOfStacks
应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()
和SetOfStacks.pop()
应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。 进阶:实现一个popAt(int index)
方法,根据指定的子栈,执行pop操作。
当某个栈为空时,应当删除该栈。当栈中没有元素或不存在该栈时,pop
,popAt
应返回 -1.
示例1:
@@ -22,8 +31,12 @@ [null, null, null, null, 2, 1, 3] + + ## 解法 + + ### 方法一:模拟 我们可以使用一个栈列表 $stk$ 来模拟这个过程,初始时 $stk$ 为空。 @@ -36,6 +49,8 @@ +#### Python3 + ```python class StackOfPlates: def __init__(self, cap: int): @@ -68,6 +83,8 @@ class StackOfPlates: # param_3 = obj.popAt(index) ``` +#### Java + ```java class StackOfPlates { private ListImagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks
that mimics this. SetOfStacks
should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push()
and SetOfStacks.pop()
should behave identically to a single stack (that is, pop()
should return the same values as it would if there were just a single stack). Follow Up: Implement a function popAt(int index)
which performs a pop operation on a specific sub-stack.
You should delete the sub-stack when it becomes empty. pop
, popAt
should return -1 when there's no element to pop.
Example1:
@@ -37,8 +47,12 @@ + + ## Solutions + + ### Solution 1: Simulation We can use a list of stacks $stk$ to simulate this process, initially $stk$ is empty. @@ -51,6 +65,8 @@ The space complexity is $O(n)$, where $n$ is the number of elements. +#### Python3 + ```python class StackOfPlates: def __init__(self, cap: int): @@ -83,6 +99,8 @@ class StackOfPlates: # param_3 = obj.popAt(index) ``` +#### Java + ```java class StackOfPlates { private List实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
push to top
, peek/pop from top
, size
和 is empty
操作是合法的。Implement a MyQueue class which implements a queue using two stacks.
@@ -38,8 +48,12 @@ queue.empty(); // return false+ + ## Solutions + + ### Solution 1: Double Stack We use two stacks, where `stk1` is used for enqueue, and another stack `stk2` is used for dequeue. @@ -54,6 +68,8 @@ When checking whether the queue is empty, we only need to check whether both sta +#### Python3 + ```python class MyQueue: def __init__(self): @@ -88,6 +104,8 @@ class MyQueue: # param_4 = obj.empty() ``` +#### Java + ```java class MyQueue { private Deque
栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push
、pop
、peek
和 isEmpty
。当栈为空时,peek
返回 -1。
示例1:
@@ -31,8 +40,12 @@Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push
, pop
, peek
, and isEmpty
. When the stack is empty, peek
should return -1.
Example1:
@@ -44,8 +54,12 @@动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人只能收养所有动物中“最老”(由其进入收容所的时间长短而定)的动物,或者可以挑选猫或狗(同时必须收养此类动物中“最老”的)。换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,比如enqueue
、dequeueAny
、dequeueDog
和dequeueCat
。允许使用Java内置的LinkedList数据结构。
enqueue
方法有一个animal
参数,animal[0]
代表动物编号,animal[1]
代表动物种类,其中 0 代表猫,1 代表狗。
An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first out" basis. People must adopt either the"oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue
, dequeueAny
, dequeueDog
, and dequeueCat
. You may use the built-in Linked list data structure.
enqueue
method has a animal
parameter, animal[0]
represents the number of the animal, animal[1]
represents the type of the animal, 0 for cat and 1 for dog.
节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
示例1:
@@ -27,8 +36,12 @@Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
Example1:
@@ -34,8 +44,12 @@给定一个有序整数数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉搜索树。
示例:给定有序数组: [-10,-3,0,5,9],+ + ## 解法 + + ### 方法一:递归 -我们设计一个函数 $\text{dfs}(l, r)$,表示构造出从 $l$ 到 $r$ 的子树,那么答案就是 $\text{dfs}(0, \text{len}(nums) - 1)$。 +我们设计一个函数 $\textit{dfs}(l, r)$,表示构造出从 $l$ 到 $r$ 的子树,那么答案就是 $\textit{dfs}(0, \textit{len}(nums) - 1)$。 -函数 $\text{dfs}(l, r)$ 的执行过程如下: +函数 $\textit{dfs}(l, r)$ 的执行过程如下: -1. 如果 $l > r$,返回 $\text{None}$。 -2. 否则,我们计算出中间位置 $mid = \frac{l + r}{2}$,然后构造出根节点,左子树为 $\text{dfs}(l, mid - 1)$,右子树为 $\text{dfs}(mid + 1, r)$。 +1. 如果 $l > r$,返回 $\textit{None}$。 +2. 否则,我们计算出中间位置 $mid = \frac{l + r}{2}$,然后构造出根节点,左子树为 $\textit{dfs}(l, mid - 1)$,右子树为 $\textit{dfs}(mid + 1, r)$。 3. 最后返回根节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 +#### Python3 + ```python # Definition for a binary tree node. # class TreeNode: @@ -43,6 +58,8 @@ class Solution: return dfs(0, len(nums) - 1) ``` +#### Java + ```java /** * Definition for a binary tree node. @@ -71,6 +88,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for a binary tree node. @@ -84,7 +103,7 @@ class Solution { class Solution { public: TreeNode* sortedArrayToBST(vector
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
Example:
@@ -14,24 +24,28 @@ Given sorted array: [-10,-3,0,5,9], -One possible answer is: [0,-3,9,-10,null,5],which represents the following tree: +One possible answer is: [0,-3,9,-10,null,5],which represents the following tree: - 0 + 0 - / \ + / \ - -3 9 + -3 9 - / / + / / - -10 5 + -10 5 + + ## Solutions + + ### Solution 1: Recursion We design a function `dfs(l, r)`, which constructs a subtree from `l` to `r`. Therefore, the answer is `dfs(0, len(nums) - 1)`. @@ -46,6 +60,8 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is +#### Python3 + ```python # Definition for a binary tree node. # class TreeNode: @@ -66,6 +82,8 @@ class Solution: return dfs(0, len(nums) - 1) ``` +#### Java + ```java /** * Definition for a binary tree node. @@ -94,6 +112,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for a binary tree node. @@ -107,7 +127,7 @@ class Solution { class Solution { public: TreeNode* sortedArrayToBST(vector给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D
,则会创建出 D
个链表)。返回一个包含所有深度的链表的数组。
@@ -24,8 +33,12 @@ 输出:[[1],[2,3],[4,5,7],[8]] + + ## 解法 + + ### 方法一:BFS 层序遍历 我们可以使用 BFS 层序遍历的方法,每次遍历一层,将当前层的节点值存入链表中,然后将链表加入到结果数组中。 @@ -34,6 +47,8 @@ +#### Python3 + ```python # Definition for a binary tree node. # class TreeNode: @@ -67,6 +82,8 @@ class Solution: return ans ``` +#### Java + ```java /** * Definition for a binary tree node. @@ -111,6 +128,8 @@ class Solution { } ``` +#### C++ + ```cpp /** * Definition for a binary tree node. @@ -156,6 +175,8 @@ public: }; ``` +#### Go + ```go /** * Definition for a binary tree node. @@ -195,6 +216,8 @@ func listOfDepth(tree *TreeNode) (ans []*ListNode) { } ``` +#### TypeScript + ```ts /** * Definition for a binary tree node. @@ -241,6 +264,8 @@ function listOfDepth(tree: TreeNode | null): Array