162 Commits

Author SHA1 Message Date
YDZ
8796fe779f Add solution 1603、1608、1700、1710、1716、1720、1725、1732、1736、1742、1748、1752、1758 2021-02-15 13:20:24 +08:00
YDZ
9de9488b04 Fix gitalk issue 2021-02-15 11:49:32 +08:00
YDZ
14d0942f5a 1. Add solution 1091、1614、1619、1624、1629、1636、1704
2. ctl strings.TrimSpace question.Title
2021-02-15 11:37:57 +08:00
YDZ
af41c91d60 Add solution 1631、1691 2021-02-13 23:00:46 +08:00
YDZ
c7862ae2bd Add solution 0665、0669、1423、1463、1579 2021-02-13 19:09:06 +08:00
YDZ
5e1c45cb84 Add solution 0031、0987、1675 2021-02-13 03:18:06 +08:00
YDZ
0881edff66 Add solution 0119、1439 2021-02-12 12:43:08 +08:00
YDZ
048c42db23 Add solution 0284、0703 2021-02-11 21:12:13 +08:00
YDZ
3c1ad916e7 Add solution 0538、1038 2021-02-11 03:53:43 +08:00
YDZ
3bd8dd1732 Add solution 0821 2021-02-07 21:04:15 +08:00
YDZ
8d2a3414c1 Add solution 0643 2021-02-07 17:32:15 +08:00
10307418dc Merge pull request #98 from halfrost/collapsed_menu
[Breaking Change] Collapsed menu #55
2021-02-07 16:53:00 +08:00
YDZ
8bef91a948 Update ctl 2021-02-07 15:31:35 +08:00
YDZ
2110901fa0 update theme 2021-02-07 15:22:25 +08:00
YDZ
aec4ce1248 change file path 2021-02-07 15:22:24 +08:00
YDZ
2a242af5a8 Add CLRUCache 2021-02-07 02:31:21 +08:00
YDZ
3665fc17fb Update 509 2021-02-03 16:22:37 +08:00
YDZ
7887621c9b Update note 2021-01-30 13:28:21 +08:00
a5924fcba2 Merge pull request #96 from yangzuwei/master
Update 15. 3Sum.go
2021-01-30 12:35:47 +08:00
yzw
ebbb7354d6 Update 15. 3Sum.go
unnecessary
2021-01-29 16:56:08 +08:00
YDZ
bcf217f7be Update solution 1663 2021-01-29 00:25:44 +08:00
YDZ
096da771dc Add solution 1437 2021-01-25 21:59:43 +08:00
a6ffd5258a Merge pull request #85 from frankegoesdown/1436-Cherry-Pickup-II
1436 cherry pickup ii
2021-01-25 16:49:47 +08:00
YDZ
ebebf5c1a8 Modify solution 220 2021-01-25 16:24:12 +08:00
e172b5e98d Merge pull request #94 from dotcom900825/bugfix/minor-typo-fix-on-p567
Minor typo fix on problem description for p567
2021-01-25 12:00:19 +08:00
aeda134392 minor typo fix 2021-01-24 15:36:35 -08:00
YDZ
8747599780 Add solution 674 2021-01-24 23:46:18 +08:00
YDZ
4c34ef0a82 Add solution 1329 2021-01-24 23:08:20 +08:00
YDZ
a16766e01a Update Backtracking.md 2021-01-23 18:39:00 +08:00
d9e9218445 Merge pull request #92 from lhfelis/patch-1
Fix N-Queens solution time complexity
2021-01-23 18:27:22 +08:00
de52e10486 Fix N-Queens solution time complexity 2021-01-23 17:54:24 +08:00
YDZ
d46930712e Add solution 1319 2021-01-23 16:44:23 +08:00
YDZ
228bde3678 Add solution 989 2021-01-22 13:38:37 +08:00
YDZ
952be29e39 Add solution 138 README 2021-01-21 18:13:45 +08:00
YDZ
9e037c66b4 Merge branch 'master' of github.com:halfrost/LeetCode-Go 2021-01-21 15:53:34 +08:00
YDZ
823d42ef9b Fix solution 628 2021-01-21 15:53:19 +08:00
00a1c77c65 Merge pull request #91 from sivanWu0222/leetcode-138
增加LeetCode-138双百题解
2021-01-20 18:23:28 +08:00
c9ff2bc617 Merge branch 'master' into leetcode-138 2021-01-20 18:22:21 +08:00
73764b7bcd 增加LeetCode-138双百题解 2021-01-20 08:20:39 +08:00
YDZ
bfb9839828 Use Katex in solution markdown 2021-01-20 01:26:01 +08:00
YDZ
0ae1bb2655 Add solution 1696 & ctl add build menu 2021-01-19 23:56:48 +08:00
YDZ
ff570474b3 Add solution 1203 2021-01-18 18:13:30 +08:00
YDZ
c90926c899 Add solution 1641 2021-01-18 11:06:37 +08:00
YDZ
05f56189f1 Ctl add generate PDF 2021-01-17 14:48:47 +08:00
YDZ
9354e61414 chapter four add pre-next 2021-01-17 02:31:22 +08:00
YDZ
e1a090b451 Add pre-next 2021-01-17 02:23:56 +08:00
YDZ
1a51946f5d render chapter two 2021-01-16 01:33:27 +08:00
YDZ
4614f589ec Micro fix 2021-01-16 00:18:39 +08:00
YDZ
a2ceb138bb render chapter two 2021-01-15 23:05:13 +08:00
YDZ
5b58e62176 Ctl add build chapter-two 2021-01-15 22:32:12 +08:00
YDZ
e3ba2d3153 Add solution 1018 2021-01-14 01:25:19 +08:00
YDZ
4067a7858d Add person data statistic 2021-01-13 00:09:12 +08:00
YDZ
fbbc4ff73a Add solution 228、1694、1695 2021-01-12 11:04:25 +08:00
YDZ
1bc9d34209 Add solution 189 2021-01-08 02:44:27 +08:00
YDZ
c700a335cc rengder README.md from template.markdown 2021-01-08 00:47:11 +08:00
YDZ
b7cc898a6a Add robot 2021-01-07 19:31:47 +08:00
YDZ
fd9d3fd9e1 Add solution 1539 2021-01-06 20:11:25 +08:00
YDZ
88f0a1d9e1 Add wechat-qr-code 2021-01-05 14:50:29 +08:00
YDZ
71b030cf63 Add solution 830 2021-01-05 12:11:15 +08:00
YDZ
0735a68bc9 ChapterThree Add LFUCache/LRUCache 2021-01-04 00:28:07 +08:00
YDZ
7bc6c9d9a0 Add solution 146、460 2021-01-04 00:13:00 +08:00
YDZ
38aa0acb0d Add LFU/LRU template 2021-01-03 23:48:14 +08:00
YDZ
fb72c855ee Modify solution 0164 2021-01-02 01:14:29 +08:00
YDZ
3e2d511c6b Optimization solution 0015 2021-01-02 01:04:43 +08:00
YDZ
bbb448d3be Add solution 1640 2021-01-02 00:53:28 +08:00
YDZ
88a0452f26 Add solution 605 2021-01-02 00:44:50 +08:00
YDZ
0392f638ae Merge branch 'master' of github.com:halfrost/LeetCode-Go 2021-01-02 00:40:39 +08:00
YDZ
5cb2ded45c Add 5629 2021-01-02 00:34:11 +08:00
YDZ
b9c64a1057 Add 5629 2020-12-30 23:15:10 +08:00
354c802c22 Merge pull request #84 from frankegoesdown/0910-smallest-range-ii
add 0910 smallest-range-ii
2020-12-25 15:19:01 +08:00
c117dfdc24 Merge pull request #86 from kingeasternsun/patch-1
Update 0387.First-Unique-Character-in-a-String.md
2020-12-25 00:03:49 +08:00
2c41ea320f Update 0387.First-Unique-Character-in-a-String.md 2020-12-23 12:53:01 +08:00
fcd2655a4a edit mainFunc name 2020-12-21 17:55:24 +03:00
e4a828a658 1436-Cherry-Pickup_II 2020-12-21 17:54:11 +03:00
c18739f262 add dummy-comments 2020-12-21 14:14:13 +03:00
65d2fd668b add 0910 smallest-range-ii 2020-12-21 13:58:49 +03:00
YDZ
e3fd0d2671 Add solution 1674、1690 2020-12-17 13:18:51 +08:00
YDZ
e85f3236f4 Add solution 1668、1669、1670、1672、1673 2020-12-16 15:50:19 +08:00
YDZ
2e796fe70e Add solution 1573、1684、1685、1688、1689 2020-12-15 21:22:19 +08:00
YDZ
75e5a7eeff Update 1680 test 2020-12-15 13:47:29 +08:00
YDZ
7c6a8bd33d Add Weekly Contest 218 2020-12-15 13:15:14 +08:00
YDZ
3881a5a214 Update solution 0148 2020-12-11 23:34:50 +08:00
YDZ
85dfc8b80c Add Weekly 218 2020-12-08 14:13:18 +08:00
YDZ
6eb4df3bff Fix 0077 suoloution 2020-12-05 22:47:48 +08:00
YDZ
7af661be97 Fix 5613 test 2020-12-02 12:28:33 +08:00
YDZ
adaf03bbc5 Add Weekly 216 2020-12-01 23:02:07 +08:00
YDZ
1d5b343e5b Add Biweekly 40 2020-12-01 23:00:32 +08:00
YDZ
efbd8e4156 Add Biweekly 40 2020-12-01 22:58:16 +08:00
YDZ
9ac3fdeb96 Add solution 1654、1655 2020-11-28 15:24:45 +08:00
YDZ
0c4b373319 Add solution 1652、1653 2020-11-28 14:37:19 +08:00
YDZ
5770d110d0 Update 0027 solution 2020-11-25 00:52:55 +08:00
YDZ
4384f0d468 Update 0978 solution 2020-11-25 00:46:59 +08:00
YDZ
37fde650a5 Add solution 1662、1663、1664、1665 2020-11-23 22:17:33 +08:00
YDZ
285f7a1c75 Add solution 1656、1657、1658、1659 2020-11-22 19:46:48 +08:00
YDZ
35c39173bc Add solution 1656、1657 2020-11-20 23:35:30 +08:00
YDZ
91e1a92cdd Add Biweekly 39 / weekly 215 solutions 2020-11-15 22:39:49 +08:00
YDZ
7d7007c6e3 Fix PWA Lighthouse issue 2020-11-15 13:28:46 +08:00
YDZ
9b3b574760 Update 0633 README.md 2020-11-14 16:29:19 +08:00
3420cdbe85 Merge pull request #79 from zbq2019/patch-1
Update README.md
2020-11-14 16:19:11 +08:00
YDZ
dd72560ce2 Fix head link 2020-11-14 15:49:46 +08:00
595d4cd678 Update README.md
修正区间范围
2020-11-13 23:02:29 +08:00
YDZ
8401264952 Update EN Desc 2020-11-13 16:54:22 +08:00
YDZ
ea38a91202 Add weekly-contest-214 solution 2020-11-10 08:34:52 +08:00
YDZ
f3888ff449 Add weekly-contest-214 2020-11-08 11:59:51 +08:00
YDZ
6d2472da5f micro fix 2020-10-18 15:38:31 +08:00
8b6dd34148 Merge pull request #76 from halfrost/add_solution_0785
Add solution 0785
2020-10-06 13:27:14 +08:00
YDZ
7ccb69a920 Add solution 0785 2020-10-06 13:26:32 +08:00
5f4219ca84 Merge pull request #74 from born69confused/patch-1
785.Is Graph Bipartite?
2020-10-06 11:08:05 +08:00
YDZ
f88b33b047 Update README 2020-10-06 10:53:15 +08:00
26a8308c72 Merge pull request #75 from tejasdobariya7/patch-1
Update README.md
2020-10-06 10:50:33 +08:00
59380b26ed Update README.md 2020-10-05 22:54:53 +05:30
e85635e6f9 785.Is Graph Bipartite?
Adding a new solution,
Leetcode Q.785 solution in Go lang using Depth First Search,
faster than 100 % ( 20ms ) with a memory usage of 12 MB.
2020-10-04 15:38:27 +05:30
YDZ
e6a965f767 Refresh goreportcard 2020-10-03 01:31:59 +08:00
YDZ
c39c65dfce Hidden goreportcard 2020-10-02 02:18:31 +08:00
YDZ
aa8d1801de Display goreportcard 2020-10-01 09:46:23 +08:00
YDZ
80a641546a Fix goreportcard 2020-10-01 09:42:46 +08:00
YDZ
2af7be3791 Fix problem 82 gofmt 2020-10-01 09:27:18 +08:00
YDZ
deb2aa1dc1 Change problem 1079 image 2020-09-30 14:22:17 +08:00
YDZ
3e7996d371 Fix go report card 2020-09-30 10:47:46 +08:00
c1f421273b Merge pull request #71 from harryleonardo/master
Add problem 1480 & 1512
2020-09-24 16:42:52 +08:00
44f8b5b8a6 [ADD] 1480 & 1512 2020-09-24 00:23:54 +07:00
YDZ
5830c8dbfc Badge add link 2020-09-21 00:37:45 +08:00
YDZ
e2a31f2a92 Add word count 2020-09-20 16:04:49 +08:00
YDZ
fb9da5f885 micro fix 2020-09-20 10:44:47 +08:00
adf980425c Merge pull request #70 from halfrost/fix_1300
Due to problem 1300 test case change, so solution should modify
2020-09-18 12:23:18 +08:00
YDZ
f56f6889bc Due to problem 1300 test case change, so solution should modify 2020-09-18 12:15:02 +08:00
3e301996c9 Merge pull request #69 from Janetyu/janetyu
leetcode82 提供更多的解法
2020-09-18 09:35:44 +08:00
8ab50ac930 leetcode82 提供更多的解法 2020-09-16 23:46:08 +08:00
YDZ
ec09c8d37b Problem 113 add solutions 2020-09-15 20:19:05 +08:00
f38c70a6c8 Merge pull request #68 from halfrost/add_qr_code
Add QR code
2020-09-10 17:14:54 +08:00
YDZ
2461c246fb Add QR code 2020-09-10 17:09:30 +08:00
b45568ba96 Merge pull request #67 from halfrost/fix_925
Due to problem 925 test case change, so solution should modify
2020-09-09 21:06:29 +08:00
YDZ
0e424f7105 Due to problem 925 test case change, so solution should modify 2020-09-09 20:51:49 +08:00
YDZ
e02e370d4e micro fix 2020-09-06 13:31:37 +08:00
YDZ
5fa44b9f6d remove go mod 2020-09-03 09:44:05 +08:00
b504737c19 Merge pull request #63 from lyricslee/bits
增加位运算
2020-09-03 09:25:55 +08:00
3158b6706d 增加位运算 2020-09-02 17:34:45 +08:00
2363839e94 Merge pull request #61 from xxgail/patch-1
Update 0017.Letter-Combinations-of-a-Phone-Number.md
2020-08-28 11:21:22 +08:00
04bcb27275 Merge branch 'master' into patch-1 2020-08-28 10:39:46 +08:00
46faa66642 Merge pull request #60 from halfrost/code_quality_improvement
optimization code quality level from A to A+
2020-08-27 17:41:27 +08:00
fa6c758004 Update 0017.Letter-Combinations-of-a-Phone-Number.md
Update 0017.Letter-Combinations-of-a-Phone-Number 参考回溯模板,增加回溯的解法(类似于DFS)
2020-08-27 15:37:41 +08:00
d2dfc2d634 Merge pull request #60 from halfrost/code_quality_improvement
optimization code quality level from A to A+
2020-08-27 13:21:57 +08:00
YDZ
96c36de45b optimization code level from A to A+ 2020-08-27 00:58:22 +08:00
7b7307761c Merge pull request #58 from halfrost/supplement_chapterone
完成第一章中少的 2 章节
2020-08-26 11:11:19 +08:00
YDZ
9531d78820 supplement ChapterOne 2020-08-26 03:13:48 +08:00
YDZ
db8c8979fd Problem0017 add solution two 2020-08-25 00:26:12 +08:00
YDZ
d7ed4c32cf Dark mode micro fix 2020-08-25 00:17:00 +08:00
YDZ
64be02e6b7 Update README 2020-08-24 12:03:09 +08:00
YDZ
30f483e769 HD image 2020-08-24 09:57:18 +08:00
YDZ
eb3c71bafa Delete public 2020-08-24 02:06:57 +08:00
3c9d679a53 Merge pull request #57 from halfrost/dark_theme
Add dark theme
2020-08-24 01:44:59 +08:00
YDZ
6f7e2e9582 Add dark theme 2020-08-24 01:35:54 +08:00
91c51977af Merge pull request #53 from kadefor/patch-1
精简代码
2020-08-23 08:25:01 +08:00
8075f0696f 精简代码 2020-08-23 00:00:42 +08:00
YDZ
5e6111e107 Add starchart 2020-08-22 08:19:39 +08:00
YDZ
e9dcc1e2fe Add PWA description 2020-08-21 04:22:17 +08:00
YDZ
bb1a101d38 fix iOS / Android PWA icon 2020-08-21 03:51:02 +08:00
YDZ
28e8d2a8e0 web add banner 2020-08-20 13:53:38 +08:00
YDZ
b64292975a Update README 2020-08-20 10:01:55 +08:00
bc7c289512 Merge pull request #52 from Janetyu/janetyu
finish 0724 solution
2020-08-20 08:06:38 +08:00
9df3022c4b Merge branch 'master' into janetyu 2020-08-19 23:18:52 +08:00
aa5ef0b9ac finish 724 solution 2020-08-19 23:12:50 +08:00
1813 changed files with 46133 additions and 9355 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.toml

14
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
"go.formatTool": "gofmt",
"go.formatFlags": [
"-s"
],
"go.autocompleteUnimportedPackages": true,
"[go]": {
"editor.insertSpaces": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}

3452
README.md Normal file → Executable file

File diff suppressed because it is too large Load Diff

1173
README_old.md Normal file

File diff suppressed because it is too large Load Diff

20
ctl/README.md Normal file
View File

@ -0,0 +1,20 @@
# LeetCode-Go ctl
## 配置方法
1.`.gitignore`中,添加一行`*.toml`
2.`LeetCode-Go`目录下,添加文本文件`config.toml`
3. 把以下内容复制到`config.toml`中。
4.`config.toml`中的`test`分别修改为你的 leetcode `用户名``密码`
5. 去 leetcode 登录后,把网站 cookie 复制 (需要复制 csrftoken 和 LEETCODE_SESSION) 并替换 `config.toml`中的`Cookie`
```toml
Username="test"
Password="test"
Cookie="csrftoken=XXXXXXXXX; LEETCODE_SESSION=YYYYYYYY;"
CSRFtoken="ZZZZZZZZ"
```
## PDF 生成
`leetcode-go pdf` 命令先生成书籍内容的合并版本 pdf.md再用 vscode 或者其他支持 toc 目录生成的工具,生成 toc。最后用 Typora 把 md 文件转换成 pdf。就可以发布 release 新版本了。

30
ctl/command.go Normal file
View File

@ -0,0 +1,30 @@
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "leetcode-go",
Short: "A simple command line client for leetcode-go.",
}
func execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
rootCmd.AddCommand(
versionCmd,
newBuildCommand(),
newLabelCommand(),
newPDFCommand(),
newRefresh(),
)
}

32
ctl/config.go Normal file
View File

@ -0,0 +1,32 @@
package main
import (
"fmt"
"log"
"github.com/BurntSushi/toml"
)
const (
configTOML = "config.toml"
)
type config struct {
Username string
Password string
Cookie string
CSRFtoken string
}
func (c config) String() string {
return fmt.Sprintf("Username: %s, Password: %s", c.Username, c.Password)
}
func getConfig() *config {
cfg := new(config)
if _, err := toml.DecodeFile(configTOML, &cfg); err != nil {
log.Panicf(err.Error())
}
// log.Printf("get config: %s", cfg)
return cfg
}

21
ctl/error.go Normal file
View File

@ -0,0 +1,21 @@
package main
import (
"fmt"
"os"
)
const (
// ExitSuccess define
ExitSuccess = iota
// ExitError define
ExitError
// ExitBadArgs define
ExitBadArgs
)
// ExitWithError define
func ExitWithError(code int, err error) {
fmt.Fprintln(os.Stderr, "Error: ", err)
os.Exit(code)
}

347
ctl/label.go Normal file
View File

@ -0,0 +1,347 @@
package main
import (
"bufio"
"errors"
"fmt"
"github.com/halfrost/LeetCode-Go/ctl/util"
"github.com/spf13/cobra"
"io"
"io/ioutil"
"os"
"regexp"
"strings"
)
var (
chapterOneFileOrder = []string{"_index", "Data_Structure", "Algorithm"}
chapterOneMenuOrder = []string{"_index", "#关于作者", "Data_Structure", "Algorithm"}
chapterTwoFileOrder = []string{"_index", "Array", "String", "Two_Pointers", "Linked_List", "Stack", "Tree", "Dynamic_Programming", "Backtracking", "Depth_First_Search", "Breadth_First_Search",
"Binary_Search", "Math", "Hash_Table", "Sort", "Bit_Manipulation", "Union_Find", "Sliding_Window", "Segment_Tree", "Binary_Indexed_Tree"}
chapterThreeFileOrder = []string{"_index", "Segment_Tree", "UnionFind", "LRUCache", "LFUCache"}
preNextHeader = "----------------------------------------------\n<div style=\"display: flex;justify-content: space-between;align-items: center;\">\n"
preNextFotter = "</div>"
delLine = "----------------------------------------------\n"
delHeader = "<div style=\"display: flex;justify-content: space-between;align-items: center;\">"
delLabel = "<[a-zA-Z]+.*?>([\\s\\S]*?)</[a-zA-Z]*?>"
delFooter = "</div>"
//ErrNoFilename is thrown when the path the the file to tail was not given
ErrNoFilename = errors.New("You must provide the path to a file in the \"-file\" flag.")
//ErrInvalidLineCount is thrown when the user provided 0 (zero) as the value for number of lines to tail
ErrInvalidLineCount = errors.New("You cannot tail zero lines.")
chapterMap = map[string]map[string]string{
"ChapterOne": {
"_index": "第一章 序章",
"#关于作者": "1.1 关于作者",
"Data_Structure": "1.2 数据结构知识",
"Algorithm": "1.3 算法知识",
},
"ChapterTwo": {
"_index": "第二章 算法专题",
"Array": "2.01 Array",
"String": "2.02 String",
"Two_Pointers": "2.03 ✅ Two Pointers",
"Linked_List": "2.04 ✅ Linked List",
"Stack": "2.05 ✅ Stack",
"Tree": "2.06 Tree",
"Dynamic_Programming": "2.07 Dynamic Programming",
"Backtracking": "2.08 ✅ Backtracking",
"Depth_First_Search": "2.09 Depth First Search",
"Breadth_First_Search": "2.10 Breadth First Search",
"Binary_Search": "2.11 Binary Search",
"Math": "2.12 Math",
"Hash_Table": "2.13 Hash Table",
"Sort": "2.14 ✅ Sort",
"Bit_Manipulation": "2.15 ✅ Bit Manipulation",
"Union_Find": "2.16 ✅ Union Find",
"Sliding_Window": "2.17 ✅ Sliding Window",
"Segment_Tree": "2.18 ✅ Segment Tree",
"Binary_Indexed_Tree": "2.19 ✅ Binary Indexed Tree",
},
"ChapterThree": {
"_index": "第三章 一些模板",
"Segment_Tree": "3.1 Segment Tree",
"UnionFind": "3.2 UnionFind",
"LRUCache": "3.3 LRUCache",
"LFUCache": "3.4 LFUCache",
},
"ChapterFour": {
"_index": "第四章 Leetcode 题解",
},
}
)
func getChapterFourFileOrder() ([]string, []int) {
solutions, solutionIds := util.LoadChapterFourDir()
chapterFourFileOrder := []string{"_index"}
chapterFourFileOrder = append(chapterFourFileOrder, solutions...)
fmt.Printf("ChapterFour 中包括 _index 有 %v 个文件, len(id) = %v\n", len(chapterFourFileOrder), len(solutionIds))
return chapterFourFileOrder, solutionIds
}
func newLabelCommand() *cobra.Command {
mc := &cobra.Command{
Use: "label <subcommand>",
Short: "Label related commands",
}
//mc.PersistentFlags().StringVar(&logicEndpoint, "endpoint", "localhost:5880", "endpoint of logic service")
mc.AddCommand(
newAddPreNext(),
newDeletePreNext(),
)
return mc
}
func newAddPreNext() *cobra.Command {
cmd := &cobra.Command{
Use: "add-pre-next",
Short: "Add pre-next label",
Run: func(cmd *cobra.Command, args []string) {
addPreNext()
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func newDeletePreNext() *cobra.Command {
cmd := &cobra.Command{
Use: "del-pre-next",
Short: "Delete pre-next label",
Run: func(cmd *cobra.Command, args []string) {
delPreNext()
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func addPreNext() {
// Chpater one add pre-next
addPreNextLabel(chapterOneFileOrder, []string{}, []int{}, "", "ChapterOne", "ChapterTwo")
// Chpater two add pre-next
addPreNextLabel(chapterTwoFileOrder, chapterOneFileOrder, []int{}, "ChapterOne", "ChapterTwo", "ChapterThree")
// Chpater three add pre-next
addPreNextLabel(chapterThreeFileOrder, chapterTwoFileOrder, []int{}, "ChapterTwo", "ChapterThree", "ChapterFour")
// Chpater four add pre-next
//fmt.Printf("%v\n", getChapterFourFileOrder())
chapterFourFileOrder, solutionIds := getChapterFourFileOrder()
addPreNextLabel(chapterFourFileOrder, chapterThreeFileOrder, solutionIds, "ChapterThree", "ChapterFour", "")
}
func addPreNextLabel(order, preOrder []string, chapterFourIds []int, preChapter, chapter, nextChapter string) {
var (
exist bool
err error
res []byte
count int
)
for index, path := range order {
tmp := ""
if index == 0 {
if chapter == "ChapterOne" {
// 第一页不需要“上一章”
tmp = "\n\n" + delLine + fmt.Sprintf("<p align = \"right\"><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1])
} else {
if chapter == "ChapterFour" {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一章</a></p>\n", preChapter, preOrder[len(preOrder)-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">下一页➡️</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter
} else {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一章</a></p>\n", preChapter, preOrder[len(preOrder)-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) + preNextFotter
}
}
} else if index == len(order)-1 {
if chapter == "ChapterFour" {
// 最后一页不需要“下一页”
tmp = "\n\n" + delLine + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">⬅️上一页</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)-1]), order[index-1])
} else {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一页</a></p>\n", chapter, order[index-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/\">下一章➡️</a></p>\n", nextChapter) + preNextFotter
}
} else if index == 1 {
if chapter == "ChapterFour" {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/\">⬅️上一页</a></p>\n", chapter) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">下一页➡️</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter
} else {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/\">⬅️上一页</a></p>\n", chapter) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) + preNextFotter
}
} else {
if chapter == "ChapterFour" {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">⬅️上一页</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)-1]), order[index-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">下一页➡️</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter
} else {
tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一页</a></p>\n", chapter, order[index-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) + preNextFotter
}
}
if chapter == "ChapterFour" && index > 0 {
path = fmt.Sprintf("%v/%v", util.GetChpaterFourFileNum(chapterFourIds[(index-1)]), path)
}
exist, err = needAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path))
if err != nil {
fmt.Println(err)
return
}
// 当前没有上一页和下一页,才添加
if !exist && err == nil {
res, err = eofAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), tmp)
if err != nil {
fmt.Println(err)
return
}
util.WriteFile(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), res)
count++
}
}
fmt.Printf("添加了 %v 个文件的 pre-next\n", count)
}
func eofAdd(filePath string, labelString string) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
output = append(output, []byte(labelString)...)
output = append(output, []byte("\n")...)
return output, nil
}
return nil, err
}
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
func delPreNext() {
// Chpater one del pre-next
delPreNextLabel(chapterOneFileOrder, []int{}, "ChapterOne")
// Chpater two del pre-next
delPreNextLabel(chapterTwoFileOrder, []int{}, "ChapterTwo")
// Chpater three del pre-next
delPreNextLabel(chapterThreeFileOrder, []int{}, "ChapterThree")
// Chpater four del pre-next
chapterFourFileOrder, solutionIds := getChapterFourFileOrder()
delPreNextLabel(chapterFourFileOrder, solutionIds, "ChapterFour")
}
func delPreNextLabel(order []string, chapterFourIds []int, chapter string) {
count := 0
for index, path := range order {
lineNum := 5
if index == 0 && chapter == "ChapterOne" || index == len(order)-1 && chapter == "ChapterFour" {
lineNum = 3
}
if chapter == "ChapterFour" && index > 0 {
path = fmt.Sprintf("%v/%v", util.GetChpaterFourFileNum(chapterFourIds[(index-1)]), path)
}
exist, err := needAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path))
if err != nil {
fmt.Println(err)
return
}
// 存在才删除
if exist && err == nil {
removeLine(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), lineNum+1)
count++
}
}
fmt.Printf("删除了 %v 个文件的 pre-next\n", count)
// 另外一种删除方法
// res, err := eofDel(fmt.Sprintf("../website/content/ChapterOne/%v.md", v))
// if err != nil {
// fmt.Println(err)
// return
// }
// util.WriteFile(fmt.Sprintf("../website/content/ChapterOne/%v.md", v), res)
}
func needAdd(filePath string) (bool, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return false, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return false, nil
}
return false, err
}
if ok, _ := regexp.Match(delHeader, line); ok {
return true, nil
} else if ok, _ := regexp.Match(delLabel, line); ok {
return true, nil
} else {
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
}
func eofDel(filePath string) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return output, nil
}
return nil, err
}
if ok, _ := regexp.Match(delLine, line); ok {
reg := regexp.MustCompile(delLine)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match(delHeader, line); ok {
reg := regexp.MustCompile(delHeader)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match(delLabel, line); ok {
reg := regexp.MustCompile(delLabel)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match(delFooter, line); ok {
reg := regexp.MustCompile(delFooter)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else {
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
}
func removeLine(path string, lineNumber int) {
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
info, _ := os.Stat(path)
mode := info.Mode()
array := strings.Split(string(file), "\n")
array = array[:len(array)-lineNumber-1]
ioutil.WriteFile(path, []byte(strings.Join(array, "\n")), mode)
//fmt.Println("remove line successful")
}

5
ctl/main.go Normal file
View File

@ -0,0 +1,5 @@
package main
func main() {
execute()
}

52
ctl/meta/Array Normal file
View File

@ -0,0 +1,52 @@
|1. Two Sum| [Go]({{< relref "/ChapterFour/0001.Two-Sum.md" >}})| Easy | O(n)| O(n)||
|11. Container With Most Water| [Go]({{< relref "/ChapterFour/0011.Container-With-Most-Water.md" >}})| Medium | O(n)| O(1)||
|15. 3Sum | [Go]({{< relref "/ChapterFour/0015.3Sum.md" >}})| Medium | O(n^2)| O(n)|❤️|
|16. 3Sum Closest | [Go]({{< relref "/ChapterFour/0016.3Sum-Closest.md" >}})| Medium | O(n^2)| O(1)|❤️|
|18. 4Sum | [Go]({{< relref "/ChapterFour/0018.4Sum.md" >}})| Medium | O(n^3)| O(n^2)|❤️|
|26. Remove Duplicates from Sorted Array | [Go]({{< relref "/ChapterFour/0026.Remove-Duplicates-from-Sorted-Array.md" >}})| Easy | O(n)| O(1)||
|27. Remove Element | [Go]({{< relref "/ChapterFour/0027.Remove-Element.md" >}})| Easy | O(n)| O(1)||
|39. Combination Sum | [Go]({{< relref "/ChapterFour/0039.Combination-Sum.md" >}})| Medium | O(n log n)| O(n)||
|40. Combination Sum II | [Go]({{< relref "/ChapterFour/0040.Combination-Sum-II.md" >}})| Medium | O(n log n)| O(n)||
|41. First Missing Positive | [Go]({{< relref "/ChapterFour/0041.First-Missing-Positive.md" >}})| Hard | O(n)| O(n)||
|42. Trapping Rain Water | [Go]({{< relref "/ChapterFour/0042.Trapping-Rain-Water.md" >}})| Hard | O(n)| O(1)|❤️|
|48. Rotate Image | [Go]({{< relref "/ChapterFour/0048.Rotate-Image.md" >}})| Medium | O(n)| O(1)||
|53. Maximum Subarray| [Go]({{< relref "/ChapterFour/0053.Maximum-Subarray.md" >}})| Easy | O(n)| O(n)||
|54. Spiral Matrix| [Go]({{< relref "/ChapterFour/0054.Spiral-Matrix.md" >}})| Medium | O(n)| O(n^2)||
|56. Merge Intervals | [Go]({{< relref "/ChapterFour/0056.Merge-Intervals.md" >}})| Medium | O(n log n)| O(1)||
|57. Insert Interval | [Go]({{< relref "/ChapterFour/0057.Insert-Interval.md" >}})| Hard | O(n)| O(1)||
|59. Spiral Matrix II | [Go]({{< relref "/ChapterFour/0059.Spiral-Matrix-II.md" >}})| Medium | O(n)| O(n^2)||
|62. Unique Paths | [Go]({{< relref "/ChapterFour/0062.Unique-Paths.md" >}})| Medium | O(n^2)| O(n^2)||
|63. Unique Paths II | [Go]({{< relref "/ChapterFour/0063.Unique-Paths-II.md" >}})| Medium | O(n^2)| O(n^2)||
|64. Minimum Path Sum | [Go]({{< relref "/ChapterFour/0064.Minimum-Path-Sum.md" >}})| Medium | O(n^2)| O(n^2)||
|75. Sort Colors | [Go]({{< relref "/ChapterFour/0075.Sort-Colors.md" >}})| Medium| O(n)| O(1)|❤️|
|78. Subsets| [Go]({{< relref "/ChapterFour/0078.Subsets.md" >}})| Medium | O(n^2)| O(n)|❤️|
|79. Word Search | [Go]({{< relref "/ChapterFour/0079.Word-Search.md" >}})| Medium | O(n^2)| O(n^2)|❤️|
|80. Remove Duplicates from Sorted Array II| [Go]({{< relref "/ChapterFour/0080.Remove-Duplicates-from-Sorted-Array-II.md" >}})| Medium | O(n)| O(1||
|84. Largest Rectangle in Histogram | [Go]({{< relref "/ChapterFour/0084.Largest-Rectangle-in-Histogram.md" >}})| Medium | O(n)| O(n)|❤️|
|88. Merge Sorted Array | [Go]({{< relref "/ChapterFour/0088.Merge-Sorted-Array.md" >}})| Easy | O(n)| O(1)|❤️|
|90. Subsets II | [Go]({{< relref "/ChapterFour/0090.Subsets-II.md" >}})| Medium | O(n^2)| O(n)|❤️|
|120. Triangle | [Go]({{< relref "/ChapterFour/0120.Triangle.md" >}})| Medium | O(n^2)| O(n)||
|121. Best Time to Buy and Sell Stock | [Go]({{< relref "/ChapterFour/0121.Best-Time-to-Buy-and-Sell-Stock.md" >}})| Easy | O(n)| O(1)||
|122. Best Time to Buy and Sell Stock II | [Go]({{< relref "/ChapterFour/0122.Best-Time-to-Buy-and-Sell-Stock-II.md" >}})| Easy | O(n)| O(1)||
|126. Word Ladder II | [Go]({{< relref "/ChapterFour/0126.Word-Ladder-II.md" >}})| Hard | O(n)| O(n^2)|❤️|
|152. Maximum Product Subarray | [Go]({{< relref "/ChapterFour/0152.Maximum-Product-Subarray.md" >}})| Medium | O(n)| O(1)||
|167. Two Sum II - Input array is sorted | [Go]({{< relref "/ChapterFour/0167.Two-Sum-II---Input-array-is-sorted.md" >}})| Easy | O(n)| O(1)||
|209. Minimum Size Subarray Sum | [Go]({{< relref "/ChapterFour/0209.Minimum-Size-Subarray-Sum.md" >}})| Medium | O(n)| O(1)||
|216. Combination Sum III | [Go]({{< relref "/ChapterFour/0216.Combination-Sum-III.md" >}})| Medium | O(n)| O(1)|❤️|
|217. Contains Duplicate | [Go]({{< relref "/ChapterFour/0217.Contains-Duplicate.md" >}})| Easy | O(n)| O(n)||
|219. Contains Duplicate II | [Go]({{< relref "/ChapterFour/0219.Contains-Duplicate-II.md" >}})| Easy | O(n)| O(n)||
|283. Move Zeroes | [Go]({{< relref "/ChapterFour/0283.Move-Zeroes.md" >}})| Easy | O(n)| O(1)||
|287. Find the Duplicate Number | [Go]({{< relref "/ChapterFour/0287.Find-the-Duplicate-Number.md" >}})| Easy | O(n)| O(1)|❤️|
|532. K-diff Pairs in an Array | [Go]({{< relref "/ChapterFour/0532.K-diff-Pairs-in-an-Array.md" >}})| Easy | O(n)| O(n)||
|566. Reshape the Matrix | [Go]({{< relref "/ChapterFour/0566.Reshape-the-Matrix.md" >}})| Easy | O(n^2)| O(n^2)||
|628. Maximum Product of Three Numbers | [Go]({{< relref "/ChapterFour/0628.Maximum-Product-of-Three-Numbers.md" >}})| Easy | O(n)| O(1)||
|713. Subarray Product Less Than K | [Go]({{< relref "/ChapterFour/0713.Subarray-Product-Less-Than-K.md" >}})| Medium | O(n)| O(1)||
|714. Best Time to Buy and Sell Stock with Transaction Fee| [Go]({{< relref "/ChapterFour/0714.Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee.md" >}})| Medium | O(n)| O(1)||
|746. Min Cost Climbing Stairs | [Go]({{< relref "/ChapterFour/0746.Min-Cost-Climbing-Stairs.md" >}})| Easy | O(n)| O(1)||
|766. Toeplitz Matrix | [Go]({{< relref "/ChapterFour/0766.Toeplitz-Matrix.md" >}})| Easy | O(n)| O(1)||
|867. Transpose Matrix | [Go]({{< relref "/ChapterFour/0867.Transpose-Matrix.md" >}})| Easy | O(n)| O(1)||
|891. Sum of Subsequence Widths | [Go]({{< relref "/ChapterFour/0891.Sum-of-Subsequence-Widths.md" >}})| Hard | O(n log n)| O(1)||
|907. Sum of Subarray Minimums | [Go]({{< relref "/ChapterFour/0907.Sum-of-Subarray-Minimums.md" >}})| Medium | O(n)| O(n)|❤️|
|922. Sort Array By Parity II | [Go]({{< relref "/ChapterFour/0922.Sort-Array-By-Parity-II.md" >}})| Medium | O(n)| O(1)||
|969. Pancake Sorting | [Go]({{< relref "/ChapterFour/0969.Pancake-Sorting.md" >}})| Medium | O(n)| O(1)|❤️|
|977. Squares of a Sorted Array | [Go]({{< relref "/ChapterFour/0977.Squares-of-a-Sorted-Array.md" >}})| Easy | O(n)| O(1)||

30
ctl/meta/Backtracking Normal file
View File

@ -0,0 +1,30 @@
|17. Letter Combinations of a Phone Number | [Go]({{< relref "/ChapterFour/0017.Letter-Combinations-of-a-Phone-Number.md" >}})| Medium | O(log n)| O(1)||
|22. Generate Parentheses| [Go]({{< relref "/ChapterFour/0022.Generate-Parentheses.md" >}})| Medium | O(log n)| O(1)||
|37. Sudoku Solver | [Go]({{< relref "/ChapterFour/0037.Sudoku-Solver.md" >}})| Hard | O(n^2)| O(n^2)|❤️|
|39. Combination Sum | [Go]({{< relref "/ChapterFour/0039.Combination-Sum.md" >}})| Medium | O(n log n)| O(n)||
|40. Combination Sum II | [Go]({{< relref "/ChapterFour/0040.Combination-Sum-II.md" >}})| Medium | O(n log n)| O(n)||
|46. Permutations | [Go]({{< relref "/ChapterFour/0046.Permutations.md" >}})| Medium | O(n)| O(n)|❤️|
|47. Permutations II | [Go]({{< relref "/ChapterFour/0047.Permutations-II.md" >}})| Medium | O(n^2)| O(n)|❤️|
|51. N-Queens | [Go]({{< relref "/ChapterFour/0051.N-Queens.md" >}})| Hard | O(n!)| O(n)|❤️|
|52. N-Queens II | [Go]({{< relref "/ChapterFour/0052.N-Queens-II.md" >}})| Hard | O(n!)| O(n)|❤️|
|60. Permutation Sequence | [Go]({{< relref "/ChapterFour/0060.Permutation-Sequence.md" >}})| Medium | O(n log n)| O(1)||
|77. Combinations | [Go]({{< relref "/ChapterFour/0077.Combinations.md" >}})| Medium | O(n)| O(n)|❤️|
|78. Subsets | [Go]({{< relref "/ChapterFour/0078.Subsets.md" >}})| Medium | O(n^2)| O(n)|❤️|
|79. Word Search | [Go]({{< relref "/ChapterFour/0079.Word-Search.md" >}})| Medium | O(n^2)| O(n^2)|❤️|
|89. Gray Codes | [Go]({{< relref "/ChapterFour/0089.Gray-Code.md" >}})| Medium | O(n)| O(1)||
|90. Subsets II | [Go]({{< relref "/ChapterFour/0090.Subsets-II.md" >}})| Medium | O(n^2)| O(n)|❤️|
|93. Restore IP Addresses | [Go]({{< relref "/ChapterFour/0093.Restore-IP-Addresses.md" >}})| Medium | O(n)| O(n)|❤️|
|126. Word Ladder II | [Go]({{< relref "/ChapterFour/0126.Word-Ladder-II.md" >}})| Hard | O(n)| O(n^2)|❤️|
|131. Palindrome Partitioning | [Go]({{< relref "/ChapterFour/0131.Palindrome-Partitioning.md" >}})| Medium | O(n)| O(n^2)|❤️|
|211. Add and Search Word - Data structure design | [Go]({{< relref "/ChapterFour/0211.Add-and-Search-Word---Data-structure-design.md" >}})| Medium | O(n)| O(n)|❤️|
|212. Word Search II | [Go]({{< relref "/ChapterFour/0212.Word-Search-II.md" >}})| Hard | O(n^2)| O(n^2)|❤️|
|216. Combination Sum III | [Go]({{< relref "/ChapterFour/0216.Combination-Sum-III.md" >}})| Medium | O(n)| O(1)|❤️|
|306. Additive Number | [Go]({{< relref "/ChapterFour/0306.Additive-Number.md" >}})| Medium | O(n^2)| O(1)|❤️|
|357. Count Numbers with Unique Digits | [Go]({{< relref "/ChapterFour/0357.Count-Numbers-with-Unique-Digits.md" >}})| Medium | O(1)| O(1)||
|401. Binary Watch | [Go]({{< relref "/ChapterFour/0401.Binary-Watch.md" >}})| Easy | O(1)| O(1)||
|526. Beautiful Arrangement | [Go]({{< relref "/ChapterFour/0526.Beautiful-Arrangement.md" >}})| Medium | O(n^2)| O(1)|❤️|
|784. Letter Case Permutation | [Go]({{< relref "/ChapterFour/0784.Letter-Case-Permutation.md" >}})| Easy | O(n)| O(n)||
|842. Split Array into Fibonacci Sequence | [Go]({{< relref "/ChapterFour/0842.Split-Array-into-Fibonacci-Sequence.md" >}})| Medium | O(n^2)| O(1)|❤️|
|980. Unique Paths III | [Go]({{< relref "/ChapterFour/0980.Unique-Paths-III.md" >}})| Hard | O(n log n)| O(n)||
|996. Number of Squareful Arrays | [Go]({{< relref "/ChapterFour/0996.Number-of-Squareful-Arrays.md" >}})| Hard | O(n log n)| O(n) ||
|1079. Letter Tile Possibilities | [Go]({{< relref "/ChapterFour/1079.Letter-Tile-Possibilities.md" >}})| Medium | O(n^2)| O(1)|❤️|

View File

13
ctl/meta/Binary_Search Normal file
View File

@ -0,0 +1,13 @@
|50. Pow(x, n) | [Go]({{< relref "/ChapterFour/0050.Powx-n.md" >}})| Medium | O(log n)| O(1)||
|69. Sqrt(x) | [Go]({{< relref "/ChapterFour/0069.Sqrtx.md" >}})| Easy | O(log n)| O(1)||
|167. Two Sum II - Input array is sorted | [Go]({{< relref "/ChapterFour/0167.Two-Sum-II---Input-array-is-sorted.md" >}})| Easy | O(n)| O(1)||
|209. Minimum Size Subarray Sum | [Go]({{< relref "/ChapterFour/0209.Minimum-Size-Subarray-Sum.md" >}})| Medium | O(n)| O(1)||
|222. Count Complete Tree Nodes | [Go]({{< relref "/ChapterFour/0222.Count-Complete-Tree-Nodes.md" >}})| Medium | O(n)| O(1)||
|230. Kth Smallest Element in a BST | [Go]({{< relref "/ChapterFour/0230.Kth-Smallest-Element-in-a-BST.md" >}})| Medium | O(n)| O(1)||
|287. Find the Duplicate Number | [Go]({{< relref "/ChapterFour/0287.Find-the-Duplicate-Number.md" >}})| Easy | O(n)| O(1)|❤️|
|300. Longest Increasing Subsequence | [Go]({{< relref "/ChapterFour/0300.Longest-Increasing-Subsequence.md" >}})| Medium | O(n log n)| O(n)||
|349. Intersection of Two Arrays | [Go]({{< relref "/ChapterFour/0349.Intersection-of-Two-Arrays.md" >}})| Easy | O(n)| O(n) ||
|350. Intersection of Two Arrays II | [Go]({{< relref "/ChapterFour/0350.Intersection-of-Two-Arrays-II.md" >}})| Easy | O(n)| O(n) ||
|392. Is Subsequence | [Go]({{< relref "/ChapterFour/0392.Is-Subsequence.md" >}})| Medium | O(n)| O(1)||
|454. 4Sum II | [Go]({{< relref "/ChapterFour/0454.4Sum-II.md" >}})| Medium | O(n^2)| O(n) ||
|710. Random Pick with Blacklist | [Go]({{< relref "/ChapterFour/0710.Random-Pick-with-Blacklist.md" >}})| Hard | O(n)| O(n) ||

29
ctl/meta/Bit_Manipulation Normal file
View File

@ -0,0 +1,29 @@
|78. Subsets | [Go]({{< relref "/ChapterFour/0078.Subsets.md" >}})| Medium | O(n^2)| O(n)|❤️|
|136. Single Number | [Go]({{< relref "/ChapterFour/0136.Single-Number.md" >}})| Easy | O(n)| O(1)||
|137. Single Number II | [Go]({{< relref "/ChapterFour/0137.Single-Number-II.md" >}})| Medium | O(n)| O(1)|❤️|
|169. Majority Element | [Go]({{< relref "/ChapterFour/0169.Majority-Element.md" >}})| Easy | O(n)| O(1)|❤️|
|187. Repeated DNA Sequences | [Go]({{< relref "/ChapterFour/0187.Repeated-DNA-Sequences.md" >}})| Medium | O(n)| O(1)||
|190. Reverse Bits | [Go]({{< relref "/ChapterFour/0190.Reverse-Bits.md" >}})| Easy | O(n)| O(1)|❤️|
|191. Number of 1 Bits | [Go]({{< relref "/ChapterFour/0191.Number-of-1-Bits.md" >}})| Easy | O(n)| O(1)||
|201. Bitwise AND of Numbers Range | [Go]({{< relref "/ChapterFour/0201.Bitwise-AND-of-Numbers-Range.md" >}})| Medium | O(n)| O(1)|❤️|
|231. Power of Two | [Go]({{< relref "/ChapterFour/0231.Power-of-Two.md" >}})| Easy | O(1)| O(1)||
|260. Single Number III | [Go]({{< relref "/ChapterFour/0260.Single-Number-III.md" >}})| Medium | O(n)| O(1)|❤️|
|268. Missing Number | [Go]({{< relref "/ChapterFour/0268.Missing-Number.md" >}})| Easy | O(n)| O(1)||
|318. Maximum Product of Word Lengths | [Go]({{< relref "/ChapterFour/0318.Maximum-Product-of-Word-Lengths.md" >}})| Medium | O(n)| O(1)||
|338. Counting Bits | [Go]({{< relref "/ChapterFour/0338.Counting-Bits.md" >}})| Medium | O(n)| O(n)||
|342. Power of Four | [Go]({{< relref "/ChapterFour/0342.Power-of-Four.md" >}})| Easy | O(n)| O(1)||
|371. Sum of Two Integers | [Go]({{< relref "/ChapterFour/0371.Sum-of-Two-Integers.md" >}})| Easy | O(n)| O(1)||
|389. Find the Difference | [Go]({{< relref "/ChapterFour/0389.Find-the-Difference.md" >}})| Easy | O(n)| O(1)||
|393. UTF-8 Validation | [Go]({{< relref "/ChapterFour/0393.UTF-8-Validation.md" >}})| Medium | O(n)| O(1)||
|397. Integer Replacement | [Go]({{< relref "/ChapterFour/0397.Integer-Replacement.md" >}})| Medium | O(n)| O(1)||
|401. Binary Watch | [Go]({{< relref "/ChapterFour/0401.Binary-Watch.md" >}})| Easy | O(1)| O(1)||
|405. Convert a Number to Hexadecimal | [Go]({{< relref "/ChapterFour/0405.Convert-a-Number-to-Hexadecimal.md" >}})| Easy | O(n)| O(1)||
|421. Maximum XOR of Two Numbers in an Array | [Go]({{< relref "/ChapterFour/0421.Maximum-XOR-of-Two-Numbers-in-an-Array.md" >}})| Medium | O(n)| O(1)|❤️|
|461. Hamming Distance | [Go]({{< relref "/ChapterFour/0461.Hamming-Distance.md" >}})| Easy | O(n)| O(1)||
|476. Number Complement | [Go]({{< relref "/ChapterFour/0476.Number-Complement.md" >}})| Easy | O(n)| O(1)||
|477. Total Hamming Distance | [Go]({{< relref "/ChapterFour/0477.Total-Hamming-Distance.md" >}})| Medium | O(n)| O(1)||
|693. Binary Number with Alternating Bits | [Go]({{< relref "/ChapterFour/0693.Binary-Number-with-Alternating-Bits.md" >}})| Easy | O(n)| O(1)|❤️|
|756. Pyramid Transition Matrix | [Go]({{< relref "/ChapterFour/0756.Pyramid-Transition-Matrix.md" >}})| Medium | O(n log n)| O(n)||
|762. Prime Number of Set Bits in Binary Representation | [Go]({{< relref "/ChapterFour/0762.Prime-Number-of-Set-Bits-in-Binary-Representation.md" >}})| Easy | O(n)| O(1)||
|784. Letter Case Permutation | [Go]({{< relref "/ChapterFour/0784.Letter-Case-Permutation.md" >}})| Easy | O(n)| O(1)||
|898. Bitwise ORs of Subarrays | [Go]({{< relref "/ChapterFour/0898.Bitwise-ORs-of-Subarrays.md" >}})| Medium | O(n)| O(1)||

View File

@ -0,0 +1,14 @@
|101. Symmetric Tree | [Go]({{< relref "/ChapterFour/0101.Symmetric-Tree.md" >}})| Easy | O(n)| O(1)||
|102. Binary Tree Level Order Traversal | [Go]({{< relref "/ChapterFour/0102.Binary-Tree-Level-Order-Traversal.md" >}})| Medium | O(n)| O(1)||
|103. Binary Tree Zigzag Level Order Traversal | [Go]({{< relref "/ChapterFour/0103.Binary-Tree-Zigzag-Level-Order-Traversal.md" >}})| Medium | O(n)| O(n)||
|107. Binary Tree Level Order Traversal II | [Go]({{< relref "/ChapterFour/0107.Binary-Tree-Level-Order-Traversal-II.md" >}})| Easy | O(n)| O(1)||
|111. Minimum Depth of Binary Tree | [Go]({{< relref "/ChapterFour/0111.Minimum-Depth-of-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|126. Word Ladder II | [Go]({{< relref "/ChapterFour/0126.Word-Ladder-II.md" >}})| Hard | O(n)| O(n^2)|❤️|
|127. Word Ladder | [Go]({{< relref "/ChapterFour/0127.Word-Ladder.md" >}})| Medium | O(n)| O(n)||
|199. Binary Tree Right Side View | [Go]({{< relref "/ChapterFour/0199.Binary-Tree-Right-Side-View.md" >}})| Medium | O(n)| O(1)||
|200. Number of Islands | [Go]({{< relref "/ChapterFour/0200.Number-of-Islands.md" >}})| Medium | O(n^2)| O(n^2)||
|207. Course Schedule | [Go]({{< relref "/ChapterFour/0207.Course-Schedule.md" >}})| Medium | O(n^2)| O(n^2)||
|210. Course Schedule II | [Go]({{< relref "/ChapterFour/0210.Course-Schedule-II.md" >}})| Medium | O(n^2)| O(n^2)||
|515. Find Largest Value in Each Tree Row | [Go]({{< relref "/ChapterFour/0515.Find-Largest-Value-in-Each-Tree-Row.md" >}})| Medium | O(n)| O(n)||
|542. 01 Matrix | [Go]({{< relref "/ChapterFour/0542.01-Matrix.md" >}})| Medium | O(n)| O(1)||
|993. Cousins in Binary Tree | [Go]({{< relref "/ChapterFour/0993.Cousins-in-Binary-Tree.md" >}})| Easy | O(n)| O(1)||

View File

@ -0,0 +1,23 @@
|98. Validate Binary Search Tree | [Go]({{< relref "/ChapterFour/0098.Validate-Binary-Search-Tree.md" >}})| Medium | O(n)| O(1)||
|99. Recover Binary Search Tree | [Go]({{< relref "/ChapterFour/0099.Recover-Binary-Search-Tree.md" >}})| Hard | O(n)| O(1)||
|100. Same Tree | [Go]({{< relref "/ChapterFour/0100.Same-Tree.md" >}})| Easy | O(n)| O(1)||
|101. Symmetric Tree | [Go]({{< relref "/ChapterFour/0101.Symmetric-Tree.md" >}})| Easy | O(n)| O(1)||
|104. Maximum Depth of Binary Tree | [Go]({{< relref "/ChapterFour/0104.Maximum-Depth-of-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|108. Convert Sorted Array to Binary Search Tree | [Go]({{< relref "/ChapterFour/0108.Convert-Sorted-Array-to-Binary-Search-Tree.md" >}})| Easy | O(n)| O(1)||
|109. Convert Sorted List to Binary Search Tree | [Go]({{< relref "/ChapterFour/0109.Convert-Sorted-List-to-Binary-Search-Tree.md" >}})| Medium | O(log n)| O(n)||
|110. Balanced Binary Tree | [Go]({{< relref "/ChapterFour/0110.Balanced-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|111. Minimum Depth of Binary Tree | [Go]({{< relref "/ChapterFour/0111.Minimum-Depth-of-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|112. Path Sum | [Go]({{< relref "/ChapterFour/0112.Path-Sum.md" >}})| Easy | O(n)| O(1)||
|113. Path Sum II | [Go]({{< relref "/ChapterFour/0113.Path-Sum-II.md" >}})| Medium | O(n)| O(1)||
|114. Flatten Binary Tree to Linked List | [Go]({{< relref "/ChapterFour/0114.Flatten-Binary-Tree-to-Linked-List.md" >}})| Medium | O(n)| O(1)||
|124. Binary Tree Maximum Path Sum | [Go]({{< relref "/ChapterFour/0124.Binary-Tree-Maximum-Path-Sum.md" >}})| Hard | O(n)| O(1)||
|129. Sum Root to Leaf Numbers | [Go]({{< relref "/ChapterFour/0129.Sum-Root-to-Leaf-Numbers.md" >}})| Medium | O(n)| O(1)||
|199. Binary Tree Right Side View | [Go]({{< relref "/ChapterFour/0199.Binary-Tree-Right-Side-View.md" >}})| Medium | O(n)| O(1)||
|200. Number of Islands | [Go]({{< relref "/ChapterFour/0200.Number-of-Islands.md" >}})| Medium | O(n^2)| O(n^2)||
|207. Course Schedule | [Go]({{< relref "/ChapterFour/0207.Course-Schedule.md" >}})| Medium | O(n^2)| O(n^2)||
|210. Course Schedule II | [Go]({{< relref "/ChapterFour/0210.Course-Schedule-II.md" >}})| Medium | O(n^2)| O(n^2)||
|257. Binary Tree Paths | [Go]({{< relref "/ChapterFour/0257.Binary-Tree-Paths.md" >}})| Easy | O(n)| O(1)||
|394. Decode String | [Go]({{< relref "/ChapterFour/0394.Decode-String.md" >}})| Medium | O(n)| O(n)||
|515. Find Largest Value in Each Tree Row | [Go]({{< relref "/ChapterFour/0515.Find-Largest-Value-in-Each-Tree-Row.md" >}})| Medium | O(n)| O(n)||
|542. 01 Matrix | [Go]({{< relref "/ChapterFour/0542.01-Matrix.md" >}})| Medium | O(n)| O(1)||
|980. Unique Paths III | [Go]({{< relref "/ChapterFour/0980.Unique-Paths-III.md" >}})| Hard | O(n log n)| O(n)||

View File

@ -0,0 +1,26 @@
|53. Maximum Subarray| [Go]({{< relref "/ChapterFour/0053.Maximum-Subarray.md" >}})| Easy | O(n)| O(n)||
|62. Unique Paths | [Go]({{< relref "/ChapterFour/0062.Unique-Paths.md" >}})| Medium | O(n^2)| O(n^2)||
|63. Unique Paths II | [Go]({{< relref "/ChapterFour/0063.Unique-Paths-II.md" >}})| Medium | O(n^2)| O(n^2)||
|64. Minimum Path Sum | [Go]({{< relref "/ChapterFour/0064.Minimum-Path-Sum.md" >}})| Medium | O(n^2)| O(n^2)||
|70. Climbing Stairs | [Go]({{< relref "/ChapterFour/0070.Climbing-Stairs.md" >}})| Easy | O(n)| O(n)||
|91. Decode Ways | [Go]({{< relref "/ChapterFour/0091.Decode-Ways.md" >}})| Medium | O(n)| O(n)||
|96. Unique Binary Search Trees | [Go]({{< relref "/ChapterFour/0096.Unique-Binary-Search-Trees.md" >}})| Medium | O(n)| O(n)||
|120. Triangle | [Go]({{< relref "/ChapterFour/0120.Triangle.md" >}})| Medium | O(n^2)| O(n)||
|121. Best Time to Buy and Sell Stock | [Go]({{< relref "/ChapterFour/0121.Best-Time-to-Buy-and-Sell-Stock.md" >}})| Easy | O(n)| O(1)||
|152. Maximum Product Subarray | [Go]({{< relref "/ChapterFour/0152.Maximum-Product-Subarray.md" >}})| Medium | O(n)| O(1)||
|198. House Robber | [Go]({{< relref "/ChapterFour/0198.House-Robber.md" >}})| Easy | O(n)| O(n)||
|213. House Robber II | [Go]({{< relref "/ChapterFour/0213.House-Robber-II.md" >}})| Medium | O(n)| O(n)||
|300. Longest Increasing Subsequence | [Go]({{< relref "/ChapterFour/0300.Longest-Increasing-Subsequence.md" >}})| Medium | O(n log n)| O(n)||
|309. Best Time to Buy and Sell Stock with Cooldown | [Go]({{< relref "/ChapterFour/0309.Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.md" >}})| Medium | O(n)| O(n)||
|322. Coin Change | [Go]({{< relref "/ChapterFour/0322.Coin-Change.md" >}})| Medium | O(n)| O(n)||
|338. Counting Bits | [Go]({{< relref "/ChapterFour/0338.Counting-Bits.md" >}})| Medium | O(n)| O(n)||
|343. Integer Break | [Go]({{< relref "/ChapterFour/0343.Integer-Break.md" >}})| Medium | O(n^2)| O(n)||
|357. Count Numbers with Unique Digits | [Go]({{< relref "/ChapterFour/0357.Count-Numbers-with-Unique-Digits.md" >}})| Medium | O(1)| O(1)||
|392. Is Subsequence | [Go]({{< relref "/ChapterFour/0392.Is-Subsequence.md" >}})| Medium | O(n)| O(1)||
|416. Partition Equal Subset Sum | [Go]({{< relref "/ChapterFour/0416.Partition-Equal-Subset-Sum.md" >}})| Medium | O(n^2)| O(n)||
|714. Best Time to Buy and Sell Stock with Transaction Fee | [Go]({{< relref "/ChapterFour/0714.Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee.md" >}})| Medium | O(n)| O(1)||
|746. Min Cost Climbing Stairs | [Go]({{< relref "/ChapterFour/0746.Min-Cost-Climbing-Stairs.md" >}})| Easy | O(n)| O(1)||
|838. Push Dominoes | [Go]({{< relref "/ChapterFour/0838.Push-Dominoes.md" >}})| Medium | O(n)| O(n)||
|1025. Divisor Game | [Go]({{< relref "/ChapterFour/1025.Divisor-Game.md" >}})| Easy | O(1)| O(1)||
|891. Sum of Subsequence Widths | [Go]({{< relref "/ChapterFour/0891.Sum-of-Subsequence-Widths.md" >}})| Hard | O(n log n)| O(1)||
|942. DI String Match | [Go]({{< relref "/ChapterFour/0942.DI-String-Match.md" >}})| Easy | O(n)| O(1)||

33
ctl/meta/Hash_Table Normal file
View File

@ -0,0 +1,33 @@
|1. Two Sum | [Go]({{< relref "/ChapterFour/0001.Two-Sum.md" >}})| Easy | O(n)| O(n)||
|3. Longest Substring Without Repeating Characters | [Go]({{< relref "/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md" >}})| Medium | O(n)| O(1)|❤️|
|18. 4Sum | [Go]({{< relref "/ChapterFour/0018.4Sum.md" >}})| Medium | O(n^3)| O(n^2)|❤️|
|30. Substring with Concatenation of All Words | [Go]({{< relref "/ChapterFour/0030.Substring-with-Concatenation-of-All-Words.md" >}})| Hard | O(n)| O(n)|❤️|
|36. Valid Sudoku | [Go]({{< relref "/ChapterFour/0036.Valid-Sudoku.md" >}})| Medium | O(n^2)| O(n^2)||
|37. Sudoku Solver | [Go]({{< relref "/ChapterFour/0037.Sudoku-Solver.md" >}})| Hard | O(n^2)| O(n^2)|❤️|
|49. Group Anagrams | [Go]({{< relref "/ChapterFour/0049.Group-Anagrams.md" >}})| Medium | O(n log n)| O(n)||
|76. Minimum Window Substring | [Go]({{< relref "/ChapterFour/0076.Minimum-Window-Substring.md" >}})| Hard | O(n)| O(n)|❤️|
|94. Binary Tree Inorder Traversal | [Go]({{< relref "/ChapterFour/0094.Binary-Tree-Inorder-Traversal.md" >}})| Medium | O(n)| O(1)||
|138. Copy List with Random Pointer | [Go]()| Medium | O(n)| O(1)||
|202. Happy Number | [Go]({{< relref "/ChapterFour/0202.Happy-Number.md" >}})| Easy | O(log n)| O(1)||
|205. Isomorphic Strings | [Go]({{< relref "/ChapterFour/0205.Isomorphic-Strings.md" >}})| Easy | O(log n)| O(n)||
|217. Contains Duplicate | [Go]({{< relref "/ChapterFour/0217.Contains-Duplicate.md" >}})| Easy | O(n)| O(n)||
|219. Contains Duplicate II | [Go]({{< relref "/ChapterFour/0219.Contains-Duplicate-II.md" >}})| Easy | O(n)| O(n)||
|242. Valid Anagram | [Go]({{< relref "/ChapterFour/0242.Valid-Anagram.md" >}})| Easy | O(n)| O(n) ||
|274. H-Index | [Go]({{< relref "/ChapterFour/0274.H-Index.md" >}})| Medium | O(n)| O(n) ||
|290. Word Pattern | [Go]({{< relref "/ChapterFour/0290.Word-Pattern.md" >}})| Easy | O(n)| O(n) ||
|347. Top K Frequent Elements | [Go]({{< relref "/ChapterFour/0347.Top-K-Frequent-Elements.md" >}})| Medium | O(n)| O(n) ||
|349. Intersection of Two Arrays | [Go]({{< relref "/ChapterFour/0349.Intersection-of-Two-Arrays.md" >}})| Easy | O(n)| O(n) ||
|350. Intersection of Two Arrays II | [Go]({{< relref "/ChapterFour/0350.Intersection-of-Two-Arrays-II.md" >}})| Easy | O(n)| O(n) ||
|438. Find All Anagrams in a String | [Go]({{< relref "/ChapterFour/0438.Find-All-Anagrams-in-a-String.md" >}})| Easy | O(n)| O(1) ||
|447. Number of Boomerangs | [Go]({{< relref "/ChapterFour/0447.Number-of-Boomerangs.md" >}})| Easy | O(n)| O(1) ||
|451. Sort Characters By Frequency | [Go]({{< relref "/ChapterFour/0451.Sort-Characters-By-Frequency.md" >}})| Medium | O(n log n)| O(1) ||
|454. 4Sum II | [Go]({{< relref "/ChapterFour/0454.4Sum-II.md" >}})| Medium | O(n^2)| O(n) ||
|648. Replace Words | [Go]({{< relref "/ChapterFour/0648.Replace-Words.md" >}})| Medium | O(n)| O(n) ||
|676. Implement Magic Dictionary | [Go]({{< relref "/ChapterFour/0676.Implement-Magic-Dictionary.md" >}})| Medium | O(n)| O(n) ||
|720. Longest Word in Dictionary | [Go]({{< relref "/ChapterFour/0720.Longest-Word-in-Dictionary.md" >}})| Easy | O(n)| O(n) ||
|726. Number of Atoms | [Go]({{< relref "/ChapterFour/0726.Number-of-Atoms.md" >}})| Hard | O(n)| O(n) |❤️|
|739. Daily Temperatures | [Go]({{< relref "/ChapterFour/0739.Daily-Temperatures.md" >}})| Medium | O(n)| O(n) ||
|710. Random Pick with Blacklist | [Go]({{< relref "/ChapterFour/0710.Random-Pick-with-Blacklist.md" >}})| Hard | O(n)| O(n) ||
|895. Maximum Frequency Stack | [Go]({{< relref "/ChapterFour/0895.Maximum-Frequency-Stack.md" >}})| Hard | O(n)| O(n) ||
|930. Binary Subarrays With Sum | [Go]({{< relref "/ChapterFour/0930.Binary-Subarrays-With-Sum.md" >}})| Medium | O(n)| O(n) |❤️|
|992. Subarrays with K Different Integers | [Go]({{< relref "/ChapterFour/0992.Subarrays-with-K-Different-Integers.md" >}})| Hard | O(n)| O(n) |❤️|

29
ctl/meta/Linked_List Normal file
View File

@ -0,0 +1,29 @@
|2. Add Two Numbers | [Go]({{< relref "/ChapterFour/0002.Add-Two-Numbers.md" >}})| Medium | O(n)| O(1)||
|19. Remove Nth Node From End of List | [Go]({{< relref "/ChapterFour/0019.Remove-Nth-Node-From-End-of-List.md" >}})| Medium | O(n)| O(1)||
|21. Merge Two Sorted Lists | [Go]({{< relref "/ChapterFour/0021.Merge-Two-Sorted-Lists.md" >}})| Easy | O(log n)| O(1)||
|23. Merge k Sorted Lists| [Go]({{< relref "/ChapterFour/0023.Merge-k-Sorted-Lists.md" >}})| Hard | O(log n)| O(1)|❤️|
|24. Swap Nodes in Pairs | [Go]({{< relref "/ChapterFour/0024.Swap-Nodes-in-Pairs.md" >}})| Medium | O(n)| O(1)||
|25. Reverse Nodes in k-Group | [Go]({{< relref "/ChapterFour/0025.Reverse-Nodes-in-k-Group.md" >}})| Hard | O(log n)| O(1)|❤️|
|61. Rotate List | [Go]({{< relref "/ChapterFour/0061.Rotate-List.md" >}})| Medium | O(n)| O(1)||
|82. Remove Duplicates from Sorted List II | [Go]({{< relref "/ChapterFour/0082.Remove-Duplicates-from-Sorted-List-II.md" >}})| Medium | O(n)| O(1)||
|83. Remove Duplicates from Sorted List | [Go]({{< relref "/ChapterFour/0083.Remove-Duplicates-from-Sorted-List.md" >}})| Easy | O(n)| O(1)||
|86. Partition List | [Go]({{< relref "/ChapterFour/0086.Partition-List.md" >}})| Medium | O(n)| O(1)|❤️|
|92. Reverse Linked List II | [Go]({{< relref "/ChapterFour/0092.Reverse-Linked-List-II.md" >}})| Medium | O(n)| O(1)|❤️|
|109. Convert Sorted List to Binary Search Tree | [Go]({{< relref "/ChapterFour/0109.Convert-Sorted-List-to-Binary-Search-Tree.md" >}})| Medium | O(log n)| O(n)||
|141. Linked List Cycle | [Go]({{< relref "/ChapterFour/0141.Linked-List-Cycle.md" >}})| Easy | O(n)| O(1)|❤️|
|142. Linked List Cycle II | [Go]({{< relref "/ChapterFour/0142.Linked-List-Cycle-II.md" >}})| Medium | O(n)| O(1)|❤️|
|143. Reorder List | [Go]({{< relref "/ChapterFour/0143.Reorder-List.md" >}})| Medium | O(n)| O(1)|❤️|
|147. Insertion Sort List | [Go]({{< relref "/ChapterFour/0147.Insertion-Sort-List.md" >}})| Medium | O(n)| O(1)|❤️|
|148. Sort List | [Go]({{< relref "/ChapterFour/0148.Sort-List.md" >}})| Medium | O(n log n)| O(n)|❤️|
|160. Intersection of Two Linked Lists | [Go]({{< relref "/ChapterFour/0160.Intersection-of-Two-Linked-Lists.md" >}})| Easy | O(n)| O(1)|❤️|
|203. Remove Linked List Elements | [Go]({{< relref "/ChapterFour/0203.Remove-Linked-List-Elements.md" >}})| Easy | O(n)| O(1)||
|206. Reverse Linked List | [Go]({{< relref "/ChapterFour/0206.Reverse-Linked-List.md" >}})| Easy | O(n)| O(1)||
|234. Palindrome Linked List | [Go]({{< relref "/ChapterFour/0234.Palindrome-Linked-List.md" >}})| Easy | O(n)| O(1)||
|237. Delete Node in a Linked List | [Go]({{< relref "/ChapterFour/0237.Delete-Node-in-a-Linked-List.md" >}})| Easy | O(n)| O(1)||
|328. Odd Even Linked List | [Go]({{< relref "/ChapterFour/0328.Odd-Even-Linked-List.md" >}})| Medium | O(n)| O(1)||
|445. Add Two Numbers II | [Go]({{< relref "/ChapterFour/0445.Add-Two-Numbers-II.md" >}})| Medium | O(n)| O(n)||
|725. Split Linked List in Parts | [Go]({{< relref "/ChapterFour/0725.Split-Linked-List-in-Parts.md" >}})| Medium | O(n)| O(1)||
|817. Linked List Components | [Go]({{< relref "/ChapterFour/0817.Linked-List-Components.md" >}})| Medium | O(n)| O(1)||
|707. Design Linked List | [Go]({{< relref "/ChapterFour/0707.Design-Linked-List.md" >}})| Easy | O(n)| O(1)||
|876. Middle of the Linked List | [Go]({{< relref "/ChapterFour/0876.Middle-of-the-Linked-List.md" >}})| Easy | O(n)| O(1)|❤️|
|1019. Next Greater Node In Linked List | [Go]({{< relref "/ChapterFour/1019.Next-Greater-Node-In-Linked-List.md" >}})| Medium | O(n)| O(1)||

18
ctl/meta/Math Normal file
View File

@ -0,0 +1,18 @@
|2. Add Two Numbers | [Go]({{< relref "/ChapterFour/0002.Add-Two-Numbers.md" >}})| Medium | O(n)| O(1)||
|50. Pow(x, n) | [Go]({{< relref "/ChapterFour/0050.Powx-n.md" >}})| Medium | O(log n)| O(1)||
|60. Permutation Sequence | [Go]({{< relref "/ChapterFour/0060.Permutation-Sequence.md" >}})| Medium | O(n log n)| O(1)||
|69. Sqrt(x) | [Go]({{< relref "/ChapterFour/0069.Sqrtx.md" >}})| Easy | O(log n)| O(1)||
|202. Happy Number | [Go]({{< relref "/ChapterFour/0202.Happy-Number.md" >}})| Easy | O(log n)| O(1)||
|224. Basic Calculator | [Go]({{< relref "/ChapterFour/0224.Basic-Calculator.md" >}})| Hard | O(n)| O(n)||
|231. Power of Two | [Go]({{< relref "/ChapterFour/0231.Power-of-Two.md" >}})| Easy | O(1)| O(1)||
|263. Ugly Number | [Go]({{< relref "/ChapterFour/0263.Ugly-Number.md" >}})| Easy | O(log n)| O(1)||
|326. Power of Three | [Go]({{< relref "/ChapterFour/0326.Power-of-Three.md" >}})| Easy | O(1)| O(1)||
|343. Integer Break | [Go]({{< relref "/ChapterFour/0343.Integer-Break.md" >}})| Medium | O(n^2)| O(n)||
|357. Count Numbers with Unique Digits | [Go]({{< relref "/ChapterFour/0357.Count-Numbers-with-Unique-Digits.md" >}})| Medium | O(1)| O(1)||
|628. Maximum Product of Three Numbers | [Go]({{< relref "/ChapterFour/0628.Maximum-Product-of-Three-Numbers.md" >}})| Easy | O(n)| O(1)||
|885. Spiral Matrix III | [Go]({{< relref "/ChapterFour/0885.Spiral-Matrix-III.md" >}})| Medium | O(n^2)| O(1)||
|891. Sum of Subsequence Widths | [Go]({{< relref "/ChapterFour/0891.Sum-of-Subsequence-Widths.md" >}})| Hard | O(n log n)| O(1)||
|942. DI String Match | [Go]({{< relref "/ChapterFour/0942.DI-String-Match.md" >}})| Easy | O(n)| O(1)||
|976. Largest Perimeter Triangle | [Go]({{< relref "/ChapterFour/0976.Largest-Perimeter-Triangle.md" >}})| Easy | O(n log n)| O(log n) ||
|996. Number of Squareful Arrays | [Go]({{< relref "/ChapterFour/0996.Number-of-Squareful-Arrays.md" >}})| Hard | O(n log n)| O(n) ||
|1025. Divisor Game | [Go]({{< relref "/ChapterFour/1025.Divisor-Game.md" >}})| Easy | O(1)| O(1)||

12
ctl/meta/PDFPreface Normal file
View File

@ -0,0 +1,12 @@
<img src="https://books.halfrost.com/leetcode/logo.png" alt="logo" heigth="1300px" align="center"/>
# 说明
此版本是 https://books.halfrost.com/leetcode 网页的离线版,由于网页版实时会更新,所以此 PDF 版难免会有一些排版或者错别字。如果读者遇到了,可以到网页版相应页面,点击页面 edit 按钮,提交 pr 进行更改。此 PDF 版本号是 V1.5.20。PDF 永久更新地址是 https://github.com/halfrost/LeetCode-Go/releases/,以版本号区分不同版本。笔者还是强烈推荐看在线版,有任何错误都会立即更新。如果觉得此书对刷题有一点点帮助,可以给此书点一个 star鼓励一下笔者早点更新更多题解。
> 版本号说明V1.5.201 是大版本号5 代表当前题解中有几百题,目前是 520 题,所以第二个版本号是 520 代表当前题解中有几十题,目前是 520 题,所以第三个版本号是 20 。
# 目录
[toc]

10
ctl/meta/Segment_Tree Normal file
View File

@ -0,0 +1,10 @@
|218. The Skyline Problem | [Go]({{< relref "/ChapterFour/0218.The-Skyline-Problem.md" >}})| Hard | O(n log n)| O(n)|❤️|
|307. Range Sum Query - Mutable | [Go]({{< relref "/ChapterFour/0307.Range-Sum-Query---Mutable.md" >}})| Hard | O(1)| O(n)||
|315. Count of Smaller Numbers After Self | [Go]({{< relref "/ChapterFour/0315.Count-of-Smaller-Numbers-After-Self.md" >}})| Hard | O(n log n)| O(n)||
|327. Count of Range Sum | [Go]({{< relref "/ChapterFour/0327.Count-of-Range-Sum.md" >}})| Hard | O(n log n)| O(n)|❤️|
|493. Reverse Pairs | [Go]({{< relref "/ChapterFour/0493.Reverse-Pairs.md" >}})| Hard | O(n log n)| O(n)||
|699. Falling Squares | [Go]({{< relref "/ChapterFour/0699.Falling-Squares.md" >}})| Hard | O(n log n)| O(n)|❤️|
|715. Range Module | [Go]({{< relref "/ChapterFour/0715.Range-Module.md" >}})| Hard | O(log n)| O(n)|❤️|
|732. My Calendar III | [Go]({{< relref "/ChapterFour/0732.My-Calendar-III.md" >}})| Hard | O(log n)| O(n)|❤️|
|850. Rectangle Area II | [Go]({{< relref "/ChapterFour/0850.Rectangle-Area-II.md" >}})| Hard | O(n log n)| O(n)|❤️|
|1157. Online Majority Element In Subarray | [Go]({{< relref "/ChapterFour/1157.Online-Majority-Element-In-Subarray.md" >}})| Hard | O(log n)| O(n)|❤️|

13
ctl/meta/Sliding_Window Normal file
View File

@ -0,0 +1,13 @@
|3. Longest Substring Without Repeating Characters | [Go]({{< relref "/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md" >}})| Medium | O(n)| O(1)|❤️|
|76. Minimum Window Substring | [Go]({{< relref "/ChapterFour/0076.Minimum-Window-Substring.md" >}})| Hard | O(n)| O(n)|❤️|
|239. Sliding Window Maximum | [Go]({{< relref "/ChapterFour/0239.Sliding-Window-Maximum.md" >}})| Hard | O(n * k)| O(n)|❤️|
|424. Longest Repeating Character Replacement | [Go]({{< relref "/ChapterFour/0424.Longest-Repeating-Character-Replacement.md" >}})| Medium | O(n)| O(1) ||
|480. Sliding Window Median | [Go]({{< relref "/ChapterFour/0480.Sliding-Window-Median.md" >}})| Hard | O(n * log k)| O(k)|❤️|
|567. Permutation in String | [Go]({{< relref "/ChapterFour/0567.Permutation-in-String.md" >}})| Medium | O(n)| O(1)|❤️|
|978. Longest Turbulent Subarray | [Go]({{< relref "/ChapterFour/0978.Longest-Turbulent-Subarray.md" >}})| Medium | O(n)| O(1)|❤️|
|992. Subarrays with K Different Integers | [Go]({{< relref "/ChapterFour/0992.Subarrays-with-K-Different-Integers.md" >}})| Hard | O(n)| O(n)|❤️|
|995. Minimum Number of K Consecutive Bit Flips | [Go]({{< relref "/ChapterFour/0995.Minimum-Number-of-K-Consecutive-Bit-Flips.md" >}})| Hard | O(n)| O(1)|❤️|
|1004. Max Consecutive Ones III | [Go]({{< relref "/ChapterFour/1004.Max-Consecutive-Ones-III.md" >}})| Medium | O(n)| O(1) ||
|1040. Moving Stones Until Consecutive II | [Go]({{< relref "/ChapterFour/1040.Moving-Stones-Until-Consecutive-II.md" >}})| Medium | O(n log n)| O(1) |❤️|
|1052. Grumpy Bookstore Owner | [Go]({{< relref "/ChapterFour/1052.Grumpy-Bookstore-Owner.md" >}})| Medium | O(n log n)| O(1) ||
|1074. Number of Submatrices That Sum to Target | [Go]({{< relref "/ChapterFour/1074.Number-of-Submatrices-That-Sum-to-Target.md" >}})| Hard | O(n^3)| O(n) |❤️|

23
ctl/meta/Sort Normal file
View File

@ -0,0 +1,23 @@
|56. Merge Intervals | [Go]({{< relref "/ChapterFour/0056.Merge-Intervals.md" >}})| Medium | O(n log n)| O(log n)||
|57. Insert Interval | [Go]({{< relref "/ChapterFour/0057.Insert-Interval.md" >}})| Hard | O(n)| O(1)||
|75. Sort Colors | [Go]({{< relref "/ChapterFour/0075.Sort-Colors.md" >}})| Medium| O(n)| O(1)|❤️|
|147. Insertion Sort List | [Go]({{< relref "/ChapterFour/0147.Insertion-Sort-List.md" >}})| Medium | O(n)| O(1) |❤️|
|148. Sort List | [Go]({{< relref "/ChapterFour/0148.Sort-List.md" >}})| Medium |O(n log n)| O(log n)|❤️|
|164. Maximum Gap | [Go]({{< relref "/ChapterFour/0164.Maximum-Gap.md" >}})| Hard | O(n log n)| O(log n) |❤️|
|179. Largest Number | [Go]({{< relref "/ChapterFour/0179.Largest-Number.md" >}})| Medium | O(n log n)| O(log n) |❤️|
|220. Contains Duplicate III | [Go]({{< relref "/ChapterFour/0220.Contains-Duplicate-III.md" >}})| Medium | O(n log n)| O(1) |❤️|
|242. Valid Anagram | [Go]({{< relref "/ChapterFour/0242.Valid-Anagram.md" >}})| Easy | O(n)| O(n) ||
|274. H-Index | [Go]({{< relref "/ChapterFour/0274.H-Index.md" >}})| Medium | O(n)| O(n) ||
|324. Wiggle Sort II | [Go]({{< relref "/ChapterFour/0324.Wiggle-Sort-II.md" >}})| Medium| O(n)| O(n)|❤️|
|349. Intersection of Two Arrays | [Go]({{< relref "/ChapterFour/0349.Intersection-of-Two-Arrays.md" >}})| Easy | O(n)| O(n) ||
|350. Intersection of Two Arrays II | [Go]({{< relref "/ChapterFour/0350.Intersection-of-Two-Arrays-II.md" >}})| Easy | O(n)| O(n) ||
|524. Longest Word in Dictionary through Deleting | [Go]({{< relref "/ChapterFour/0524.Longest-Word-in-Dictionary-through-Deleting.md" >}})| Medium | O(n)| O(1) ||
|767. Reorganize String | [Go]({{< relref "/ChapterFour/0767.Reorganize-String.md" >}})| Medium | O(n log n)| O(log n) |❤️|
|853. Car Fleet | [Go]({{< relref "/ChapterFour/0853.Car-Fleet.md" >}})| Medium | O(n log n)| O(log n) ||
|710. Random Pick with Blacklist | [Go]({{< relref "/ChapterFour/0710.Random-Pick-with-Blacklist.md" >}})| Hard | O(n)| O(n) ||
|922. Sort Array By Parity II | [Go]({{< relref "/ChapterFour/0922.Sort-Array-By-Parity-II.md" >}})| Easy | O(n)| O(1) ||
|969. Pancake Sorting | [Go]({{< relref "/ChapterFour/0969.Pancake-Sorting.md" >}})| Medium | O(n log n)| O(log n) |❤️|
|973. K Closest Points to Origin | [Go]({{< relref "/ChapterFour/0973.K-Closest-Points-to-Origin.md" >}})| Medium | O(n log n)| O(log n) ||
|976. Largest Perimeter Triangle | [Go]({{< relref "/ChapterFour/0976.Largest-Perimeter-Triangle.md" >}})| Easy | O(n log n)| O(log n) ||
|1030. Matrix Cells in Distance Order | [Go]({{< relref "/ChapterFour/1030.Matrix-Cells-in-Distance-Order.md" >}})| Easy | O(n^2)| O(1) ||
|1054. Distant Barcodes | [Go]({{< relref "/ChapterFour/1054.Distant-Barcodes.md" >}})| Medium | O(n log n)| O(log n) |❤️|

37
ctl/meta/Stack Normal file
View File

@ -0,0 +1,37 @@
|20. Valid Parentheses | [Go]({{< relref "/ChapterFour/0020.Valid-Parentheses.md" >}})| Easy | O(log n)| O(1)||
|42. Trapping Rain Water | [Go]({{< relref "/ChapterFour/0042.Trapping-Rain-Water.md" >}})| Hard | O(n)| O(1)|❤️|
|71. Simplify Path | [Go]({{< relref "/ChapterFour/0071.Simplify-Path.md" >}})| Medium | O(n)| O(n)|❤️|
|84. Largest Rectangle in Histogram | [Go]({{< relref "/ChapterFour/0084.Largest-Rectangle-in-Histogram.md" >}})| Medium | O(n)| O(n)|❤️|
|94. Binary Tree Inorder Traversal | [Go]({{< relref "/ChapterFour/0094.Binary-Tree-Inorder-Traversal.md" >}})| Medium | O(n)| O(1)||
|103. Binary Tree Zigzag Level Order Traversal | [Go]({{< relref "/ChapterFour/0103.Binary-Tree-Zigzag-Level-Order-Traversal.md" >}})| Medium | O(n)| O(n)||
|144. Binary Tree Preorder Traversal | [Go]({{< relref "/ChapterFour/0144.Binary-Tree-Preorder-Traversal.md" >}})| Medium | O(n)| O(1)||
|145. Binary Tree Postorder Traversal | [Go]({{< relref "/ChapterFour/0145.Binary-Tree-Postorder-Traversal.md" >}})| Hard | O(n)| O(1)||
|150. Evaluate Reverse Polish Notation | [Go]({{< relref "/ChapterFour/0150.Evaluate-Reverse-Polish-Notation.md" >}})| Medium | O(n)| O(1)||
|155. Min Stack | [Go]({{< relref "/ChapterFour/0155.Min-Stack.md" >}})| Easy | O(n)| O(n)||
|173. Binary Search Tree Iterator | [Go]({{< relref "/ChapterFour/0173.Binary-Search-Tree-Iterator.md" >}})| Medium | O(n)| O(1)||
|224. Basic Calculator | [Go]({{< relref "/ChapterFour/0224.Basic-Calculator.md" >}})| Hard | O(n)| O(n)||
|225. Implement Stack using Queues | [Go]({{< relref "/ChapterFour/0225.Implement-Stack-using-Queues.md" >}})| Easy | O(n)| O(n)||
|232. Implement Queue using Stacks | [Go]({{< relref "/ChapterFour/0232.Implement-Queue-using-Stacks.md" >}})| Easy | O(n)| O(n)||
|331. Verify Preorder Serialization of a Binary Tree | [Go]({{< relref "/ChapterFour/0331.Verify-Preorder-Serialization-of-a-Binary-Tree.md" >}})| Medium | O(n)| O(1)||
|394. Decode String | [Go]({{< relref "/ChapterFour/0394.Decode-String.md" >}})| Medium | O(n)| O(n)||
|402. Remove K Digits | [Go]({{< relref "/ChapterFour/0402.Remove-K-Digits.md" >}})| Medium | O(n)| O(1)||
|456. 132 Pattern | [Go]({{< relref "/ChapterFour/0456.132-Pattern.md" >}})| Medium | O(n)| O(n)||
|496. Next Greater Element I | [Go]({{< relref "/ChapterFour/0496.Next-Greater-Element-I.md" >}})| Easy | O(n)| O(n)||
|503. Next Greater Element II | [Go]({{< relref "/ChapterFour/0503.Next-Greater-Element-II.md" >}})| Medium | O(n)| O(n)||
|636. Exclusive Time of Functions | [Go]({{< relref "/ChapterFour/0636.Exclusive-Time-of-Functions.md" >}})| Medium | O(n)| O(n)||
|682. Baseball Game | [Go]({{< relref "/ChapterFour/0682.Baseball-Game.md" >}})| Easy | O(n)| O(n)||
|726. Number of Atoms | [Go]({{< relref "/ChapterFour/0726.Number-of-Atoms.md" >}})| Hard | O(n)| O(n) |❤️|
|735. Asteroid Collision | [Go]({{< relref "/ChapterFour/0735.Asteroid-Collision.md" >}})| Medium | O(n)| O(n) ||
|739. Daily Temperatures | [Go]({{< relref "/ChapterFour/0739.Daily-Temperatures.md" >}})| Medium | O(n)| O(n) ||
|844. Backspace String Compare | [Go]({{< relref "/ChapterFour/0844.Backspace-String-Compare.md" >}})| Easy | O(n)| O(n) ||
|856. Score of Parentheses | [Go]({{< relref "/ChapterFour/0856.Score-of-Parentheses.md" >}})| Medium | O(n)| O(n)||
|880. Decoded String at Index | [Go]({{< relref "/ChapterFour/0880.Decoded-String-at-Index.md" >}})| Medium | O(n)| O(n)||
|895. Maximum Frequency Stack | [Go]({{< relref "/ChapterFour/0895.Maximum-Frequency-Stack.md" >}})| Hard | O(n)| O(n) ||
|901. Online Stock Span | [Go]({{< relref "/ChapterFour/0901.Online-Stock-Span.md" >}})| Medium | O(n)| O(n) ||
|907. Sum of Subarray Minimums | [Go]({{< relref "/ChapterFour/0907.Sum-of-Subarray-Minimums.md" >}})| Medium | O(n)| O(n)|❤️|
|921. Minimum Add to Make Parentheses Valid | [Go]({{< relref "/ChapterFour/0921.Minimum-Add-to-Make-Parentheses-Valid.md" >}})| Medium | O(n)| O(n)||
|946. Validate Stack Sequences | [Go]({{< relref "/ChapterFour/0946.Validate-Stack-Sequences.md" >}})| Medium | O(n)| O(n)||
|1003. Check If Word Is Valid After Substitutions | [Go]({{< relref "/ChapterFour/1003.Check-If-Word-Is-Valid-After-Substitutions.md" >}})| Medium | O(n)| O(1)||
|1019. Next Greater Node In Linked List | [Go]({{< relref "/ChapterFour/1019.Next-Greater-Node-In-Linked-List.md" >}})| Medium | O(n)| O(1)||
|1021. Remove Outermost Parentheses | [Go]({{< relref "/ChapterFour/1021.Remove-Outermost-Parentheses.md" >}})| Medium | O(n)| O(1)||
|1047. Remove All Adjacent Duplicates In String | [Go]({{< relref "/ChapterFour/1047.Remove-All-Adjacent-Duplicates-In-String.md" >}})| Medium | O(n)| O(1)||

20
ctl/meta/String Normal file
View File

@ -0,0 +1,20 @@
|3. Longest Substring Without Repeating Characters | [Go]({{< relref "/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md" >}})| Medium | O(n)| O(1)|❤️|
|17. Letter Combinations of a Phone Number | [Go]({{< relref "/ChapterFour/0017.Letter-Combinations-of-a-Phone-Number.md" >}})| Medium | O(log n)| O(1)||
|20. Valid Parentheses | [Go]({{< relref "/ChapterFour/0020.Valid-Parentheses.md" >}})| Easy | O(log n)| O(1)||
|22. Generate Parentheses | [Go]({{< relref "/ChapterFour/0022.Generate-Parentheses.md" >}})| Medium | O(log n)| O(1)||
|28. Implement strStr() | [Go]({{< relref "/ChapterFour/0028.Implement-strStr.md" >}})| Easy | O(n)| O(1)||
|30. Substring with Concatenation of All Words | [Go]({{< relref "/ChapterFour/0030.Substring-with-Concatenation-of-All-Words.md" >}})| Hard | O(n)| O(n)|❤️|
|49. Group Anagrams | [Go]({{< relref "/ChapterFour/0049.Group-Anagrams.md" >}})| Medium | O(n log n)| O(n)||
|71. Simplify Path | [Go]({{< relref "/ChapterFour/0071.Simplify-Path.md" >}})| Medium | O(n)| O(n)||
|76. Minimum Window Substring | [Go]({{< relref "/ChapterFour/0076.Minimum-Window-Substring.md" >}})| Hard | O(n)| O(n)|❤️|
|91. Decode Ways | [Go]({{< relref "/ChapterFour/0091.Decode-Ways.md" >}})| Medium | O(n)| O(n)||
|93. Restore IP Addresses | [Go]({{< relref "/ChapterFour/0093.Restore-IP-Addresses.md" >}})| Medium | O(n)| O(n)|❤️|
|125. Valid Palindrome | [Go]({{< relref "/ChapterFour/0125.Valid-Palindrome.md" >}})| Easy | O(n)| O(1)||
|126. Word Ladder II | [Go]({{< relref "/ChapterFour/0126.Word-Ladder-II.md" >}})| Hard | O(n)| O(n^2)|❤️|
|344. Reverse String | [Go]({{< relref "/ChapterFour/0344.Reverse-String.md" >}})| Easy | O(n)| O(1)||
|345. Reverse Vowels of a String | [Go]({{< relref "/ChapterFour/0345.Reverse-Vowels-of-a-String.md" >}})| Easy | O(n)| O(1)||
|767. Reorganize String | [Go]({{< relref "/ChapterFour/0767.Reorganize-String.md" >}})| Medium | O(n log n)| O(log n) |❤️|
|842. Split Array into Fibonacci Sequence | [Go]({{< relref "/ChapterFour/0842.Split-Array-into-Fibonacci-Sequence.md" >}})| Medium | O(n^2)| O(1)|❤️|
|856. Score of Parentheses | [Go]({{< relref "/ChapterFour/0856.Score-of-Parentheses.md" >}})| Medium | O(n)| O(n)||
|925. Long Pressed Name | [Go]({{< relref "/ChapterFour/0925.Long-Pressed-Name.md" >}})| Easy | O(n)| O(1)||
|1003. Check If Word Is Valid After Substitutions | [Go]({{< relref "/ChapterFour/1003.Check-If-Word-Is-Valid-After-Substitutions.md" >}})| Medium | O(n)| O(1)||

33
ctl/meta/Tree Normal file
View File

@ -0,0 +1,33 @@
|94. Binary Tree Inorder Traversal | [Go]({{< relref "/ChapterFour/0094.Binary-Tree-Inorder-Traversal.md" >}})| Medium | O(n)| O(1)||
|96. Unique Binary Search Trees | [Go]({{< relref "/ChapterFour/0096.Unique-Binary-Search-Trees.md" >}})| Medium | O(n^2)| O(n)||
|98. Validate Binary Search Tree | [Go]({{< relref "/ChapterFour/0098.Validate-Binary-Search-Tree.md" >}})| Medium | O(n)| O(1)||
|99. Recover Binary Search Tree | [Go]({{< relref "/ChapterFour/0099.Recover-Binary-Search-Tree.md" >}})| Hard | O(n)| O(1)||
|100. Same Tree | [Go]({{< relref "/ChapterFour/0100.Same-Tree.md" >}})| Easy | O(n)| O(1)||
|101. Symmetric Tree | [Go]({{< relref "/ChapterFour/0101.Symmetric-Tree.md" >}})| Easy | O(n)| O(1)||
|102. Binary Tree Level Order Traversal | [Go]({{< relref "/ChapterFour/0102.Binary-Tree-Level-Order-Traversal.md" >}})| Medium | O(n)| O(1)||
|103. Binary Tree Zigzag Level Order Traversal | [Go]({{< relref "/ChapterFour/0103.Binary-Tree-Zigzag-Level-Order-Traversal.md" >}})| Medium | O(n)| O(n)||
|104. Maximum Depth of Binary Tree | [Go]({{< relref "/ChapterFour/0104.Maximum-Depth-of-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|107. Binary Tree Level Order Traversal II | [Go]({{< relref "/ChapterFour/0107.Binary-Tree-Level-Order-Traversal-II.md" >}})| Easy | O(n)| O(1)||
|108. Convert Sorted Array to Binary Search Tree | [Go]({{< relref "/ChapterFour/0108.Convert-Sorted-Array-to-Binary-Search-Tree.md" >}})| Easy | O(n)| O(1)||
|110. Balanced Binary Tree | [Go]({{< relref "/ChapterFour/0110.Balanced-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|111. Minimum Depth of Binary Tree | [Go]({{< relref "/ChapterFour/0111.Minimum-Depth-of-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|112. Path Sum | [Go]({{< relref "/ChapterFour/0112.Path-Sum.md" >}})| Easy | O(n)| O(1)||
|113. Path Sum II | [Go]({{< relref "/ChapterFour/0113.Path-Sum-II.md" >}})| Medium | O(n)| O(1)||
|114. Flatten Binary Tree to Linked List | [Go]({{< relref "/ChapterFour/0114.Flatten-Binary-Tree-to-Linked-List.md" >}})| Medium | O(n)| O(1)||
|124. Binary Tree Maximum Path Sum | [Go]({{< relref "/ChapterFour/0124.Binary-Tree-Maximum-Path-Sum.md" >}})| Hard | O(n)| O(1)||
|129. Sum Root to Leaf Numbers | [Go]({{< relref "/ChapterFour/0129.Sum-Root-to-Leaf-Numbers.md" >}})| Medium | O(n)| O(1)||
|144. Binary Tree Preorder Traversal | [Go]({{< relref "/ChapterFour/0144.Binary-Tree-Preorder-Traversal.md" >}})| Medium | O(n)| O(1)||
|145. Binary Tree Postorder Traversal | [Go]({{< relref "/ChapterFour/0145.Binary-Tree-Postorder-Traversal.md" >}})| Hard | O(n)| O(1)||
|173. Binary Search Tree Iterator | [Go]({{< relref "/ChapterFour/0173.Binary-Search-Tree-Iterator.md" >}})| Medium | O(n)| O(1)||
|199. Binary Tree Right Side View | [Go]({{< relref "/ChapterFour/0199.Binary-Tree-Right-Side-View.md" >}})| Medium | O(n)| O(1)||
|222. Count Complete Tree Nodes | [Go]({{< relref "/ChapterFour/0222.Count-Complete-Tree-Nodes.md" >}})| Medium | O(n)| O(1)||
|226. Invert Binary Tree | [Go]({{< relref "/ChapterFour/0226.Invert-Binary-Tree.md" >}})| Easy | O(n)| O(1)||
|230. Kth Smallest Element in a BST | [Go]({{< relref "/ChapterFour/0230.Kth-Smallest-Element-in-a-BST.md" >}})| Medium | O(n)| O(1)||
|235. Lowest Common Ancestor of a Binary Search Tree | [Go]({{< relref "/ChapterFour/0235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree.md" >}})| Easy | O(n)| O(1)||
|236. Lowest Common Ancestor of a Binary Tree | [Go]({{< relref "/ChapterFour/0236.Lowest-Common-Ancestor-of-a-Binary-Tree.md" >}})| Medium | O(n)| O(1)||
|257. Binary Tree Paths | [Go]({{< relref "/ChapterFour/0257.Binary-Tree-Paths.md" >}})| Easy | O(n)| O(1)||
|404. Sum of Left Leaves | [Go]({{< relref "/ChapterFour/0404.Sum-of-Left-Leaves.md" >}})| Easy | O(n)| O(1)||
|437. Path Sum III | [Go]({{< relref "/ChapterFour/0437.Path-Sum-III.md" >}})| Easy | O(n)| O(1)||
|515. Find Largest Value in Each Tree Row | [Go]({{< relref "/ChapterFour/0515.Find-Largest-Value-in-Each-Tree-Row.md" >}})| Medium | O(n)| O(n)||
|637. Average of Levels in Binary Tree | [Go]({{< relref "/ChapterFour/0637.Average-of-Levels-in-Binary-Tree.md" >}})| Easy | O(n)| O(n)||
|993. Cousins in Binary Tree | [Go]({{< relref "/ChapterFour/0993.Cousins-in-Binary-Tree.md" >}})| Easy | O(n)| O(1)||

50
ctl/meta/Two_Pointers Normal file
View File

@ -0,0 +1,50 @@
|3. Longest Substring Without Repeating Characters | [Go]({{< relref "/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md" >}})| Medium | O(n)| O(1)|❤️|
|11. Container With Most Water | [Go]({{< relref "/ChapterFour/0011.Container-With-Most-Water.md" >}})| Medium | O(n)| O(1)||
|15. 3Sum | [Go]({{< relref "/ChapterFour/0015.3Sum.md" >}})| Medium | O(n^2)| O(n)|❤️|
|16. 3Sum Closest | [Go]({{< relref "/ChapterFour/0016.3Sum-Closest.md" >}})| Medium | O(n^2)| O(1)|❤️|
|18. 4Sum | [Go]({{< relref "/ChapterFour/0018.4Sum.md" >}})| Medium | O(n^3)| O(n^2)|❤️|
|19. Remove Nth Node From End of List | [Go]({{< relref "/ChapterFour/0019.Remove-Nth-Node-From-End-of-List.md" >}})| Medium | O(n)| O(1)||
|26. Remove Duplicates from Sorted Array | [Go]({{< relref "/ChapterFour/0026.Remove-Duplicates-from-Sorted-Array.md" >}})| Easy | O(n)| O(1)||
|27. Remove Element | [Go]({{< relref "/ChapterFour/0027.Remove-Element.md" >}})| Easy | O(n)| O(1)||
|28. Implement strStr() | [Go]({{< relref "/ChapterFour/0028.Implement-strStr.md" >}})| Easy | O(n)| O(1)||
|30. Substring with Concatenation of All Words | [Go]({{< relref "/ChapterFour/0030.Substring-with-Concatenation-of-All-Words.md" >}})| Hard | O(n)| O(n)|❤️|
|42. Trapping Rain Water | [Go]({{< relref "/ChapterFour/0042.Trapping-Rain-Water.md" >}})| Hard | O(n)| O(1)|❤️|
|61. Rotate List | [Go]({{< relref "/ChapterFour/0061.Rotate-List.md" >}})| Medium | O(n)| O(1)||
|75. Sort Colors | [Go]({{< relref "/ChapterFour/0075.Sort-Colors.md" >}})| Medium| O(n)| O(1)|❤️|
|76. Minimum Window Substring | [Go]({{< relref "/ChapterFour/0076.Minimum-Window-Substring.md" >}})| Hard | O(n)| O(n)|❤️|
|80. Remove Duplicates from Sorted Array II | [Go]({{< relref "/ChapterFour/0080.Remove-Duplicates-from-Sorted-Array-II.md" >}})| Medium | O(n)| O(1||
|86. Partition List | [Go]({{< relref "/ChapterFour/0086.Partition-List.md" >}})| Medium | O(n)| O(1)|❤️|
|88. Merge Sorted Array | [Go]({{< relref "/ChapterFour/0088.Merge-Sorted-Array.md" >}})| Easy | O(n)| O(1)|❤️|
|125. Valid Palindrome | [Go]({{< relref "/ChapterFour/0125.Valid-Palindrome.md" >}})| Easy | O(n)| O(1)||
|141. Linked List Cycle | [Go]({{< relref "/ChapterFour/0141.Linked-List-Cycle.md" >}})| Easy | O(n)| O(1)|❤️|
|142. Linked List Cycle II | [Go]({{< relref "/ChapterFour/0142.Linked-List-Cycle-II.md" >}})| Medium | O(n)| O(1)|❤️|
|167. Two Sum II - Input array is sorted | [Go]({{< relref "/ChapterFour/0167.Two-Sum-II---Input-array-is-sorted.md" >}})| Easy | O(n)| O(1)||
|209. Minimum Size Subarray Sum | [Go]({{< relref "/ChapterFour/0209.Minimum-Size-Subarray-Sum.md" >}})| Medium | O(n)| O(1)||
|234. Palindrome Linked List | [Go]({{< relref "/ChapterFour/0234.Palindrome-Linked-List.md" >}})| Easy | O(n)| O(1)||
|283. Move Zeroes | [Go]({{< relref "/ChapterFour/0283.Move-Zeroes.md" >}})| Easy | O(n)| O(1)||
|287. Find the Duplicate Number | [Go]({{< relref "/ChapterFour/0287.Find-the-Duplicate-Number.md" >}})| Easy | O(n)| O(1)|❤️|
|344. Reverse String | [Go]({{< relref "/ChapterFour/0344.Reverse-String.md" >}})| Easy | O(n)| O(1)||
|345. Reverse Vowels of a String | [Go]({{< relref "/ChapterFour/0345.Reverse-Vowels-of-a-String.md" >}})| Easy | O(n)| O(1)||
|349. Intersection of Two Arrays | [Go]({{< relref "/ChapterFour/0349.Intersection-of-Two-Arrays.md" >}})| Easy | O(n)| O(n) ||
|350. Intersection of Two Arrays II | [Go]({{< relref "/ChapterFour/0350.Intersection-of-Two-Arrays-II.md" >}})| Easy | O(n)| O(n) ||
|424. Longest Repeating Character Replacement | [Go]({{< relref "/ChapterFour/0424.Longest-Repeating-Character-Replacement.md" >}})| Medium | O(n)| O(1) ||
|524. Longest Word in Dictionary through Deleting | [Go]({{< relref "/ChapterFour/0524.Longest-Word-in-Dictionary-through-Deleting.md" >}})| Medium | O(n)| O(1) ||
|532. K-diff Pairs in an Array | [Go]({{< relref "/ChapterFour/0532.K-diff-Pairs-in-an-Array.md" >}})| Easy | O(n)| O(n)||
|567. Permutation in String | [Go]({{< relref "/ChapterFour/0567.Permutation-in-String.md" >}})| Medium | O(n)| O(1)|❤️|
|713. Subarray Product Less Than K | [Go]({{< relref "/ChapterFour/0713.Subarray-Product-Less-Than-K.md" >}})| Medium | O(n)| O(1)||
|763. Partition Labels | [Go]({{< relref "/ChapterFour/0763.Partition-Labels.md" >}})| Medium | O(n)| O(1)|❤️|
|826. Most Profit Assigning Work | [Go]({{< relref "/ChapterFour/0826.Most-Profit-Assigning-Work.md" >}})| Medium | O(n log n)| O(n)||
|828. Count Unique Characters of All Substrings of a Given String | [Go]({{< relref "/ChapterFour/0828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.md" >}})| Hard | O(n)| O(1)|❤️|
|838. Push Dominoes | [Go]({{< relref "/ChapterFour/0838.Push-Dominoes.md" >}})| Medium | O(n)| O(n)||
|844. Backspace String Compare | [Go]({{< relref "/ChapterFour/0844.Backspace-String-Compare.md" >}})| Easy | O(n)| O(n) ||
|845. Longest Mountain in Array | [Go]({{< relref "/ChapterFour/0845.Longest-Mountain-in-Array.md" >}})| Medium | O(n)| O(1) ||
|881. Boats to Save People | [Go]({{< relref "/ChapterFour/0881.Boats-to-Save-People.md" >}})| Medium | O(n log n)| O(1) ||
|904. Fruit Into Baskets | [Go]({{< relref "/ChapterFour/0904.Fruit-Into-Baskets.md" >}})| Medium | O(n log n)| O(1) ||
|923. 3Sum With Multiplicity | [Go]({{< relref "/ChapterFour/0923.3Sum-With-Multiplicity.md" >}})| Medium | O(n^2)| O(n) ||
|925. Long Pressed Name | [Go]({{< relref "/ChapterFour/0925.Long-Pressed-Name.md" >}})| Easy | O(n)| O(1)||
|930. Binary Subarrays With Sum | [Go]({{< relref "/ChapterFour/0930.Binary-Subarrays-With-Sum.md" >}})| Medium | O(n)| O(n) |❤️|
|977. Squares of a Sorted Array | [Go]({{< relref "/ChapterFour/0977.Squares-of-a-Sorted-Array.md" >}})| Easy | O(n)| O(1)||
|986. Interval List Intersections | [Go]({{< relref "/ChapterFour/0986.Interval-List-Intersections.md" >}})| Medium | O(n)| O(1)||
|992. Subarrays with K Different Integers | [Go]({{< relref "/ChapterFour/0992.Subarrays-with-K-Different-Integers.md" >}})| Hard | O(n)| O(n)|❤️|
|1004. Max Consecutive Ones III | [Go]({{< relref "/ChapterFour/1004.Max-Consecutive-Ones-III.md" >}})| Medium | O(n)| O(1) ||
|1093. Statistics from a Large Sample | [Go]({{< relref "/ChapterFour/1093.Statistics-from-a-Large-Sample.md" >}})| Medium | O(n)| O(1) ||

18
ctl/meta/Union_Find Normal file
View File

@ -0,0 +1,18 @@
|128. Longest Consecutive Sequence | [Go]({{< relref "/ChapterFour/0128.Longest-Consecutive-Sequence.md" >}})| Hard | O(n)| O(n)|❤️|
|130. Surrounded Regions | [Go]({{< relref "/ChapterFour/0130.Surrounded-Regions.md" >}})| Medium | O(m\*n)| O(m\*n)||
|200. Number of Islands | [Go]({{< relref "/ChapterFour/0200.Number-of-Islands.md" >}})| Medium | O(m\*n)| O(m\*n)||
|399. Evaluate Division | [Go]({{< relref "/ChapterFour/0399.Evaluate-Division.md" >}})| Medium | O(n)| O(n)||
|547. Number of Provinces | [Go]({{< relref "/ChapterFour/0547.Number-of-Provinces.md" >}})| Medium | O(n^2)| O(n)||
|684. Redundant Connection | [Go]({{< relref "/ChapterFour/0684.Redundant-Connection.md" >}})| Medium | O(n)| O(n)||
|685. Redundant Connection II | [Go]({{< relref "/ChapterFour/0685.Redundant-Connection-II.md" >}})| Hard | O(n)| O(n)||
|721. Accounts Merge | [Go]({{< relref "/ChapterFour/0721.Accounts-Merge.md" >}})| Medium | O(n)| O(n)|❤️|
|765. Couples Holding Hands | [Go]({{< relref "/ChapterFour/0765.Couples-Holding-Hands.md" >}})| Hard | O(n)| O(n)|❤️|
|778. Swim in Rising Water | [Go]({{< relref "/ChapterFour/0778.Swim-in-Rising-Water.md" >}})| Hard | O(n^2)| O(n)|❤️|
|803. Bricks Falling When Hit | [Go]({{< relref "/ChapterFour/0803.Bricks-Falling-When-Hit.md" >}})| Hard | O(n^2)| O(n)|❤️|
|839. Similar String Groups | [Go]({{< relref "/ChapterFour/0839.Similar-String-Groups.md" >}})| Hard | O(n^2)| O(n)||
|924. Minimize Malware Spread | [Go]({{< relref "/ChapterFour/0924.Minimize-Malware-Spread.md" >}})| Hard | O(m\*n)| O(n)||
|928. Minimize Malware Spread II | [Go]({{< relref "/ChapterFour/0928.Minimize-Malware-Spread-II.md" >}})| Hard | O(m\*n)| O(n)|❤️|
|947. Most Stones Removed with Same Row or Column | [Go]({{< relref "/ChapterFour/0947.Most-Stones-Removed-with-Same-Row-or-Column.md" >}})| Medium | O(n)| O(n)||
|952. Largest Component Size by Common Factor | [Go]({{< relref "/ChapterFour/0952.Largest-Component-Size-by-Common-Factor.md" >}})| Hard | O(n)| O(n)|❤️|
|959. Regions Cut By Slashes | [Go]({{< relref "/ChapterFour/0959.Regions-Cut-By-Slashes.md" >}})| Medium | O(n^2)| O(n^2)|❤️|
|990. Satisfiability of Equality Equations | [Go]({{< relref "/ChapterFour/0990.Satisfiability-of-Equality-Equations.md" >}})| Medium | O(n)| O(n)||

2
ctl/meta/meta Normal file
View File

@ -0,0 +1,2 @@
| Title | Solution | Difficulty | Time | Space |收藏|
| ----- | :--------: | :----------: | :----: | :-----: | :-----: |

104
ctl/models/lcproblems.go Normal file
View File

@ -0,0 +1,104 @@
package models
import (
"fmt"
"strings"
)
// LeetCodeProblemAll define
type LeetCodeProblemAll struct {
UserName string `json:"user_name"`
NumSolved int32 `json:"num_solved"`
NumTotal int32 `json:"num_total"`
AcEasy int32 `json:"ac_easy"`
AcMedium int32 `json:"ac_medium"`
AcHard int32 `json:"ac_hard"`
StatStatusPairs []StatStatusPairs `json:"stat_status_pairs"`
FrequencyHigh int32 `json:"frequency_high"`
FrequencyMid int32 `json:"frequency_mid"`
CategorySlug string `json:"category_slug"`
AcEasyTotal int32
AcMediumTotal int32
AcHardTotal int32
}
// ConvertUserInfoModel define
func ConvertUserInfoModel(lpa LeetCodeProblemAll) UserInfo {
info := UserInfo{}
info.UserName = lpa.UserName
info.NumSolved = lpa.NumSolved
info.NumTotal = lpa.NumTotal
info.AcEasy = lpa.AcEasy
info.AcMedium = lpa.AcMedium
info.AcHard = lpa.AcHard
info.FrequencyHigh = lpa.FrequencyHigh
info.FrequencyMid = lpa.FrequencyMid
info.CategorySlug = lpa.CategorySlug
return info
}
// StatStatusPairs define
type StatStatusPairs struct {
Stat Stat `json:"stat"`
Status string `json:"status"`
Difficulty Difficulty `json:"difficulty"`
PaidOnly bool `json:"paid_only"`
IsFavor bool `json:"is_favor"`
Frequency float64 `json:"frequency"`
Progress float64 `json:"progress"`
}
// ConvertMdModelFromSsp define
func ConvertMdModelFromSsp(problems []StatStatusPairs) []Mdrow {
mdrows := []Mdrow{}
for _, problem := range problems {
res := Mdrow{}
res.FrontendQuestionID = problem.Stat.FrontendQuestionID
res.QuestionTitle = strings.TrimSpace(problem.Stat.QuestionTitle)
res.QuestionTitleSlug = strings.TrimSpace(problem.Stat.QuestionTitleSlug)
res.Acceptance = fmt.Sprintf("%.1f%%", (problem.Stat.TotalAcs/problem.Stat.TotalSubmitted)*100)
res.Difficulty = DifficultyMap[problem.Difficulty.Level]
res.Frequency = fmt.Sprintf("%f", problem.Frequency)
mdrows = append(mdrows, res)
}
return mdrows
}
// ConvertMdModelFromIds define
func ConvertMdModelFromIds(problemsMap map[int]StatStatusPairs, ids []int) []Mdrow {
mdrows := []Mdrow{}
for _, v := range ids {
res, problem := Mdrow{}, problemsMap[v]
res.FrontendQuestionID = problem.Stat.FrontendQuestionID
res.QuestionTitle = strings.TrimSpace(problem.Stat.QuestionTitle)
res.QuestionTitleSlug = strings.TrimSpace(problem.Stat.QuestionTitleSlug)
res.Acceptance = fmt.Sprintf("%.1f%%", (problem.Stat.TotalAcs/problem.Stat.TotalSubmitted)*100)
res.Difficulty = DifficultyMap[problem.Difficulty.Level]
res.Frequency = fmt.Sprintf("%f", problem.Frequency)
mdrows = append(mdrows, res)
}
return mdrows
}
// Stat define
type Stat struct {
QuestionTitle string `json:"question__title"`
QuestionTitleSlug string `json:"question__title_slug"`
TotalAcs float64 `json:"total_acs"`
TotalSubmitted float64 `json:"total_submitted"`
Acceptance string
Difficulty string
FrontendQuestionID int32 `json:"frontend_question_id"`
}
// Difficulty define
type Difficulty struct {
Level int32 `json:"level"`
}
// DifficultyMap define
var DifficultyMap = map[int32]string{
1: "Easy",
2: "Medium",
3: "Hard",
}

67
ctl/models/mdrow.go Normal file
View File

@ -0,0 +1,67 @@
package models
import (
"fmt"
"strings"
)
// Mdrow define
type Mdrow struct {
FrontendQuestionID int32 `json:"question_id"`
QuestionTitle string `json:"question__title"`
QuestionTitleSlug string `json:"question__title_slug"`
SolutionPath string `json:"solution_path"`
Acceptance string `json:"acceptance"`
Difficulty string `json:"difficulty"`
Frequency string `json:"frequency"`
}
// GenerateMdRows define
func GenerateMdRows(solutionIds []int, mdrows []Mdrow) {
for i := 0; i < len(solutionIds); i++ {
id := mdrows[solutionIds[i]-1].FrontendQuestionID
if solutionIds[i] == int(id) {
//fmt.Printf("id = %v i = %v solutionIds = %v\n", id, i, solutionIds[i])
mdrows[id-1].SolutionPath = fmt.Sprintf("[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/%v)", fmt.Sprintf("%04d.%v", id, strings.Replace(strings.TrimSpace(mdrows[id-1].QuestionTitle), " ", "-", -1)))
} else {
fmt.Printf("序号出错了 solutionIds = %v id = %v\n", solutionIds[i], id)
}
}
}
// | 0001 | Two Sum | [Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0001.Two-Sum)| 45.6% | Easy | |
func (m Mdrow) tableLine() string {
return fmt.Sprintf("|%04d|%v|%v|%v|%v||\n", m.FrontendQuestionID, m.QuestionTitle, m.SolutionPath, m.Acceptance, m.Difficulty)
}
// SortByQuestionID define
type SortByQuestionID []Mdrow
func (a SortByQuestionID) Len() int { return len(a) }
func (a SortByQuestionID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a SortByQuestionID) Less(i, j int) bool {
return a[i].FrontendQuestionID < a[j].FrontendQuestionID
}
// Mdrows define
type Mdrows struct {
Mdrows []Mdrow
}
// | No. | Title | Solution | Acceptance | Difficulty | Frequency |
// |:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:|
func (mds Mdrows) table() string {
res := "| No. | Title | Solution | Acceptance | Difficulty | Frequency |\n"
res += "|:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:|\n"
for _, p := range mds.Mdrows {
res += p.tableLine()
}
// 加这一行是为了撑开整个表格
res += "|------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------|"
return res
}
// AvailableTable define
func (mds Mdrows) AvailableTable() string {
return mds.table()
}

255
ctl/models/tagproblem.go Normal file
View File

@ -0,0 +1,255 @@
package models
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/halfrost/LeetCode-Go/ctl/util"
)
// Graphql define
type Graphql struct {
OperationName string `json:"operationName"`
Variables struct {
TitleSlug string `json:"titleSlug"`
} `json:"variables"`
Query string `json:"query"`
}
// GraphQLResp define
type GraphQLResp struct {
Data struct {
TopicTag TopicTag `json:"topicTag"`
FavoritesLists FavoritesLists `json:"favoritesLists"`
} `json:"data"`
}
// TopicTag define
type TopicTag struct {
Name string `json:"name"`
TranslatedName string `json:"translatedName"`
Slug string `json:"slug"`
Questions []Question `json:"questions"`
Frequencies float64 `json:"frequencies"`
Typename string `json:"__typename"`
}
// Question define
type Question struct {
Status string `json:"status"`
QuestionID string `json:"questionId"`
QuestionFrontendID string `json:"questionFrontendId"`
Title string `json:"title"`
TitleSlug string `json:"titleSlug"`
TranslatedTitle string `json:"translatedTitle"`
Stats string `json:"stats"`
Difficulty string `json:"difficulty"`
TopicTags []TopicTags `json:"topicTags"`
CompanyTags interface{} `json:"companyTags"`
Typename string `json:"__typename"`
}
// TopicTags define
type TopicTags struct {
Name string `json:"name"`
TranslatedName string `json:"translatedName"`
Slug string `json:"slug"`
Typename string `json:"__typename"`
}
func (q Question) generateTagStatus() (TagStatus, error) {
var ts TagStatus
err := json.Unmarshal([]byte(q.Stats), &ts)
if err != nil {
fmt.Println(err)
return ts, err
}
return ts, nil
}
// TagStatus define
type TagStatus struct {
TotalAccepted string `json:"totalAccepted"`
TotalSubmission string `json:"totalSubmission"`
TotalAcceptedRaw int32 `json:"totalAcceptedRaw"`
TotalSubmissionRaw int32 `json:"totalSubmissionRaw"`
AcRate string `json:"acRate"`
}
// ConvertMdModelFromQuestions define
func ConvertMdModelFromQuestions(questions []Question) []Mdrow {
mdrows := []Mdrow{}
for _, question := range questions {
res := Mdrow{}
v, _ := strconv.Atoi(question.QuestionFrontendID)
res.FrontendQuestionID = int32(v)
res.QuestionTitle = strings.TrimSpace(question.Title)
res.QuestionTitleSlug = strings.TrimSpace(question.TitleSlug)
q, err := question.generateTagStatus()
if err != nil {
fmt.Println(err)
}
res.Acceptance = q.AcRate
res.Difficulty = question.Difficulty
mdrows = append(mdrows, res)
}
return mdrows
}
// TagList define
type TagList struct {
FrontendQuestionID int32 `json:"question_id"`
QuestionTitle string `json:"question__title"`
SolutionPath string `json:"solution_path"`
Acceptance string `json:"acceptance"`
Difficulty string `json:"difficulty"`
TimeComplexity string `json:"time_complexity"`
SpaceComplexity string `json:"space_complexity"`
Favorite string `json:"favorite"`
}
// | 0001 | Two Sum | [Go]({{< relref "/ChapterFour/0001.Two-Sum.md" >}})| Easy | O(n)| O(n)|❤️|50%|
func (t TagList) tableLine() string {
return fmt.Sprintf("|%04d|%v|%v|%v|%v|%v|%v|%v|\n", t.FrontendQuestionID, t.QuestionTitle, t.SolutionPath, t.Difficulty, t.TimeComplexity, t.SpaceComplexity, t.Favorite, t.Acceptance)
}
// GenerateTagMdRows define
func GenerateTagMdRows(solutionIds []int, metaMap map[int]TagList, mdrows []Mdrow, internal bool) []TagList {
tl := []TagList{}
for _, row := range mdrows {
if util.BinarySearch(solutionIds, int(row.FrontendQuestionID)) != -1 {
tmp := TagList{}
tmp.FrontendQuestionID = row.FrontendQuestionID
tmp.QuestionTitle = strings.TrimSpace(row.QuestionTitle)
s1 := strings.Replace(tmp.QuestionTitle, " ", "-", -1)
s2 := strings.Replace(s1, "'", "", -1)
s3 := strings.Replace(s2, "%", "", -1)
s4 := strings.Replace(s3, "(", "", -1)
s5 := strings.Replace(s4, ")", "", -1)
s6 := strings.Replace(s5, ",", "", -1)
s7 := strings.Replace(s6, "?", "", -1)
if internal {
tmp.SolutionPath = fmt.Sprintf("[Go]({{< relref \"/ChapterFour/%v/%v.md\" >}})", util.GetChpaterFourFileNum(int(row.FrontendQuestionID)), fmt.Sprintf("%04d.%v", int(row.FrontendQuestionID), s7))
} else {
tmp.SolutionPath = fmt.Sprintf("[Go](https://books.halfrost.com/leetcode/ChapterFour/%v/%v)", util.GetChpaterFourFileNum(int(row.FrontendQuestionID)), fmt.Sprintf("%04d.%v", int(row.FrontendQuestionID), s7))
}
tmp.Acceptance = row.Acceptance
tmp.Difficulty = row.Difficulty
tmp.TimeComplexity = metaMap[int(row.FrontendQuestionID)].TimeComplexity
tmp.SpaceComplexity = metaMap[int(row.FrontendQuestionID)].SpaceComplexity
tmp.Favorite = metaMap[int(row.FrontendQuestionID)].Favorite
tl = append(tl, tmp)
}
}
return tl
}
// TagLists define
type TagLists struct {
TagLists []TagList
}
//| No. | Title | Solution | Difficulty | TimeComplexity | SpaceComplexity |Favorite| Acceptance |
//|:--------:|:------- | :--------: | :----------: | :----: | :-----: | :-----: |:-----: |
func (tls TagLists) table() string {
res := "| No. | Title | Solution | Difficulty | TimeComplexity | SpaceComplexity |Favorite| Acceptance |\n"
res += "|:--------:|:------- | :--------: | :----------: | :----: | :-----: | :-----: |:-----: |\n"
for _, p := range tls.TagLists {
res += p.tableLine()
}
// 加这一行是为了撑开整个表格
res += "|------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------|-------------|-------------|"
return res
}
// AvailableTagTable define
func (tls TagLists) AvailableTagTable() string {
return tls.table()
}
// FavoritesLists define
type FavoritesLists struct {
PublicFavorites []int `json:"publicFavorites"`
PrivateFavorites []struct {
IDHash string `json:"idHash"`
ID string `json:"id"`
Name string `json:"name"`
IsPublicFavorite bool `json:"isPublicFavorite"`
ViewCount int `json:"viewCount"`
Creator string `json:"creator"`
IsWatched bool `json:"isWatched"`
Questions []struct {
QuestionID string `json:"questionId"`
Title string `json:"title"`
TitleSlug string `json:"titleSlug"`
Typename string `json:"__typename"`
} `json:"questions"`
Typename string `json:"__typename"`
} `json:"privateFavorites"`
Typename string `json:"__typename"`
}
// Gproblem define
type Gproblem struct {
QuestionID string `json:"questionId"`
QuestionFrontendID string `json:"questionFrontendId"`
BoundTopicID int `json:"boundTopicId"`
Title string `json:"title"`
TitleSlug string `json:"titleSlug"`
Content string `json:"content"`
TranslatedTitle string `json:"translatedTitle"`
TranslatedContent string `json:"translatedContent"`
IsPaidOnly bool `json:"isPaidOnly"`
Difficulty string `json:"difficulty"`
Likes int `json:"likes"`
Dislikes int `json:"dislikes"`
IsLiked interface{} `json:"isLiked"`
SimilarQuestions string `json:"similarQuestions"`
Contributors []interface{} `json:"contributors"`
LangToValidPlayground string `json:"langToValidPlayground"`
TopicTags []struct {
Name string `json:"name"`
Slug string `json:"slug"`
TranslatedName string `json:"translatedName"`
Typename string `json:"__typename"`
} `json:"topicTags"`
CompanyTagStats interface{} `json:"companyTagStats"`
CodeSnippets []GcodeSnippet `json:"codeSnippets"`
Stats string `json:"stats"`
Hints []interface{} `json:"hints"`
Solution interface{} `json:"solution"`
Status interface{} `json:"status"`
SampleTestCase string `json:"sampleTestCase"`
MetaData string `json:"metaData"`
JudgerAvailable bool `json:"judgerAvailable"`
JudgeType string `json:"judgeType"`
MysqlSchemas []interface{} `json:"mysqlSchemas"`
EnableRunCode bool `json:"enableRunCode"`
EnableTestMode bool `json:"enableTestMode"`
EnvInfo string `json:"envInfo"`
Typename string `json:"__typename"`
}
// Gstat define
type Gstat struct {
TotalAcs int `json:"total_acs"`
QuestionTitle string `json:"question__title"`
IsNewQuestion bool `json:"is_new_question"`
QuestionArticleSlug string `json:"question__article__slug"`
TotalSubmitted int `json:"total_submitted"`
FrontendQuestionID int `json:"frontend_question_id"`
QuestionTitleSlug string `json:"question__title_slug"`
QuestionArticleLive bool `json:"question__article__live"`
QuestionHide bool `json:"question__hide"`
QuestionID int `json:"question_id"`
}
// GcodeSnippet define
type GcodeSnippet struct {
Lang string `json:"lang"`
LangSlug string `json:"langSlug"`
Code string `json:"code"`
Typename string `json:"__typename"`
}

44
ctl/models/user.go Normal file
View File

@ -0,0 +1,44 @@
package models
import (
"fmt"
)
// UserInfo define
type UserInfo struct {
UserName string `json:"user_name"`
NumSolved int32 `json:"num_solved"`
NumTotal int32 `json:"num_total"`
AcEasy int32 `json:"ac_easy"`
AcMedium int32 `json:"ac_medium"`
AcHard int32 `json:"ac_hard"`
EasyTotal int32
MediumTotal int32
HardTotal int32
OptimizingEasy int32
OptimizingMedium int32
OptimizingHard int32
FrequencyHigh int32 `json:"frequency_high"`
FrequencyMid int32 `json:"frequency_mid"`
CategorySlug string `json:"category_slug"`
}
// | | Easy | Medium | Hard | Total | optimizing |
// |:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:|
func (ui UserInfo) table() string {
res := "| | Easy | Medium | Hard | Total |\n"
res += "|:--------:|:--------:|:--------:|:--------:|:--------:|\n"
res += fmt.Sprintf("|Optimizing|%v|%v|%v|%v|\n", ui.OptimizingEasy, ui.OptimizingMedium, ui.OptimizingHard, ui.OptimizingEasy+ui.OptimizingMedium+ui.OptimizingHard)
res += fmt.Sprintf("|Accepted|**%v**|**%v**|**%v**|**%v**|\n", ui.AcEasy, ui.AcMedium, ui.AcHard, ui.AcEasy+ui.AcMedium+ui.AcHard)
res += fmt.Sprintf("|Total|%v|%v|%v|%v|\n", ui.EasyTotal, ui.MediumTotal, ui.HardTotal, ui.EasyTotal+ui.MediumTotal+ui.HardTotal)
res += fmt.Sprintf("|Perfection Rate|%.1f%%|%.1f%%|%.1f%%|%.1f%%|\n", (1-float64(ui.OptimizingEasy)/float64(ui.AcEasy))*100, (1-float64(ui.OptimizingMedium)/float64(ui.AcMedium))*100, (1-float64(ui.OptimizingHard)/float64(ui.AcHard))*100, (1-float64(ui.OptimizingEasy+ui.OptimizingMedium+ui.OptimizingHard)/float64(ui.AcEasy+ui.AcMedium+ui.AcHard))*100)
res += fmt.Sprintf("|Completion Rate|%.1f%%|%.1f%%|%.1f%%|%.1f%%|\n", float64(ui.AcEasy)/float64(ui.EasyTotal)*100, float64(ui.AcMedium)/float64(ui.MediumTotal)*100, float64(ui.AcHard)/float64(ui.HardTotal)*100, float64(ui.AcEasy+ui.AcMedium+ui.AcHard)/float64(ui.EasyTotal+ui.MediumTotal+ui.HardTotal)*100)
// 加这一行是为了撑开整个表格
res += "|------------|----------------------------|----------------------------|----------------------------|----------------------------|"
return res
}
// PersonalData define
func (ui UserInfo) PersonalData() string {
return ui.table()
}

223
ctl/pdf.go Normal file
View File

@ -0,0 +1,223 @@
package main
import (
"bufio"
"fmt"
"github.com/halfrost/LeetCode-Go/ctl/util"
"github.com/spf13/cobra"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
)
var (
cleanString1 = "{{< columns >}}"
cleanString2 = "<--->"
cleanString3 = "{{< /columns >}}"
cleanString4 = "<img src=\"https://books.halfrost.com/leetcode/logo.png\" alt=\"logo\" height=\"600\" align=\"right\" style=\"padding-left: 30px;\"/>"
pdfPreface = `<img src="https://books.halfrost.com/leetcode/logo.png" alt="logo" heigth="1300px" align="center"/>
# 说明
此版本是 https://books.halfrost.com/leetcode 网页的离线版,由于网页版实时会更新,所以此 PDF 版难免会有一些排版或者错别字。如果读者遇到了,可以到网页版相应页面,点击页面 edit 按钮,提交 pr 进行更改。此 PDF 版本号是 V%v.%v.%v。PDF 永久更新地址是 https://github.com/halfrost/LeetCode-Go/releases/,以版本号区分不同版本。笔者还是强烈推荐看在线版,有任何错误都会立即更新。如果觉得此书对刷题有一点点帮助,可以给此书点一个 star鼓励一下笔者早点更新更多题解。
> 版本号说明V%v.%v.%v%v 是大版本号,%v 代表当前题解中有几百题,目前是 %v 题,所以第二个版本号是 %v%v 代表当前题解中有几十题,目前是 %v 题,所以第三个版本号是 %v 。
# 目录
[toc]
`
majorVersion = 1
midVersion = 0
lastVersion = 0
totalSolutions = 0
)
func newPDFCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "pdf",
Short: "PDF related commands",
Run: func(cmd *cobra.Command, args []string) {
generatePDF()
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func generatePDF() {
var (
pdf, tmp []byte
err error
)
// 先删除 pre-next
delPreNext()
chapterFourFileOrder, _ := util.LoadChapterFourDir()
totalSolutions = len(chapterFourFileOrder)
midVersion = totalSolutions / 100
lastVersion = totalSolutions % 100
fmt.Printf("[当前的版本号是 V%v.%v.%v]\n", majorVersion, midVersion, lastVersion)
// 删除原始文档中的头部,并创建临时文件夹
prepare(fmt.Sprintf("../PDF v%v.%v.%v.md", majorVersion, midVersion, lastVersion))
// PDF 前言
pdf = append(pdf, []byte(fmt.Sprintf(pdfPreface, majorVersion, midVersion, lastVersion, majorVersion, midVersion, lastVersion, majorVersion, midVersion, totalSolutions, midVersion, lastVersion, totalSolutions, lastVersion))...)
// PDF 第一章
tmp, err = loadChapter(chapterOneFileOrder, "./pdftemp", "ChapterOne")
pdf = append(pdf, tmp...)
// PDF 第二章
tmp, err = loadChapter(chapterTwoFileOrder, "./pdftemp", "ChapterTwo")
pdf = append(pdf, tmp...)
// PDF 第三章
tmp, err = loadChapter(chapterThreeFileOrder, "./pdftemp", "ChapterThree")
pdf = append(pdf, tmp...)
// PDF 第四章
tmp, err = util.LoadFile("./pdftemp/ChapterFour/_index.md")
pdf = append(pdf, tmp...)
tmp, err = loadChapter(chapterFourFileOrder, "../website/content", "ChapterFour")
pdf = append(pdf, tmp...)
if err != nil {
fmt.Println(err)
}
// 生成 PDF
util.WriteFile(fmt.Sprintf("../PDF v%v.%v.%v.md", majorVersion, midVersion, lastVersion), pdf)
// 还原现场
addPreNext()
util.DestoryDir("./pdftemp")
}
func loadChapter(order []string, path, chapter string) ([]byte, error) {
var (
res, tmp []byte
err error
)
for index, v := range order {
if chapter == "ChapterOne" && index == 0 {
// 清理不支持的特殊 MarkDown 语法
tmp, err = clean(fmt.Sprintf("%v/%v/%v.md", path, chapter, v))
} else {
if chapter == "ChapterFour" {
if v[4] == '.' {
num, err := strconv.Atoi(v[:4])
if err != nil {
fmt.Println(err)
}
tmp, err = util.LoadFile(fmt.Sprintf("%v/%v/%v/%v.md", path, chapter, util.GetChpaterFourFileNum(num), v))
}
} else {
tmp, err = util.LoadFile(fmt.Sprintf("%v/%v/%v.md", path, chapter, v))
}
}
if err != nil {
fmt.Println(err)
return []byte{}, err
}
res = append(res, tmp...)
}
return res, err
}
func prepare(path string) {
err := os.Remove(path)
if err != nil {
fmt.Println("pdf 还没有创建")
fmt.Println(err)
}
fmt.Println("pdf 删除成功,开始构建全新版本")
err = os.MkdirAll("./pdftemp/ChapterOne", os.ModePerm)
if err != nil {
fmt.Println(err)
}
for _, v := range chapterOneFileOrder {
removeHeader(fmt.Sprintf("../website/content/ChapterOne/%v.md", v), fmt.Sprintf("./pdftemp/ChapterOne/%v.md", v), 5)
}
err = os.MkdirAll("./pdftemp/ChapterTwo", os.ModePerm)
if err != nil {
fmt.Println(err)
}
// 生成外部链接的 ChapterTwo
buildChapterTwo(false)
util.CopyFile("./pdftemp/ChapterTwo/_index.md", "../website/content/ChapterTwo/_index.md")
for _, v := range chapterTwoFileOrder {
removeHeader(fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", v), fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", v), 5)
}
err = os.MkdirAll("./pdftemp/ChapterThree", os.ModePerm)
if err != nil {
fmt.Println(err)
}
for _, v := range chapterThreeFileOrder {
removeHeader(fmt.Sprintf("../website/content/ChapterThree/%v.md", v), fmt.Sprintf("./pdftemp/ChapterThree/%v.md", v), 5)
}
err = os.MkdirAll("./pdftemp/ChapterFour", os.ModePerm)
if err != nil {
fmt.Println(err)
}
removeHeader(fmt.Sprintf("../website/content/ChapterFour/_index.md"), fmt.Sprintf("./pdftemp/ChapterFour/_index.md"), 5)
}
func clean(filePath string) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return output, nil
}
return nil, err
}
if ok, _ := regexp.Match(cleanString1, line); ok {
reg := regexp.MustCompile(cleanString1)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match(cleanString2, line); ok {
reg := regexp.MustCompile(cleanString2)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match(cleanString3, line); ok {
reg := regexp.MustCompile(cleanString3)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match(cleanString4, line); ok {
reg := regexp.MustCompile(cleanString4)
newByte := reg.ReplaceAll(line, []byte(""))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else {
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
}
func removeHeader(path, newPath string, lineNumber int) {
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
info, _ := os.Stat(path)
mode := info.Mode()
array := strings.Split(string(file), "\n")
array = array[lineNumber:]
ioutil.WriteFile(newPath, []byte(strings.Join(array, "\n")), mode)
//fmt.Println("remove line successful")
}

36
ctl/rangking.go Normal file
View File

@ -0,0 +1,36 @@
package main
import (
"fmt"
"strconv"
"strings"
)
// getRanking 让这个方法优雅一点
func getRanking() int {
// 获取网页数据
URL := fmt.Sprintf("https://leetcode.com/%s/", getConfig().Username)
data := getRaw(URL)
str := string(data)
// 通过不断裁剪 str 获取排名信息
fmt.Println(str)
i := strings.Index(str, "ng-init")
j := i + strings.Index(str[i:], "ng-cloak")
str = str[i:j]
i = strings.Index(str, "(")
j = strings.Index(str, ")")
str = str[i:j]
// fmt.Println("2\n", str)
strs := strings.Split(str, ",")
str = strs[6]
// fmt.Println("1\n", str)
i = strings.Index(str, "'")
j = 2 + strings.Index(str[2:], "'")
// fmt.Println("0\n", str)
str = str[i+1 : j]
r, err := strconv.Atoi(str)
if err != nil {
fmt.Printf("无法把 %s 转换成数字Ranking", str)
}
return r
}

27
ctl/refresh.go Normal file
View File

@ -0,0 +1,27 @@
package main
import (
"github.com/spf13/cobra"
)
func newRefresh() *cobra.Command {
cmd := &cobra.Command{
Use: "refresh",
Short: "Refresh all document",
Run: func(cmd *cobra.Command, args []string) {
refresh()
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func refresh() {
//buildBookMenu()
copyLackFile()
delPreNext()
buildREADME()
buildChapterTwo(true)
addPreNext()
}

366
ctl/render.go Normal file
View File

@ -0,0 +1,366 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"regexp"
"sort"
"strconv"
"strings"
m "github.com/halfrost/LeetCode-Go/ctl/models"
"github.com/halfrost/LeetCode-Go/ctl/util"
"github.com/spf13/cobra"
)
var (
chapterTwoList = []string{"Array", "String", "Two Pointers", "Linked List", "Stack", "Tree", "Dynamic Programming", "Backtracking", "Depth First Search", "Breadth First Search",
"Binary Search", "Math", "Hash Table", "Sort", "Bit Manipulation", "Union Find", "Sliding Window", "Segment Tree", "Binary Indexed Tree"}
chapterTwoFileName = []string{"Array", "String", "Two_Pointers", "Linked_List", "Stack", "Tree", "Dynamic_Programming", "Backtracking", "Depth_First_Search", "Breadth_First_Search",
"Binary_Search", "Math", "Hash_Table", "Sort", "Bit_Manipulation", "Union_Find", "Sliding_Window", "Segment_Tree", "Binary_Indexed_Tree"}
chapterTwoSlug = []string{"array", "string", "two-pointers", "linked-list", "stack", "tree", "dynamic-programming", "backtracking", "depth-first-search", "breadth-first-search",
"binary-search", "math", "hash-table", "sort", "bit-manipulation", "union-find", "sliding-window", "segment-tree", "binary-indexed-tree"}
)
func newBuildCommand() *cobra.Command {
mc := &cobra.Command{
Use: "build <subcommand>",
Short: "Build doc related commands",
}
//mc.PersistentFlags().StringVar(&logicEndpoint, "endpoint", "localhost:5880", "endpoint of logic service")
mc.AddCommand(
newBuildREADME(),
newBuildChapterTwo(),
// newBuildMenu(),
)
return mc
}
func newBuildREADME() *cobra.Command {
cmd := &cobra.Command{
Use: "readme",
Short: "Build readme.md commands",
Run: func(cmd *cobra.Command, args []string) {
buildREADME()
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func newBuildChapterTwo() *cobra.Command {
cmd := &cobra.Command{
Use: "chapter-two",
Short: "Build Chapter Two commands",
Run: func(cmd *cobra.Command, args []string) {
buildChapterTwo(true)
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func newBuildMenu() *cobra.Command {
cmd := &cobra.Command{
Use: "menu",
Short: "Build Menu commands",
Run: func(cmd *cobra.Command, args []string) {
buildBookMenu()
},
}
// cmd.Flags().StringVar(&alias, "alias", "", "alias")
// cmd.Flags().StringVar(&appId, "appid", "", "appid")
return cmd
}
func buildREADME() {
var (
problems []m.StatStatusPairs
lpa m.LeetCodeProblemAll
info m.UserInfo
)
// 请求所有题目信息
body := getProblemAllList()
problemsMap, optimizingIds := map[int]m.StatStatusPairs{}, []int{}
err := json.Unmarshal(body, &lpa)
if err != nil {
fmt.Println(err)
return
}
//writeFile("leetcode_problem.json", body)
// 拼凑 README 需要渲染的数据
problems = lpa.StatStatusPairs
info = m.ConvertUserInfoModel(lpa)
for _, v := range problems {
problemsMap[int(v.Stat.FrontendQuestionID)] = v
}
mdrows := m.ConvertMdModelFromSsp(problems)
sort.Sort(m.SortByQuestionID(mdrows))
solutionIds, _, try := util.LoadSolutionsDir()
m.GenerateMdRows(solutionIds, mdrows)
info.EasyTotal, info.MediumTotal, info.HardTotal, info.OptimizingEasy, info.OptimizingMedium, info.OptimizingHard, optimizingIds = statisticalData(problemsMap, solutionIds)
omdrows := m.ConvertMdModelFromIds(problemsMap, optimizingIds)
sort.Sort(m.SortByQuestionID(omdrows))
// 按照模板渲染 README
res, err := renderReadme("./template/template.markdown", len(solutionIds), try, m.Mdrows{Mdrows: mdrows}, m.Mdrows{Mdrows: omdrows}, info)
if err != nil {
fmt.Println(err)
return
}
util.WriteFile("../README.md", res)
fmt.Println("write file successful")
//makeReadmeFile(mds)
}
func renderReadme(filePath string, total, try int, mdrows, omdrows m.Mdrows, user m.UserInfo) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return output, nil
}
return nil, err
}
if ok, _ := regexp.Match("{{.AvailableTable}}", line); ok {
reg := regexp.MustCompile("{{.AvailableTable}}")
newByte := reg.ReplaceAll(line, []byte(mdrows.AvailableTable()))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match("{{.TotalNum}}", line); ok {
reg := regexp.MustCompile("{{.TotalNum}}")
newByte := reg.ReplaceAll(line, []byte(fmt.Sprintf("以下已经收录了 %v 道题的题解,还有 %v 道题在尝试优化到 beats 100%%", total, try)))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match("{{.PersonalData}}", line); ok {
reg := regexp.MustCompile("{{.PersonalData}}")
newByte := reg.ReplaceAll(line, []byte(user.PersonalData()))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else if ok, _ := regexp.Match("{{.OptimizingTable}}", line); ok {
reg := regexp.MustCompile("{{.OptimizingTable}}")
newByte := reg.ReplaceAll(line, []byte(fmt.Sprintf("以下 %v 道题还需要优化到 100%% 的题目列表\n\n%v", (user.OptimizingEasy+user.OptimizingMedium+user.OptimizingHard), omdrows.AvailableTable())))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else {
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
}
// internal: true 渲染的链接都是 hugo 内部链接,用户生成 hugo web
// false 渲染的链接是外部 HTTPS 链接,用于生成 PDF
func buildChapterTwo(internal bool) {
var (
gr m.GraphQLResp
questions []m.Question
count int
)
for index, tag := range chapterTwoSlug {
body := getTagProblemList(tag)
// fmt.Printf("%v\n", string(body))
err := json.Unmarshal(body, &gr)
if err != nil {
fmt.Println(err)
return
}
questions = gr.Data.TopicTag.Questions
mdrows := m.ConvertMdModelFromQuestions(questions)
sort.Sort(m.SortByQuestionID(mdrows))
solutionIds, _, _ := util.LoadSolutionsDir()
tl, err := loadMetaData(fmt.Sprintf("./meta/%v", chapterTwoFileName[index]))
if err != nil {
fmt.Printf("err = %v\n", err)
}
tls := m.GenerateTagMdRows(solutionIds, tl, mdrows, internal)
//fmt.Printf("tls = %v\n", tls)
// 按照模板渲染 README
res, err := renderChapterTwo(fmt.Sprintf("./template/%v.md", chapterTwoFileName[index]), m.TagLists{TagLists: tls})
if err != nil {
fmt.Println(err)
return
}
if internal {
util.WriteFile(fmt.Sprintf("../website/content/ChapterTwo/%v.md", chapterTwoFileName[index]), res)
} else {
util.WriteFile(fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", chapterTwoFileName[index]), res)
}
count++
}
fmt.Printf("write %v files successful", count)
}
func loadMetaData(filePath string) (map[int]m.TagList, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, metaMap := bufio.NewReader(f), map[int]m.TagList{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return metaMap, nil
}
return nil, err
}
s := strings.Split(string(line), "|")
v, _ := strconv.Atoi(strings.Split(s[1], ".")[0])
// v[0] 是题号s[4] time, s[5] space, s[6] favorite
metaMap[v] = m.TagList{
FrontendQuestionID: int32(v),
Acceptance: "",
Difficulty: "",
TimeComplexity: s[4],
SpaceComplexity: s[5],
Favorite: s[6],
}
}
}
func renderChapterTwo(filePath string, tls m.TagLists) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return output, nil
}
return nil, err
}
if ok, _ := regexp.Match("{{.AvailableTagTable}}", line); ok {
reg := regexp.MustCompile("{{.AvailableTagTable}}")
newByte := reg.ReplaceAll(line, []byte(tls.AvailableTagTable()))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else {
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
}
func buildBookMenu() {
copyLackFile()
// 按照模板重新渲染 Menu
res, err := renderBookMenu("./template/menu.md")
if err != nil {
fmt.Println(err)
return
}
util.WriteFile("../website/content/menu/index.md", res)
fmt.Println("generate Menu successful")
}
// 拷贝 leetcode 目录下的题解 README 文件至第四章对应文件夹中
func copyLackFile() {
solutionIds, soName, _ := util.LoadSolutionsDir()
_, ch4Ids := util.LoadChapterFourDir()
needCopy := []string{}
for i := 0; i < len(solutionIds); i++ {
if util.BinarySearch(ch4Ids, solutionIds[i]) == -1 {
needCopy = append(needCopy, soName[i])
}
}
if len(needCopy) > 0 {
fmt.Printf("有 %v 道题需要拷贝到第四章中\n", len(needCopy))
for i := 0; i < len(needCopy); i++ {
if needCopy[i][4] == '.' {
tmp, err := strconv.Atoi(needCopy[i][:4])
if err != nil {
fmt.Println(err)
}
err = os.MkdirAll(fmt.Sprintf("../website/content/ChapterFour/%v", util.GetChpaterFourFileNum(tmp)), os.ModePerm)
if err != nil {
fmt.Println(err)
}
util.CopyFile(fmt.Sprintf("../website/content/ChapterFour/%v/%v.md", util.GetChpaterFourFileNum(tmp), needCopy[i]), fmt.Sprintf("../leetcode/%v/README.md", needCopy[i]))
util.CopyFile(fmt.Sprintf("../website/content/ChapterFour/%v/_index.md", util.GetChpaterFourFileNum(tmp)), "./template/collapseSection.md")
}
}
} else {
fmt.Printf("【第四章没有需要添加的题解,已经完整了】\n")
}
}
func generateMenu() string {
res := ""
res += menuLine(chapterOneMenuOrder, "ChapterOne")
res += menuLine(chapterTwoFileOrder, "ChapterTwo")
res += menuLine(chapterThreeFileOrder, "ChapterThree")
chapterFourFileOrder, _ := getChapterFourFileOrder()
res += menuLine(chapterFourFileOrder, "ChapterFour")
return res
}
func menuLine(order []string, chapter string) string {
res := ""
for i := 0; i < len(order); i++ {
if i == 1 && chapter == "ChapterOne" {
res += fmt.Sprintf(" - [%v]({{< relref \"/%v/%v\" >}})\n", chapterMap[chapter][order[i]], chapter, order[i])
continue
}
if i == 0 {
res += fmt.Sprintf("- [%v]({{< relref \"/%v/%v.md\" >}})\n", chapterMap[chapter][order[i]], chapter, order[i])
} else {
if chapter == "ChapterFour" {
res += fmt.Sprintf(" - [%v]({{< relref \"/%v/%v.md\" >}})\n", order[i], chapter, order[i])
} else {
res += fmt.Sprintf(" - [%v]({{< relref \"/%v/%v.md\" >}})\n", chapterMap[chapter][order[i]], chapter, order[i])
}
}
}
return res
}
func renderBookMenu(filePath string) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return output, nil
}
return nil, err
}
if ok, _ := regexp.Match("{{.BookMenu}}", line); ok {
reg := regexp.MustCompile("{{.BookMenu}}")
newByte := reg.ReplaceAll(line, []byte(generateMenu()))
output = append(output, newByte...)
output = append(output, []byte("\n")...)
} else {
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
}

109
ctl/request.go Normal file
View File

@ -0,0 +1,109 @@
package main
import (
"bytes"
"fmt"
"github.com/mozillazg/request"
"io/ioutil"
"net/http"
)
const (
// AllProblemURL define
AllProblemURL = "https://leetcode.com/api/problems/all/"
// QraphqlURL define
QraphqlURL = "https://leetcode.com/graphql"
// LoginPageURL define
LoginPageURL = "https://leetcode.com/accounts/login/"
// AlgorithmsURL define
AlgorithmsURL = "https://leetcode.com/api/problems/Algorithms/"
// ArrayProblemURL define
ArrayProblemURL = "https://leetcode.com/tag/array/"
)
var req *request.Request
func newReq() *request.Request {
if req == nil {
req = signin()
}
return req
}
func signin() *request.Request {
cfg := getConfig()
req := request.NewRequest(new(http.Client))
req.Headers = map[string]string{
"Content-Type": "application/json",
"Accept-Encoding": "",
"cookie": cfg.Cookie,
"x-csrftoken": cfg.CSRFtoken,
"Referer": "https://leetcode.com/accounts/login/",
"origin": "https://leetcode.com",
}
return req
}
func getRaw(URL string) []byte {
req := newReq()
resp, err := req.Get(URL)
if err != nil {
fmt.Printf("getRaw: Get Error: " + err.Error())
return []byte{}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("getRaw: Read Error: " + err.Error())
return []byte{}
}
if resp.StatusCode == 200 {
fmt.Println("Get problem Success!")
}
return body
}
func getProblemAllList() []byte {
return getRaw(AllProblemURL)
}
// Variables define
type Variables struct {
slug string
}
func getQraphql(payload string) []byte {
req := newReq()
resp, err := req.PostForm(QraphqlURL, bytes.NewBuffer([]byte(payload)))
if err != nil {
fmt.Printf("getRaw: Get Error: " + err.Error())
return []byte{}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("getRaw: Read Error: " + err.Error())
return []byte{}
}
if resp.StatusCode == 200 {
fmt.Println("Get problem Success!")
}
return body
}
func getTopicTag(variable string) string {
return fmt.Sprintf(`{
"operationName": "getTopicTag",
"variables": {
"slug": "%s"
},
"query": "query getTopicTag($slug: String!) { topicTag(slug: $slug) { name translatedName slug questions { status questionId questionFrontendId title titleSlug translatedTitle stats difficulty isPaidOnly topicTags { name translatedName slug __typename } companyTags { name translatedName slug __typename } __typename } frequencies __typename } favoritesLists { publicFavorites { ...favoriteFields __typename } privateFavorites { ...favoriteFields __typename } __typename }}fragment favoriteFields on FavoriteNode { idHash id name isPublicFavorite viewCount creator isWatched questions { questionId title titleSlug __typename } __typename}"
}`, variable)
}
func getTagProblemList(tag string) []byte {
return getQraphql(getTopicTag(tag))
}

41
ctl/statistic.go Normal file
View File

@ -0,0 +1,41 @@
package main
import (
m "github.com/halfrost/LeetCode-Go/ctl/models"
"github.com/halfrost/LeetCode-Go/ctl/util"
"sort"
)
func statisticalData(problemsMap map[int]m.StatStatusPairs, solutionIds []int) (easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard int32, optimizingIds []int) {
easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard, optimizingIds = 0, 0, 0, 0, 0, 0, []int{}
for _, v := range problemsMap {
switch m.DifficultyMap[v.Difficulty.Level] {
case "Easy":
{
easyTotal++
if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
optimizingEasy++
optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID))
}
}
case "Medium":
{
mediumTotal++
if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
optimizingMedium++
optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID))
}
}
case "Hard":
{
hardTotal++
if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
optimizingHard++
optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID))
}
}
}
}
sort.Ints(optimizingIds)
return easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard, optimizingIds
}

9
ctl/template/Array.md Normal file
View File

@ -0,0 +1,9 @@
---
title: 2.01 Array
type: docs
weight: 1
---
# Array
{{.AvailableTagTable}}

View File

@ -0,0 +1,101 @@
---
title: 2.08 ✅ Backtracking
type: docs
weight: 8
---
# Backtracking
![](https://img.halfrost.com/Leetcode/Backtracking.png)
- 排列问题 Permutations。第 46 题,第 47 题。第 60 题,第 526 题,第 996 题。
- 组合问题 Combination。第 39 题,第 40 题,第 77 题,第 216 题。
- 排列和组合杂交问题。第 1079 题。
- N 皇后终极解法(二进制解法)。第 51 题,第 52 题。
- 数独问题。第 37 题。
- 四个方向搜索。第 79 题,第 212 题,第 980 题。
- 子集合问题。第 78 题,第 90 题。
- Trie。第 208 题,第 211 题。
- BFS 优化。第 126 题,第 127 题。
- DFS 模板。(只是一个例子,不对应任何题)
```go
func combinationSum2(candidates []int, target int) [][]int {
if len(candidates) == 0 {
return [][]int{}
}
c, res := []int{}, [][]int{}
sort.Ints(candidates)
findcombinationSum2(candidates, target, 0, c, &res)
return res
}
func findcombinationSum2(nums []int, target, index int, c []int, res *[][]int) {
if target == 0 {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
return
}
for i := index; i < len(nums); i++ {
if i > index && nums[i] == nums[i-1] { // 这里是去重的关键逻辑
continue
}
if target >= nums[i] {
c = append(c, nums[i])
findcombinationSum2(nums, target-nums[i], i+1, c, res)
c = c[:len(c)-1]
}
}
}
```
- BFS 模板。(只是一个例子,不对应任何题)
```go
func updateMatrix_BFS(matrix [][]int) [][]int {
res := make([][]int, len(matrix))
if len(matrix) == 0 || len(matrix[0]) == 0 {
return res
}
queue := make([][]int, 0)
for i, _ := range matrix {
res[i] = make([]int, len(matrix[0]))
for j, _ := range res[i] {
if matrix[i][j] == 0 {
res[i][j] = -1
queue = append(queue, []int{i, j})
}
}
}
level := 1
for len(queue) > 0 {
size := len(queue)
for size > 0 {
size -= 1
node := queue[0]
queue = queue[1:]
i, j := node[0], node[1]
for _, direction := range [][]int{{-1, 0}, {1, 0}, {0, 1}, {0, -1}} {
x := i + direction[0]
y := j + direction[1]
if x < 0 || x >= len(matrix) || y < 0 || y >= len(matrix[0]) || res[x][y] < 0 || res[x][y] > 0 {
continue
}
res[x][y] = level
queue = append(queue, []int{x, y})
}
}
level++
}
for i, row := range res {
for j, cell := range row {
if cell == -1 {
res[i][j] = 0
}
}
}
return res
}
```
{{.AvailableTagTable}}

View File

@ -0,0 +1,11 @@
---
title: 2.19 ✅ Binary Indexed Tree
type: docs
weight: 19
---
# Binary Indexed Tree
![](https://img.halfrost.com/Leetcode/Binary_Indexed_Tree.png)
{{.AvailableTagTable}}

View File

@ -0,0 +1,132 @@
---
title: 2.11 Binary Search
type: docs
weight: 11
---
# Binary Search
- 二分搜索的经典写法。需要注意的三点:
1. 循环退出条件,注意是 low <= high而不是 low < high
2. mid 的取值mid := low + (high-low)>>1
3. low 和 high 的更新。low = mid + 1high = mid - 1。
```go
func binarySearchMatrix(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
```
- 二分搜索的变种写法。有 4 个基本变种:
1. 查找第一个与 target 相等的元素,时间复杂度 O(logn)
2. 查找最后一个与 target 相等的元素,时间复杂度 O(logn)
3. 查找第一个大于等于 target 的元素,时间复杂度 O(logn)
4. 查找最后一个小于等于 target 的元素,时间复杂度 O(logn)
```go
// 二分查找第一个与 target 相等的元素,时间复杂度 O(logn)
func searchFirstEqualElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
} else {
if (mid == 0) || (nums[mid-1] != target) { // 找到第一个与 target 相等的元素
return mid
}
high = mid - 1
}
}
return -1
}
// 二分查找最后一个与 target 相等的元素,时间复杂度 O(logn)
func searchLastEqualElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
} else {
if (mid == len(nums)-1) || (nums[mid+1] != target) { // 找到最后一个与 target 相等的元素
return mid
}
low = mid + 1
}
}
return -1
}
// 二分查找第一个大于等于 target 的元素,时间复杂度 O(logn)
func searchFirstGreaterElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] >= target {
if (mid == 0) || (nums[mid-1] < target) { // 找到第一个大于等于 target 的元素
return mid
}
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// 二分查找最后一个小于等于 target 的元素,时间复杂度 O(logn)
func searchLastLessElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] <= target {
if (mid == len(nums)-1) || (nums[mid+1] > target) { // 找到最后一个小于等于 target 的元素
return mid
}
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
```
- 在基本有序的数组中用二分搜索。经典解法可以解,变种写法也可以写,常见的题型,在山峰数组中找山峰,在旋转有序数组中找分界点。第 33 题,第 81 题,第 153 题,第 154 题,第 162 题,第 852 题
```go
func peakIndexInMountainArray(A []int) int {
low, high := 0, len(A)-1
for low < high {
mid := low + (high-low)>>1
// 如果 mid 较大则左侧存在峰值high = m如果 mid + 1 较大则右侧存在峰值low = mid + 1
if A[mid] > A[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}
```
- max-min 最大值最小化问题。求在最小满足条件的情况下的最大值。第 410 题,第 875 题,第 1011 题,第 1283 题。
{{.AvailableTagTable}}

View File

@ -0,0 +1,45 @@
---
title: 2.15 ✅ Bit Manipulation
type: docs
weight: 15
---
# Bit Manipulation
![](https://img.halfrost.com/Leetcode/Bit_Manipulation.png)
- 异或的特性。第 136 题,第 268 题,第 389 题,第 421 题,
```go
x ^ 0 = x
x ^ 11111……1111 = ~x
x ^ (~x) = 11111……1111
x ^ x = 0
a ^ b = c => a ^ c = b => b ^ c = a (交换律)
a ^ b ^ c = a ^ (b ^ c) = (a ^ b^ c (结合律)
```
- 构造特殊 Mask将特殊位置放 0 或 1。
```go
x 最右边的 n 位清零 x & ( ~0 << n )
获取 x 的第 n 位值(0 或者 1)(x >> n) & 1
获取 x 的第 n 位的幂值x & (1 << (n - 1))
仅将第 n 位置为 1x | (1 << n)
仅将第 n 位置为 0x & (~(1 << n))
x 最高位至第 n ()清零x & ((1 << n) - 1)
将第 n 位至第 0 ()清零x & (~((1 << (n + 1)) - 1)
```
- 有特殊意义的 & 位操作运算。第 260 题,第 201 题,第 318 题,第 371 题,第 397 题,第 461 题,第 693 题,
```go
X & 1 == 1 判断是否是奇数(偶数)
X & = (X - 1) 将最低位(LSB) 1 清零
X & -X 得到最低位(LSB) 1
X & ~X = 0
```
{{.AvailableTagTable}}

View File

@ -0,0 +1,10 @@
---
title: 2.10 Breadth First Search
type: docs
weight: 10
---
# Breadth First Search
{{.AvailableTagTable}}

View File

@ -0,0 +1,10 @@
---
title: 2.09 Depth First Search
type: docs
weight: 9
---
# Depth First Search
{{.AvailableTagTable}}

View File

@ -0,0 +1,10 @@
---
title: 2.07 Dynamic Programming
type: docs
weight: 7
---
# Dynamic Programming
{{.AvailableTagTable}}

View File

@ -0,0 +1,10 @@
---
title: 2.13 Hash Table
type: docs
weight: 13
---
# Hash Table
{{.AvailableTagTable}}

View File

@ -0,0 +1,24 @@
---
title: 2.04 ✅ Linked List
type: docs
weight: 4
---
# Linked List
![](https://img.halfrost.com/Leetcode/Linked_List.png)
- 巧妙的构造虚拟头结点。可以使遍历处理逻辑更加统一。
- 灵活使用递归。构造递归条件,使用递归可以巧妙的解题。不过需要注意有些题目不能使用递归,因为递归深度太深会导致超时和栈溢出。
- 链表区间逆序。第 92 题。
- 链表寻找中间节点。第 876 题。链表寻找倒数第 n 个节点。第 19 题。只需要一次遍历就可以得到答案。
- 合并 K 个有序链表。第 21 题,第 23 题。
- 链表归类。第 86 题,第 328 题。
- 链表排序,时间复杂度要求 O(n * log n),空间复杂度 O(1)。只有一种做法,归并排序,至顶向下归并。第 148 题。
- 判断链表是否存在环,如果有环,输出环的交叉点的下标;判断 2 个链表是否有交叉点,如果有交叉点,输出交叉点。第 141 题,第 142 题,第 160 题。
{{.AvailableTagTable}}

10
ctl/template/Math.md Normal file
View File

@ -0,0 +1,10 @@
---
title: 2.12 Math
type: docs
weight: 12
---
# Math
{{.AvailableTagTable}}

View File

@ -0,0 +1,38 @@
---
title: 2.18 ✅ Segment Tree
type: docs
weight: 18
---
# Segment Tree
![](https://img.halfrost.com/Leetcode/Segment_Tree.png)
- 线段树的经典数组实现写法。将合并两个节点 pushUp 逻辑抽象出来了,可以实现任意操作(常见的操作有:加法,取 maxmin 等等)。第 218 题,第 303 题,第 307 题,第 699 题。
- 计数线段树的经典写法。第 315 题,第 327 题,第 493 题。
- 线段树的树的实现写法。第 715 题,第 732 题。
- 区间懒惰更新。第 218 题,第 699 题。
- 离散化。离散化需要注意一个特殊情况:假如三个区间为 [1,10] [1,4] [6,10],离散化后 x[1]=1,x[2]=4,x[3]=6,x[4]=10。第一个区间为 [1,4],第二个区间为 [1,2],第三个区间为 [3,4],这样一来,区间一 = 区间二 + 区间三,这和离散前的模型不符,离散前,很明显,区间一 > 区间二 + 区间三。正确的做法是:在相差大于 1 的数间加一个数,例如在上面 1 4 6 10 中间加 5即可 x[1]=1,x[2]=4,x[3]=5,x[4]=6,x[5]=10。这样处理之后区间一是 1-5 ,区间二是 1-2 ,区间三是 4-5 。
- 灵活构建线段树。线段树节点可以存储多条信息,合并两个节点的 pushUp 操作也可以是多样的。第 850 题,第 1157 题。
线段树[题型](https://blog.csdn.net/xuechelingxiao/article/details/38313105)从简单到困难:
1. 单点更新:
[HDU 1166 敌兵布阵](http://acm.hdu.edu.cn/showproblem.php?pid=1166) update:单点增减 query:区间求和
[HDU 1754 I Hate It](http://acm.hdu.edu.cn/showproblem.php?pid=1754) update:单点替换 query:区间最值
[HDU 1394 Minimum Inversion Number](http://acm.hdu.edu.cn/showproblem.php?pid=1394) update:单点增减 query:区间求和
[HDU 2795 Billboard](http://acm.hdu.edu.cn/showproblem.php?pid=2795) query:区间求最大值的位子(直接把update的操作在query里做了)
2. 区间更新:
[HDU 1698 Just a Hook](http://acm.hdu.edu.cn/showproblem.php?pid=1698) update:成段替换 (由于只query一次总区间,所以可以直接输出 1 结点的信息)
[POJ 3468 A Simple Problem with Integers](http://poj.org/problem?id=3468) update:成段增减 query:区间求和
[POJ 2528 Mayors posters](http://poj.org/problem?id=2528) 离散化 + update:成段替换 query:简单hash
[POJ 3225 Help with Intervals](http://poj.org/problem?id=3225) update:成段替换,区间异或 query:简单hash
3. 区间合并(这类题目会询问区间中满足条件的连续最长区间,所以PushUp的时候需要对左右儿子的区间进行合并):
[POJ 3667 Hotel](http://poj.org/problem?id=3667) update:区间替换 query:询问满足条件的最左端点
4. 扫描线(这类题目需要将一些操作排序,然后从左到右用一根扫描线扫过去最典型的就是矩形面积并,周长并等题):
[HDU 1542 Atlantis](http://acm.hdu.edu.cn/showproblem.php?pid=1542) update:区间增减 query:直接取根节点的值
[HDU 1828 Picture](http://acm.hdu.edu.cn/showproblem.php?pid=1828) update:区间增减 query:直接取根节点的值
{{.AvailableTagTable}}

View File

@ -0,0 +1,30 @@
---
title: 2.17 ✅ Sliding Window
type: docs
weight: 17
---
# Sliding Window
![](https://img.halfrost.com/Leetcode/Sliding_Window.png)
- 双指针滑动窗口的经典写法。右指针不断往右移,移动到不能往右移动为止(具体条件根据题目而定)。当右指针到最右边以后,开始挪动左指针,释放窗口左边界。第 3 题,第 76 题,第 209 题,第 424 题,第 438 题,第 567 题,第 713 题,第 763 题,第 845 题,第 881 题,第 904 题,第 978 题,第 992 题,第 1004 题,第 1040 题,第 1052 题。
```c
left, right := 0, -1
for left < len(s) {
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
freq[s[right+1]-'a']++
right++
} else {
freq[s[left]-'a']--
left++
}
result = max(result, right-left+1)
}
```
- 滑动窗口经典题。第 239 题,第 480 题。
{{.AvailableTagTable}}

19
ctl/template/Sort.md Normal file
View File

@ -0,0 +1,19 @@
---
title: 2.14 ✅ Sort
type: docs
weight: 14
---
# Sort
![](https://img.halfrost.com/Leetcode/Sort.png)
- 深刻的理解多路快排。第 75 题。
- 链表的排序,插入排序(第 147 题)和归并排序(第 148 题)
- 桶排序和基数排序。第 164 题。
- "摆动排序"。第 324 题。
- 两两不相邻的排序。第 767 题,第 1054 题。
- "饼子排序"。第 969 题。
{{.AvailableTagTable}}

18
ctl/template/Stack.md Normal file
View File

@ -0,0 +1,18 @@
---
title: 2.05 ✅ Stack
type: docs
weight: 5
---
# Stack
![](https://img.halfrost.com/Leetcode/Stack.png)
- 括号匹配问题及类似问题。第 20 题,第 921 题,第 1021 题。
- 栈的基本 pop 和 push 操作。第 71 题,第 150 题,第 155 题,第 224 题,第 225 题,第 232 题,第 946 题,第 1047 题。
- 利用栈进行编码问题。第 394 题,第 682 题,第 856 题,第 880 题。
- **单调栈**。**利用栈维护一个单调递增或者递减的下标数组**。第 84 题,第 456 题,第 496 题,第 503 题,第 739 题,第 901 题,第 907 题,第 1019 题。
{{.AvailableTagTable}}

10
ctl/template/String.md Normal file
View File

@ -0,0 +1,10 @@
---
title: 2.02 String
type: docs
weight: 2
---
# String
{{.AvailableTagTable}}

10
ctl/template/Tree.md Normal file
View File

@ -0,0 +1,10 @@
---
title: 2.06 Tree
type: docs
weight: 6
---
# Tree
{{.AvailableTagTable}}

View File

@ -0,0 +1,33 @@
---
title: 2.03 ✅ Two Pointers
type: docs
weight: 3
---
# Two Pointers
![](https://img.halfrost.com/Leetcode/Two_pointers.png)
- 双指针滑动窗口的经典写法。右指针不断往右移,移动到不能往右移动为止(具体条件根据题目而定)。当右指针到最右边以后,开始挪动左指针,释放窗口左边界。第 3 题,第 76 题,第 209 题,第 424 题,第 438 题,第 567 题,第 713 题,第 763 题,第 845 题,第 881 题,第 904 题,第 978 题,第 992 题,第 1004 题,第 1040 题,第 1052 题。
```c
left, right := 0, -1
for left < len(s) {
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
freq[s[right+1]-'a']++
right++
} else {
freq[s[left]-'a']--
left++
}
result = max(result, right-left+1)
}
```
- 快慢指针可以查找重复数字,时间复杂度 O(n),第 287 题。
- 替换字母以后,相同字母能出现连续最长的长度。第 424 题。
- SUM 问题集。第 1 题,第 15 题,第 16 题,第 18 题,第 167 题,第 923 题,第 1074 题。
{{.AvailableTagTable}}

View File

@ -0,0 +1,20 @@
---
title: 2.16 ✅ Union Find
type: docs
weight: 16
---
# Union Find
![](https://img.halfrost.com/Leetcode/Union_Find.png)
- 灵活使用并查集的思想,熟练掌握并查集的[模板]({{< relref "/ChapterThree/UnionFind.md" >}}),模板中有两种并查集的实现方式,一种是路径压缩 + 秩优化的版本,另外一种是计算每个集合中元素的个数 + 最大集合元素个数的版本,这两种版本都有各自使用的地方。能使用第一类并查集模板的题目有:第 128 题,第 130 题,第 547 题,第 684 题,第 721 题,第 765 题,第 778 题,第 839 题,第 924 题,第 928 题,第 947 题,第 952 题,第 959 题,第 990 题。能使用第二类并查集模板的题目有:第 803 题,第 952 题。第 803 题秩优化和统计集合个数这些地方会卡时间,如果不优化,会 TLE。
- 并查集是一种思想,有些题需要灵活使用这种思想,而不是死套模板,如第 399 题,这一题是 stringUnionFind利用并查集思想实现的。这里每个节点是基于字符串和 map 的,而不是单纯的用 int 节点编号实现的。
- 有些题死套模板反而做不出来,比如第 685 题,这一题不能路径压缩和秩优化,因为题目中涉及到有向图,需要知道节点的前驱节点,如果路径压缩了,这一题就没法做了。这一题不需要路径压缩和秩优化。
- 灵活的抽象题目给的信息,将给定的信息合理的编号,使用并查集解题,并用 map 降低时间复杂度,如第 721 题,第 959 题。
- 关于地图,砖块,网格的题目,可以新建一个特殊节点,将四周边缘的砖块或者网格都 union() 到这个特殊节点上。第 130 题,第 803 题。
- 能用并查集的题目,一般也可以用 DFS 和 BFS 解答,只不过时间复杂度会高一点。
{{.AvailableTagTable}}

View File

@ -0,0 +1,4 @@
---
bookCollapseSection: true
weight: 20
---

9
ctl/template/menu.md Normal file
View File

@ -0,0 +1,9 @@
---
headless: true
---
<hr>
{{.BookMenu}}
<br />

View File

@ -0,0 +1,644 @@
# LeetCode in Go
[LeetCode Online Judge](https://leetcode.com/) is a website containing many **algorithm questions**. Most of them are real interview questions of **Google, Facebook, LinkedIn, Apple**, etc. and it always help to sharp our algorithm Skills. Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. This repo shows my solutions in Go with the code style strictly follows the [Google Golang Style Guide](https://github.com/golang/go/wiki/CodeReviewComments). Please feel free to reference and **STAR** to support this repo, thank you!
<p align='center'>
<img src='./logo.png'>
</p>
![](./website/static/wechat-qr-code.png)
<p align='center'>
<a href="https://github.com/halfrost/LeetCode-Go/releases/" rel="nofollow"><img alt="GitHub All Releases" src="https://img.shields.io/github/downloads/halfrost/LeetCode-Go/total?label=PDF%20downloads"></a>
<img src="https://img.shields.io/badge/Total%20Word%20Count-738884-success">
<a href="https://github.com/halfrost/LeetCode-Go/actions" rel="nofollow"><img src="https://github.com/halfrost/LeetCode-Go/workflows/Deploy%20leetcode-cookbook/badge.svg?branch=master"></a>
<a href="https://travis-ci.org/github/halfrost/LeetCode-Go" rel="nofollow"><img src="https://travis-ci.org/halfrost/LeetCode-Go.svg?branch=master"></a>
<a href="https://goreportcard.com/report/github.com/halfrost/LeetCode-Go" rel="nofollow"><img src="https://goreportcard.com/badge/github.com/halfrost/LeetCode-Go"></a>
<img src="https://img.shields.io/badge/runtime%20beats-100%25-success">
<!--<img alt="GitHub go.mod Go version" src="https://img.shields.io/github/go-mod/go-version/halfrost/LeetCode-Go?color=26C2F0">-->
<img alt="Support Go version" src="https://img.shields.io/badge/Go-v1.15-26C2F0">
<img src="https://visitor-badge.laobi.icu/badge?page_id=halfrost.LeetCode-Go">
</p>
<p align='center'>
<a href="https://github.com/halfrost/LeetCode-Go/blob/master/LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/halfrost/LeetCode-Go?label=License"></a>
<img src="https://img.shields.io/badge/License-CC-000000.svg">
<a href="https://leetcode.com/halfrost/"><img src="https://img.shields.io/badge/@halfrost-8751-yellow.svg">
<img src="https://img.shields.io/badge/language-Golang-26C2F0.svg">
<a href="https://halfrost.com"><img src="https://img.shields.io/badge/Blog-Halfrost--Field-80d4f9.svg?style=flat"></a>
<a href="http://weibo.com/halfrost"><img src="https://img.shields.io/badge/weibo-@halfrost-f974ce.svg?style=flat&colorA=f4292e"></a>
<a href="https://twitter.com/halffrost"><img src="https://img.shields.io/badge/twitter-@halffrost-F8E81C.svg?style=flat&colorA=009df2"></a>
<a href="https://www.zhihu.com/people/halfrost/activities"><img src="https://img.shields.io/badge/%E7%9F%A5%E4%B9%8E-@halfrost-fd6f32.svg?style=flat&colorA=0083ea"></a>
<img src="https://img.shields.io/badge/made%20with-=1-blue.svg">
<a href="https://github.com/halfrost/LeetCode-Go/pulls"><img src="https://img.shields.io/badge/PR-Welcome-brightgreen.svg"></a>
</p>
支持 Progressive Web Apps 和 Dark Mode 的题解电子书《LeetCode Cookbook》 <a href="https://books.halfrost.com/leetcode/" rel="nofollow">Online Reading</a>
<p align='center'>
<a href="https://books.halfrost.com/leetcode/"><img src="https://img.halfrost.com/Leetcode/Cookbook_Safari_0.png"></a>
<a href="https://books.halfrost.com/leetcode/"><img src="https://img.halfrost.com/Leetcode/Cookbook_Chrome_PWA.png"></a>
</p>
离线版本的电子书《LeetCode Cookbook》PDF <a href="https://github.com/halfrost/LeetCode-Go/releases/" rel="nofollow">Download here</a>
<p align='center'>
<a href="https://github.com/halfrost/LeetCode-Go/releases/"><img src="https://img.halfrost.com/Leetcode/Cookbook.png"></a>
</p>
通过 iOS / Android 浏览器安装 PWA 版《LeetCode Cookbook》至设备桌面随时学习
<p align='center'>
<a href="https://books.halfrost.com/leetcode/"><img src="https://img.halfrost.com/Leetcode/Cookbook_PWA_iPad.png"></a>
<a href="https://books.halfrost.com/leetcode/"><img src="https://img.halfrost.com/Leetcode/Cookbook_PWA_iPad_example1__.png"></a>
<a href="https://books.halfrost.com/leetcode/"><img src="https://img.halfrost.com/Leetcode/Cookbook_PWA_iPad_example2__.png"></a>
</p>
## Data Structures
> 标识了 ✅ 的专题是完成所有题目了的,没有标识的是还没有做完所有题目的
<a href="https://books.halfrost.com/leetcode/"><img src="./website/static/logo.png" alt="logo" height="550" align="right" /></a>
* [Array](#array)
* [String](#string)
* [✅ Two Pointers](#two-pointers)
* [✅ Linked List](#linked-list)
* [✅ Stack](#stack)
* [Tree](#tree)
* [Dynamic programming](#dynamic-programming)
* [✅ Backtracking](#backtracking)
* [Depth First Search](#depth-first-search)
* [Breadth First Search](#breadth-first-search)
* [Binary Search](#binary-search)
* [Math](#math)
* [Hash Table](#hash-table)
* [✅ Sort](#sort)
* [✅ Bit Manipulation](#bit-manipulation)
* [✅ Union Find](#union-find)
* [✅ Sliding Window](#sliding-window)
* [✅ Segment Tree](#segment-tree)
* [✅ Binary Indexed Tree](#binary-indexed-tree)
<br>
<br>
| 数据结构 | 变种 | 相关题目 | 讲解文章 |
|:-------:|:-------|:------|:------|
|顺序线性表:向量||||
|单链表|1. 双向链表<br>2. 静态链表<br>3. 对称矩阵<br>4. 稀疏矩阵|||
|哈希表|1. 散列函数<br>2. 解决碰撞/填充因子<br>|||
|栈和队列|1. 广义栈<br>2. 双端队列<br>|||
|队列|1. 链表实现<br>2. 循环数组实现<br>3. 双端队列|||
|字符串|1. KMP算法<br>2. 有限状态自动机<br>3. 模式匹配有限状态自动机<br>4. BM 模式匹配算法<br>5. BM-KMP 算法<br>6. BF 算法|||
|树|1. 二叉树<br>2. 并查集<br>3. Huffman 树|||
|数组实现的堆|1. 极大堆和极小堆<br>2. 极大极小堆<br>3. 双端堆<br>4. d 叉堆|||
|树实现的堆|1. 左堆<br>2. 扁堆<br>3. 二项式堆<br>4. 斐波那契堆<br>5. 配对堆|||
|查找|1. 哈希表<br>2. 跳跃表<br>3. 排序二叉树<br>4. AVL 树<br>5. B 树 / B+ 树 / B* 树<br>6. AA 树<br>7. 红黑树<br>8. 排序二叉堆<br>9. Splay 树<br>10. 双链树<br>11. Trie 树<br>12. R 树|||
|--------------------------------------------|--------------------------------------------------------------------------------------------|---------------------------|-----------------------------------|
## Algorithm
| 算法 | 具体类型 | 相关题目 | 讲解文章 |
|:-------:|:-------|:------|:------|
|排序算法|1. 冒泡排序<br>2. 插入排序<br>3. 选择排序<br>4. 希尔 Shell 排序<br>5. 快速排序<br>6. 归并排序<br>7. 堆排序<br>8. 线性排序算法<br>9. 自省排序<br>10. 间接排序<br>11. 计数排序<br>12. 基数排序<br>13. 桶排序<br>14. 外部排序 - k 路归并败者树<br>15. 外部排序 - 最佳归并树|||
|递归与分治||1. 二分搜索/查找<br>2. 大整数的乘法<br>3. Strassen 矩阵乘法<br>4. 棋盘覆盖<br>5. 合并排序<br>6. 快速排序<br>7. 线性时间选择<br>8. 最接近点对问题<br>9. 循环赛日程表<br>||
|动态规划||1. 矩阵连乘问题<br>2. 最长公共子序列<br>3. 最大子段和<br>4. 凸多边形最优三角剖分<br>5. 多边形游戏<br>6. 图像压缩<br>7. 电路布线<br>8. 流水作业调度<br>9. 0-1 背包问题/背包九讲<br>10. 最优二叉搜索树<br>11. 动态规划加速原理<br>12. 树型 DP<br>||
|贪心||1. 活动安排问题<br>2. 最优装载<br>3. 哈夫曼编码<br>4. 单源最短路径<br>5. 最小生成树<br>6. 多机调度问题<br>||
|回溯法||1. 装载问题<br>2. 批处理作业调度<br>3. 符号三角形问题<br>4. n 后问题<br>5. 0-1 背包问题<br>6. 最大团问题<br>7. 图的 m 着色问题<br>8. 旅行售货员问题<br>9. 圆排列问题<br>10. 电路板排列问题<br>11. 连续邮资问题<br>||
|搜索|1. 枚举<br>2. DFS<br>3. BFS<br>4. 启发式搜索<br>|||
|随机化|1. 随机数<br>2. 数值随机化算法<br>3. Sherwood 舍伍德算法<br>4. Las Vegas 拉斯维加斯算法<br>5. Monte Carlo 蒙特卡罗算法<br>|1. 计算 π 值<br>2. 计算定积分<br>3. 解非线性方程组<br>4. 线性时间选择算法<br>5. 跳跃表<br>6. n 后问题<br>7. 整数因子分解<br>8. 主元素问题<br>9. 素数测试<br>||
|图论|1. 遍历 DFS / BFS<br>2. AOV / AOE 网络<br>3. Kruskal 算法(最小生成树)<br>4. Prim 算法(最小生成树)<br>5. Boruvka 算法(最小生成树)<br>6. Dijkstra 算法(单源最短路径)<br>7. Bellman-Ford 算法(单源最短路径)<br>8. SPFA 算法(单源最短路径)<br>9. Floyd 算法(多源最短路径)<br>10. Johnson 算法(多源最短路径)<br>11. Fleury 算法(欧拉回路)<br>12. Ford-Fulkerson 算法(最大网络流增广路)<br>13. Edmonds-Karp 算法(最大网络流)<br>14. Dinic 算法(最大网络流)<br>15. 一般预流推进算法<br>16. 最高标号预流推进 HLPP 算法<br>17. Primal-Dual 原始对偶算法(最小费用流)18. Kosaraju 算法(有向图强连通分量)<br>19. Tarjan 算法(有向图强连通分量)<br>20. Gabow 算法(有向图强连通分量)<br>21. 匈牙利算法(二分图匹配)<br>22. HopcroftKarp 算法(二分图匹配)<br>23. kuhn munkras 算法(二分图最佳匹配)<br>24. Edmonds Blossom-Contraction 算法(一般图匹配)<br>|1. 图遍历<br>2. 有向图和无向图的强弱连通性<br>3. 割点/割边<br>3. AOV 网络和拓扑排序<br>4. AOE 网络和关键路径<br>5. 最小代价生成树/次小生成树<br>6. 最短路径问题/第 K 短路问题<br>7. 最大网络流问题<br>8. 最小费用流问题<br>9. 图着色问题<br>10. 差分约束系统<br>11. 欧拉回路<br>12. 中国邮递员问题<br>13. 汉密尔顿回路<br>14. 最佳边割集/最佳点割集/最小边割集/最小点割集/最小路径覆盖/最小点集覆盖 <br>15. 边覆盖集<br>16. 二分图完美匹配和最大匹配问题<br>17. 仙人掌图<br>18. 弦图<br>19. 稳定婚姻问题<br>20. 最大团问题<br>||
|数论||1. 最大公约数<br> 2. 最小公倍数<br>3. 分解质因数<br>4. 素数判定<br>5. 进制转换<br>6. 高精度计算<br>7. 整除问题<br>8. 同余问题<br>9. 欧拉函数<br>10. 扩展欧几里得<br>11. 置换群<br>12. 母函数<br>13. 离散变换<br>14. 康托展开<br>15. 矩阵<br>16. 向量<br>17. 线性方程组<br>18. 线性规划<br> ||
|几何||1. 凸包 - Gift wrapping<br>2. 凸包 - Graham scan<br>3. 线段问题<br> 4. 多边形和多面体相关问题<br>||
|NP 完全|1. 计算模型<br>2. P 类与 NP 类问题<br>3. NP 完全问题<br>4. NP 完全问题的近似算法<br>|1. 随机存取机 RAM<br>2. 随机存取存储程序机 RASP<br>3. 图灵机<br>4. 非确定性图灵机<br>5. P 类与 NP 类语言<br>6. 多项式时间验证<br>7. 多项式时间变换<br>8. Cook定理<br>9. 合取范式的可满足性问题 CNF-SAT<br>10. 3 元合取范式的可满足性问题 3-SAT<br>11. 团问题 CLIQUE<br>12. 顶点覆盖问题 VERTEX-COVER<br>13. 子集和问题 SUBSET-SUM<br>14. 哈密顿回路问题 HAM-CYCLE<br>15. 旅行售货员问题 TSP<br>16. 顶点覆盖问题的近似算法<br>17. 旅行售货员问题近似算法<br>18. 具有三角不等式性质的旅行售货员问题<br>19. 一般的旅行售货员问题<br>20. 集合覆盖问题的近似算法<br>21. 子集和问题的近似算法<br>22. 子集和问题的指数时间算法<br>23. 子集和问题的多项式时间近似格式<br>||
|------------|------------------------------------------------------------------|-----------------------------------------------------------------|--------------------|
## LeetCode Problems
## 一. 个人数据
{{.PersonalData}}
## 二. 目录
{{.TotalNum}}
{{.AvailableTable}}
------------------------------------------------------------------
下面这些是免费的算法题,但是暂时还不能使用 Go 解答的:
暂无
------------------------------------------------------------------
## 三.分类
## Array
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Array/)
## String
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/String/)
## Two Pointers
![](./topic/Two_pointers.png)
- 双指针滑动窗口的经典写法。右指针不断往右移,移动到不能往右移动为止(具体条件根据题目而定)。当右指针到最右边以后,开始挪动左指针,释放窗口左边界。第 3 题,第 76 题,第 209 题,第 424 题,第 438 题,第 567 题,第 713 题,第 763 题,第 845 题,第 881 题,第 904 题,第 978 题,第 992 题,第 1004 题,第 1040 题,第 1052 题。
```c
left, right := 0, -1
for left < len(s) {
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
freq[s[right+1]-'a']++
right++
} else {
freq[s[left]-'a']--
left++
}
result = max(result, right-left+1)
}
```
- 快慢指针可以查找重复数字,时间复杂度 O(n),第 287 题。
- 替换字母以后,相同字母能出现连续最长的长度。第 424 题。
- SUM 问题集。第 1 题,第 15 题,第 16 题,第 18 题,第 167 题,第 923 题,第 1074 题。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Two_Pointers/)
## Linked List
![](./topic/Linked_List.png)
- 巧妙的构造虚拟头结点。可以使遍历处理逻辑更加统一。
- 灵活使用递归。构造递归条件,使用递归可以巧妙的解题。不过需要注意有些题目不能使用递归,因为递归深度太深会导致超时和栈溢出。
- 链表区间逆序。第 92 题。
- 链表寻找中间节点。第 876 题。链表寻找倒数第 n 个节点。第 19 题。只需要一次遍历就可以得到答案。
- 合并 K 个有序链表。第 21 题,第 23 题。
- 链表归类。第 86 题,第 328 题。
- 链表排序,时间复杂度要求 O(n * log n),空间复杂度 O(1)。只有一种做法,归并排序,至顶向下归并。第 148 题。
- 判断链表是否存在环,如果有环,输出环的交叉点的下标;判断 2 个链表是否有交叉点,如果有交叉点,输出交叉点。第 141 题,第 142 题,第 160 题。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Linked_List/)
## Stack
![](./topic/Stack.png)
- 括号匹配问题及类似问题。第 20 题,第 921 题,第 1021 题。
- 栈的基本 pop 和 push 操作。第 71 题,第 150 题,第 155 题,第 224 题,第 225 题,第 232 题,第 946 题,第 1047 题。
- 利用栈进行编码问题。第 394 题,第 682 题,第 856 题,第 880 题。
- **单调栈**。**利用栈维护一个单调递增或者递减的下标数组**。第 84 题,第 456 题,第 496 题,第 503 题,第 739 题,第 901 题,第 907 题,第 1019 题。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Stack/)
## Tree
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Tree/)
## Dynamic Programming
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Dynamic_Programming/)
## Backtracking
![](./topic/Backtracking.png)
- 排列问题 Permutations。第 46 题,第 47 题。第 60 题,第 526 题,第 996 题。
- 组合问题 Combination。第 39 题,第 40 题,第 77 题,第 216 题。
- 排列和组合杂交问题。第 1079 题。
- N 皇后终极解法(二进制解法)。第 51 题,第 52 题。
- 数独问题。第 37 题。
- 四个方向搜索。第 79 题,第 212 题,第 980 题。
- 子集合问题。第 78 题,第 90 题。
- Trie。第 208 题,第 211 题。
- BFS 优化。第 126 题,第 127 题。
- DFS 模板。(只是一个例子,不对应任何题)
```go
func combinationSum2(candidates []int, target int) [][]int {
if len(candidates) == 0 {
return [][]int{}
}
c, res := []int{}, [][]int{}
sort.Ints(candidates)
findcombinationSum2(candidates, target, 0, c, &res)
return res
}
func findcombinationSum2(nums []int, target, index int, c []int, res *[][]int) {
if target == 0 {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
return
}
for i := index; i < len(nums); i++ {
if i > index && nums[i] == nums[i-1] { // 这里是去重的关键逻辑
continue
}
if target >= nums[i] {
c = append(c, nums[i])
findcombinationSum2(nums, target-nums[i], i+1, c, res)
c = c[:len(c)-1]
}
}
}
```
- BFS 模板。(只是一个例子,不对应任何题)
```go
func updateMatrix_BFS(matrix [][]int) [][]int {
res := make([][]int, len(matrix))
if len(matrix) == 0 || len(matrix[0]) == 0 {
return res
}
queue := make([][]int, 0)
for i, _ := range matrix {
res[i] = make([]int, len(matrix[0]))
for j, _ := range res[i] {
if matrix[i][j] == 0 {
res[i][j] = -1
queue = append(queue, []int{i, j})
}
}
}
level := 1
for len(queue) > 0 {
size := len(queue)
for size > 0 {
size -= 1
node := queue[0]
queue = queue[1:]
i, j := node[0], node[1]
for _, direction := range [][]int{{-1, 0}, {1, 0}, {0, 1}, {0, -1}} {
x := i + direction[0]
y := j + direction[1]
if x < 0 || x >= len(matrix) || y < 0 || y >= len(matrix[0]) || res[x][y] < 0 || res[x][y] > 0 {
continue
}
res[x][y] = level
queue = append(queue, []int{x, y})
}
}
level++
}
for i, row := range res {
for j, cell := range row {
if cell == -1 {
res[i][j] = 0
}
}
}
return res
}
```
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Backtracking/)
## Depth First Search
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Depth_First_Search/)
## Breadth First Search
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Breadth_First_Search/)
## Binary Search
![]()
- 二分搜索的经典写法。需要注意的三点:
1. 循环退出条件,注意是 low <= high而不是 low < high
2. mid 的取值mid := low + (high-low)>>1
3. low 和 high 的更新。low = mid + 1high = mid - 1。
```go
func binarySearchMatrix(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
```
- 二分搜索的变种写法。有 4 个基本变种:
1. 查找第一个与 target 相等的元素,时间复杂度 O(logn)
2. 查找最后一个与 target 相等的元素,时间复杂度 O(logn)
3. 查找第一个大于等于 target 的元素,时间复杂度 O(logn)
4. 查找最后一个小于等于 target 的元素,时间复杂度 O(logn)
```go
// 二分查找第一个与 target 相等的元素,时间复杂度 O(logn)
func searchFirstEqualElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
} else {
if (mid == 0) || (nums[mid-1] != target) { // 找到第一个与 target 相等的元素
return mid
}
high = mid - 1
}
}
return -1
}
// 二分查找最后一个与 target 相等的元素,时间复杂度 O(logn)
func searchLastEqualElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
} else {
if (mid == len(nums)-1) || (nums[mid+1] != target) { // 找到最后一个与 target 相等的元素
return mid
}
low = mid + 1
}
}
return -1
}
// 二分查找第一个大于等于 target 的元素,时间复杂度 O(logn)
func searchFirstGreaterElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] >= target {
if (mid == 0) || (nums[mid-1] < target) { // 找到第一个大于等于 target 的元素
return mid
}
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// 二分查找最后一个小于等于 target 的元素,时间复杂度 O(logn)
func searchLastLessElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] <= target {
if (mid == len(nums)-1) || (nums[mid+1] > target) { // 找到最后一个小于等于 target 的元素
return mid
}
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
```
- 在基本有序的数组中用二分搜索。经典解法可以解,变种写法也可以写,常见的题型,在山峰数组中找山峰,在旋转有序数组中找分界点。第 33 题,第 81 题,第 153 题,第 154 题,第 162 题,第 852 题
```go
func peakIndexInMountainArray(A []int) int {
low, high := 0, len(A)-1
for low < high {
mid := low + (high-low)>>1
// 如果 mid 较大则左侧存在峰值high = m如果 mid + 1 较大则右侧存在峰值low = mid + 1
if A[mid] > A[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}
```
- max-min 最大值最小化问题。求在最小满足条件的情况下的最大值。第 410 题,第 875 题,第 1011 题,第 1283 题。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Binary_Search/)
## Math
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Math/)
## Hash Table
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Hash_Table/)
## Sort
![](./topic/Sort.png)
- 深刻的理解多路快排。第 75 题。
- 链表的排序,插入排序(第 147 题)和归并排序(第 148 题)
- 桶排序和基数排序。第 164 题。
- "摆动排序"。第 324 题。
- 两两不相邻的排序。第 767 题,第 1054 题。
- "饼子排序"。第 969 题。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Sort/)
## Bit Manipulation
![](./topic/Bit_Manipulation.png)
- 异或的特性。第 136 题,第 268 题,第 389 题,第 421 题,
```go
x ^ 0 = x
x ^ 11111……1111 = ~x
x ^ (~x) = 11111……1111
x ^ x = 0
a ^ b = c => a ^ c = b => b ^ c = a (交换律)
a ^ b ^ c = a ^ (b ^ c) = (a ^ b^ c (结合律)
```
- 构造特殊 Mask将特殊位置放 0 或 1。
```go
x 最右边的 n 位清零 x & ( ~0 << n )
获取 x 的第 n 位值(0 或者 1)(x >> n) & 1
获取 x 的第 n 位的幂值x & (1 << (n - 1))
仅将第 n 位置为 1x | (1 << n)
仅将第 n 位置为 0x & (~(1 << n))
x 最高位至第 n ()清零x & ((1 << n) - 1)
将第 n 位至第 0 ()清零x & (~((1 << (n + 1)) - 1)
```
- 有特殊意义的 & 位操作运算。第 260 题,第 201 题,第 318 题,第 371 题,第 397 题,第 461 题,第 693 题,
```go
X & 1 == 1 判断是否是奇数(偶数)
X & = (X - 1) 将最低位(LSB) 1 清零
X & -X 得到最低位(LSB) 1
X & ~X = 0
```
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Bit_Manipulation/)
## Union Find
![](./topic/Union_Find.png)
- 灵活使用并查集的思想,熟练掌握并查集的[模板](https://github.com/halfrost/LeetCode-Go/blob/master/template/UnionFind.go),模板中有两种并查集的实现方式,一种是路径压缩 + 秩优化的版本,另外一种是计算每个集合中元素的个数 + 最大集合元素个数的版本,这两种版本都有各自使用的地方。能使用第一类并查集模板的题目有:第 128 题,第 130 题,第 547 题,第 684 题,第 721 题,第 765 题,第 778 题,第 839 题,第 924 题,第 928 题,第 947 题,第 952 题,第 959 题,第 990 题。能使用第二类并查集模板的题目有:第 803 题,第 952 题。第 803 题秩优化和统计集合个数这些地方会卡时间,如果不优化,会 TLE。
- 并查集是一种思想,有些题需要灵活使用这种思想,而不是死套模板,如第 399 题,这一题是 stringUnionFind利用并查集思想实现的。这里每个节点是基于字符串和 map 的,而不是单纯的用 int 节点编号实现的。
- 有些题死套模板反而做不出来,比如第 685 题,这一题不能路径压缩和秩优化,因为题目中涉及到有向图,需要知道节点的前驱节点,如果路径压缩了,这一题就没法做了。这一题不需要路径压缩和秩优化。
- 灵活的抽象题目给的信息,将给定的信息合理的编号,使用并查集解题,并用 map 降低时间复杂度,如第 721 题,第 959 题。
- 关于地图,砖块,网格的题目,可以新建一个特殊节点,将四周边缘的砖块或者网格都 union() 到这个特殊节点上。第 130 题,第 803 题。
- 能用并查集的题目,一般也可以用 DFS 和 BFS 解答,只不过时间复杂度会高一点。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Union_Find/)
## Sliding Window
![](./topic/Sliding_Window.png)
- 双指针滑动窗口的经典写法。右指针不断往右移,移动到不能往右移动为止(具体条件根据题目而定)。当右指针到最右边以后,开始挪动左指针,释放窗口左边界。第 3 题,第 76 题,第 209 题,第 424 题,第 438 题,第 567 题,第 713 题,第 763 题,第 845 题,第 881 题,第 904 题,第 978 题,第 992 题,第 1004 题,第 1040 题,第 1052 题。
```c
left, right := 0, -1
for left < len(s) {
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
freq[s[right+1]-'a']++
right++
} else {
freq[s[left]-'a']--
left++
}
result = max(result, right-left+1)
}
```
- 滑动窗口经典题。第 239 题,第 480 题。
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Sliding_Window/)
## Segment Tree
![](./topic/Segment_Tree.png)
- 线段树的经典数组实现写法。将合并两个节点 pushUp 逻辑抽象出来了,可以实现任意操作(常见的操作有:加法,取 maxmin 等等)。第 218 题,第 303 题,第 307 题,第 699 题。
- 计数线段树的经典写法。第 315 题,第 327 题,第 493 题。
- 线段树的树的实现写法。第 715 题,第 732 题。
- 区间懒惰更新。第 218 题,第 699 题。
- 离散化。离散化需要注意一个特殊情况:假如三个区间为 [1,10] [1,4] [6,10],离散化后 x[1]=1,x[2]=4,x[3]=6,x[4]=10。第一个区间为 [1,4],第二个区间为 [1,2],第三个区间为 [3,4],这样一来,区间一 = 区间二 + 区间三,这和离散前的模型不符,离散前,很明显,区间一 > 区间二 + 区间三。正确的做法是:在相差大于 1 的数间加一个数,例如在上面 1 4 6 10 中间加 5即可 x[1]=1,x[2]=4,x[3]=5,x[4]=6,x[5]=10。这样处理之后区间一是 1-5 ,区间二是 1-2 ,区间三是 4-5 。
- 灵活构建线段树。线段树节点可以存储多条信息,合并两个节点的 pushUp 操作也可以是多样的。第 850 题,第 1157 题。
线段树[题型](https://blog.csdn.net/xuechelingxiao/article/details/38313105)从简单到困难:
1. 单点更新:
[HDU 1166 敌兵布阵](http://acm.hdu.edu.cn/showproblem.php?pid=1166) update:单点增减 query:区间求和
[HDU 1754 I Hate It](http://acm.hdu.edu.cn/showproblem.php?pid=1754) update:单点替换 query:区间最值
[HDU 1394 Minimum Inversion Number](http://acm.hdu.edu.cn/showproblem.php?pid=1394) update:单点增减 query:区间求和
[HDU 2795 Billboard](http://acm.hdu.edu.cn/showproblem.php?pid=2795) query:区间求最大值的位子(直接把update的操作在query里做了)
2. 区间更新:
[HDU 1698 Just a Hook](http://acm.hdu.edu.cn/showproblem.php?pid=1698) update:成段替换 (由于只query一次总区间,所以可以直接输出 1 结点的信息)
[POJ 3468 A Simple Problem with Integers](http://poj.org/problem?id=3468) update:成段增减 query:区间求和
[POJ 2528 Mayors posters](http://poj.org/problem?id=2528) 离散化 + update:成段替换 query:简单hash
[POJ 3225 Help with Intervals](http://poj.org/problem?id=3225) update:成段替换,区间异或 query:简单hash
3. 区间合并(这类题目会询问区间中满足条件的连续最长区间,所以PushUp的时候需要对左右儿子的区间进行合并):
[POJ 3667 Hotel](http://poj.org/problem?id=3667) update:区间替换 query:询问满足条件的最左端点
4. 扫描线(这类题目需要将一些操作排序,然后从左到右用一根扫描线扫过去最典型的就是矩形面积并,周长并等题):
[HDU 1542 Atlantis](http://acm.hdu.edu.cn/showproblem.php?pid=1542) update:区间增减 query:直接取根节点的值
[HDU 1828 Picture](http://acm.hdu.edu.cn/showproblem.php?pid=1828) update:区间增减 query:直接取根节点的值
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Segment_Tree/)
## Binary Indexed Tree
![](./topic/Binary_Indexed_Tree.png)
Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Binary_Indexed_Tree/)
----------------------------------------------------------------------------------------
<p align='center'>
<a href="https://github.com/halfrost/LeetCode-Go/releases/tag/Special"><img src="https://img.halfrost.com/Leetcode/ACM-ICPC_Algorithm_Template.png"></a>
</p>
Thank you for reading here. This is bonus. You can download my [《ACM-ICPC Algorithm Template》](https://github.com/halfrost/LeetCode-Go/releases/tag/Special/)
## ♥️ Thanks
Thanks for your Star
[![Stargazers over time](https://starchart.cc/halfrost/LeetCode-Go.svg)](https://starchart.cc/halfrost/LeetCode-Go)

38
ctl/template_render.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"bytes"
"fmt"
m "github.com/halfrost/LeetCode-Go/ctl/models"
"github.com/halfrost/LeetCode-Go/ctl/util"
"html/template"
"io/ioutil"
"os"
)
func makeReadmeFile(mdrows m.Mdrows) {
file := "./README.md"
os.Remove(file)
var b bytes.Buffer
tmpl := template.Must(template.New("readme").Parse(readTMPL("template.markdown")))
err := tmpl.Execute(&b, mdrows)
if err != nil {
fmt.Println(err)
}
// 保存 README.md 文件
util.WriteFile(file, b.Bytes())
}
func readTMPL(path string) string {
file, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
return string(data)
}

185
ctl/util/util.go Normal file
View File

@ -0,0 +1,185 @@
package util
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
// LoadSolutionsDir define
func LoadSolutionsDir() ([]int, []string, int) {
solutionIds, soNames, total := loadFile("../leetcode/")
fmt.Printf("读取了 %v 道题的题解,当前目录下有 %v 个文件(可能包含 .DS_Store),目录中有 %v 道题在尝试中\n", len(solutionIds), total, total-len(solutionIds))
return solutionIds, soNames, total - len(solutionIds)
}
func loadFile(path string) ([]int, []string, int) {
files, err := ioutil.ReadDir(path)
if err != nil {
fmt.Println(err)
}
solutionIds, soNames, solutionsMap := []int{}, []string{}, map[int]string{}
for _, f := range files {
if f.Name()[4] == '.' {
tmp, err := strconv.Atoi(f.Name()[:4])
if err != nil {
fmt.Println(err)
}
solutionIds = append(solutionIds, tmp)
solutionsMap[tmp] = f.Name()
}
}
sort.Ints(solutionIds)
for _, v := range solutionIds {
if name, ok := solutionsMap[v]; ok {
soNames = append(soNames, name)
}
}
return solutionIds, soNames, len(files)
}
// GetAllFile define
func GetAllFile(pathname string, fileList *[]string) ([]string, error) {
rd, err := ioutil.ReadDir(pathname)
for _, fi := range rd {
if fi.IsDir() {
//fmt.Printf("[%s]\n", pathname+"\\"+fi.Name())
GetAllFile(pathname+fi.Name()+"/", fileList)
} else {
//fmt.Println(fi.Name())
*fileList = append(*fileList, fi.Name())
}
}
return *fileList, err
}
// LoadChapterFourDir define
func LoadChapterFourDir() ([]string, []int) {
files, err := GetAllFile("../website/content/ChapterFour/", &[]string{})
// files, err := ioutil.ReadDir("../website/content/ChapterFour/")
if err != nil {
fmt.Println(err)
}
solutions, solutionIds, solutionsMap := []string{}, []int{}, map[int]string{}
for _, f := range files {
if f[4] == '.' {
tmp, err := strconv.Atoi(f[:4])
if err != nil {
fmt.Println(err)
}
solutionIds = append(solutionIds, tmp)
// len(f.Name())-3 = 文件名去掉 .md 后缀
solutionsMap[tmp] = f[:len(f)-3]
}
}
sort.Ints(solutionIds)
fmt.Printf("读取了第四章的 %v 道题的题解\n", len(solutionIds))
for _, v := range solutionIds {
if name, ok := solutionsMap[v]; ok {
solutions = append(solutions, name)
}
}
return solutions, solutionIds
}
// WriteFile define
func WriteFile(fileName string, content []byte) {
file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
}
defer file.Close()
_, err = file.Write(content)
if err != nil {
fmt.Println(err)
}
//fmt.Println("write file successful")
}
// LoadFile define
func LoadFile(filePath string) ([]byte, error) {
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
reader, output := bufio.NewReader(f), []byte{}
for {
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return output, nil
}
return nil, err
}
output = append(output, line...)
output = append(output, []byte("\n")...)
}
}
// DestoryDir define
func DestoryDir(path string) {
filepath.Walk(path, func(path string, fi os.FileInfo, err error) error {
if nil == fi {
return err
}
if !fi.IsDir() {
return nil
}
name := fi.Name()
if strings.Contains(name, "temp") {
fmt.Println("temp file name:", path)
err := os.RemoveAll(path)
if err != nil {
fmt.Println("delet dir error:", err)
}
}
return nil
})
}
// CopyFile define
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
defer src.Close()
dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return
}
defer dst.Close()
return io.Copy(dst, src)
}
// BinarySearch define
func BinarySearch(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// GetChpaterFourFileNum define
func GetChpaterFourFileNum(num int) string {
if num < 100 {
return fmt.Sprintf("%04d~%04d", (num/100)*100+1, (num/100)*100+99)
}
return fmt.Sprintf("%04d~%04d", (num/100)*100, (num/100)*100+99)
}

18
ctl/version.go Normal file
View File

@ -0,0 +1,18 @@
package main
import (
"fmt"
"github.com/spf13/cobra"
)
var (
version = "v1.0"
versionCmd = &cobra.Command{
Use: "version",
Short: "Prints the version of tacoctl",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("tacoctl version:", version)
},
}
)

13
go.mod Normal file
View File

@ -0,0 +1,13 @@
module github.com/halfrost/LeetCode-Go
go 1.15
require (
github.com/BurntSushi/toml v0.3.1
github.com/bitly/go-simplejson v0.5.0 // indirect
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect
github.com/mozillazg/request v0.8.0
github.com/spf13/cobra v1.1.1
github.com/stretchr/testify v1.3.0
golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect
)

303
go.sum Normal file
View File

@ -0,0 +1,303 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkNEM+Y=
github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA=
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mozillazg/request v0.8.0 h1:TbXeQUdBWr1J1df5Z+lQczDFzX9JD71kTCl7Zu/9rNM=
github.com/mozillazg/request v0.8.0/go.mod h1:weoQ/mVFNbWgRBtivCGF1tUT9lwneFesues+CleXMWc=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4=
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=

View File

@ -26,32 +26,30 @@ type ans1 struct {
func Test_Problem1(t *testing.T) {
qs := []question1{
question1{
{
para1{[]int{3, 2, 4}, 6},
ans1{[]int{1, 2}},
},
question1{
{
para1{[]int{3, 2, 4}, 5},
ans1{[]int{0, 1}},
},
question1{
{
para1{[]int{0, 8, 7, 3, 3, 4, 2}, 11},
ans1{[]int{1, 3}},
},
question1{
{
para1{[]int{0, 1}, 1},
ans1{[]int{0, 1}},
},
question1{
{
para1{[]int{0, 3}, 5},
ans1{[]int{}},
},
// 如需多个测试,可以复制上方元素。
}

View File

@ -16,36 +16,24 @@ type ListNode = structures.ListNode
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil || l2 == nil {
return nil
}
head := &ListNode{Val: 0, Next: nil}
current := head
carry := 0
for l1 != nil || l2 != nil {
var x, y int
head := &ListNode{Val: 0}
n1, n2, carry, current := 0, 0, 0, head
for l1 != nil || l2 != nil || carry != 0 {
if l1 == nil {
x = 0
n1 = 0
} else {
x = l1.Val
}
if l2 == nil {
y = 0
} else {
y = l2.Val
}
current.Next = &ListNode{Val: (x + y + carry) % 10, Next: nil}
current = current.Next
carry = (x + y + carry) / 10
if l1 != nil {
n1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
if l2 == nil {
n2 = 0
} else {
n2 = l2.Val
l2 = l2.Next
}
}
if carry > 0 {
current.Next = &ListNode{Val: carry % 10, Next: nil}
current.Next = &ListNode{Val: (n1 + n2 + carry) % 10}
current = current.Next
carry = (n1 + n2 + carry) / 10
}
return head.Next
}

View File

@ -29,42 +29,42 @@ func Test_Problem2(t *testing.T) {
qs := []question2{
question2{
{
para2{[]int{}, []int{}},
ans2{[]int{}},
},
question2{
{
para2{[]int{1}, []int{1}},
ans2{[]int{2}},
},
question2{
{
para2{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}},
ans2{[]int{2, 4, 6, 8}},
},
question2{
{
para2{[]int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}},
ans2{[]int{2, 4, 6, 8, 0, 1}},
},
question2{
{
para2{[]int{1}, []int{9, 9, 9, 9, 9}},
ans2{[]int{0, 0, 0, 0, 0, 1}},
},
question2{
{
para2{[]int{9, 9, 9, 9, 9}, []int{1}},
ans2{[]int{0, 0, 0, 0, 0, 1}},
},
question2{
{
para2{[]int{2, 4, 3}, []int{5, 6, 4}},
ans2{[]int{7, 0, 8}},
},
question2{
{
para2{[]int{1, 8, 3}, []int{7, 1}},
ans2{[]int{8, 9, 3}},
},

View File

@ -26,22 +26,22 @@ func Test_Problem3(t *testing.T) {
qs := []question3{
question3{
{
para3{"abcabcbb"},
ans3{3},
},
question3{
{
para3{"bbbbb"},
ans3{1},
},
question3{
{
para3{"pwwkew"},
ans3{3},
},
question3{
{
para3{""},
ans3{0},
},

View File

@ -27,12 +27,12 @@ func Test_Problem4(t *testing.T) {
qs := []question4{
question4{
{
para4{[]int{1, 3}, []int{2}},
ans4{2.0},
},
question4{
{
para4{[]int{1, 2}, []int{3, 4}},
ans4{2.5},
},

View File

@ -26,22 +26,22 @@ func Test_Problem7(t *testing.T) {
qs := []question7{
question7{
{
para7{321},
ans7{123},
},
question7{
{
para7{-123},
ans7{-321},
},
question7{
{
para7{120},
ans7{21},
},
question7{
{
para7{1534236469},
ans7{0},
},

View File

@ -26,37 +26,37 @@ func Test_Problem9(t *testing.T) {
qs := []question9{
question9{
{
para9{121},
ans9{true},
},
question9{
{
para9{-121},
ans9{false},
},
question9{
{
para9{10},
ans9{false},
},
question9{
{
para9{321},
ans9{false},
},
question9{
{
para9{-123},
ans9{false},
},
question9{
{
para9{120},
ans9{false},
},
question9{
{
para9{1534236469},
ans9{false},
},

View File

@ -26,12 +26,12 @@ func Test_Problem11(t *testing.T) {
qs := []question11{
question11{
{
para11{[]int{1, 8, 6, 2, 5, 4, 8, 3, 7}},
ans11{49},
},
question11{
{
para11{[]int{1, 1}},
ans11{1},
},

View File

@ -26,32 +26,32 @@ func Test_Problem13(t *testing.T) {
qs := []question13{
question13{
{
para13{"III"},
ans13{3},
},
question13{
{
para13{"IV"},
ans13{4},
},
question13{
{
para13{"IX"},
ans13{9},
},
question13{
{
para13{"LVIII"},
ans13{58},
},
question13{
{
para13{"MCMXCIV"},
ans13{1994},
},
question13{
{
para13{"MCMXICIVI"},
ans13{2014},
},

View File

@ -4,7 +4,41 @@ import (
"sort"
)
// 解法一 最优解,双指针 + 排序
func threeSum(nums []int) [][]int {
sort.Ints(nums)
result, start, end, index, addNum, length := make([][]int, 0), 0, 0, 0, 0, len(nums)
for index = 1; index < length-1; index++ {
start, end = 0, length-1
if index > 1 && nums[index] == nums[index-1] {
start = index - 1
}
for start < index && end > index {
if start > 0 && nums[start] == nums[start-1] {
start++
continue
}
if end < length-1 && nums[end] == nums[end+1] {
end--
continue
}
addNum = nums[start] + nums[end] + nums[index]
if addNum == 0 {
result = append(result, []int{nums[start], nums[index], nums[end]})
start++
end--
} else if addNum > 0 {
end--
} else {
start++
}
}
}
return result
}
// 解法二
func threeSum1(nums []int) [][]int {
res := [][]int{}
counter := map[int]int{}
for _, value := range nums {

View File

@ -26,26 +26,26 @@ func Test_Problem15(t *testing.T) {
qs := []question15{
question15{
{
para15{[]int{0, 0, 0}},
ans15{[][]int{[]int{0, 0, 0}}},
ans15{[][]int{{0, 0, 0}}},
},
question15{
{
para15{[]int{-1, 0, 1, 2, -1, -4}},
ans15{[][]int{[]int{-1, 0, 1}, []int{-1, -1, 2}}},
ans15{[][]int{{-1, 0, 1}, {-1, -1, 2}}},
},
question15{
{
para15{[]int{-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6}},
ans15{[][]int{[]int{-4, -2, 6}, []int{-4, 0, 4}, []int{-4, 1, 3}, []int{-4, 2, 2}, []int{-2, -2, 4}, []int{-2, 0, 2}}},
ans15{[][]int{{-4, -2, 6}, {-4, 0, 4}, {-4, 1, 3}, {-4, 2, 2}, {-2, -2, 4}, {-2, 0, 2}}},
},
question15{
{
para15{[]int{5, -7, 3, -3, 5, -10, 4, 8, -3, -8, -3, -3, -1, -8, 6, 4, -4, 7, 2, -5, -2, -7, -3, 7, 2, 4, -6, 5}},
ans15{[][]int{[]int{-10, 2, 8}, []int{-10, 3, 7}, []int{-10, 4, 6}, []int{-10, 5, 5}, []int{-8, 2, 6}, []int{-8, 3, 5}, []int{-8, 4, 4}, []int{-7, -1, 8},
[]int{-7, 2, 5}, []int{-7, 3, 4}, []int{-6, -2, 8}, []int{-6, -1, 7}, []int{-6, 2, 4}, []int{-5, -3, 8}, []int{-5, -2, 7}, []int{-5, -1, 6}, []int{-5, 2, 3},
[]int{-4, -3, 7}, []int{-4, -2, 6}, []int{-4, -1, 5}, []int{-4, 2, 2}, []int{-3, -3, 6}, []int{-3, -2, 5}, []int{-3, -1, 4}, []int{-2, -1, 3}}},
ans15{[][]int{{-10, 2, 8}, {-10, 3, 7}, {-10, 4, 6}, {-10, 5, 5}, {-8, 2, 6}, {-8, 3, 5}, {-8, 4, 4}, {-7, -1, 8},
{-7, 2, 5}, {-7, 3, 4}, {-6, -2, 8}, {-6, -1, 7}, {-6, 2, 4}, {-5, -3, 8}, {-5, -2, 7}, {-5, -1, 6}, {-5, 2, 3},
{-4, -3, 7}, {-4, -2, 6}, {-4, -1, 5}, {-4, 2, 2}, {-3, -3, 6}, {-3, -2, 5}, {-3, -1, 4}, {-2, -1, 3}}},
},
}

View File

@ -27,27 +27,27 @@ func Test_Problem16(t *testing.T) {
qs := []question16{
question16{
{
para16{[]int{-1, 0, 1, 1, 55}, 3},
ans16{2},
},
question16{
{
para16{[]int{0, 0, 0}, 1},
ans16{0},
},
question16{
{
para16{[]int{-1, 2, 1, -4}, 1},
ans16{2},
},
question16{
{
para16{[]int{1, 1, -1}, 0},
ans16{1},
},
question16{
{
para16{[]int{-1, 2, 1, -4}, 1},
ans16{2},
},

View File

@ -13,9 +13,11 @@ var (
"tuv", //8
"wxyz", //9
}
res = []string{}
res = []string{}
final = 0
)
// 解法一 DFS
func letterCombinations(digits string) []string {
if digits == "" {
return []string{}
@ -37,3 +39,66 @@ func findCombination(digits *string, index int, s string) {
}
return
}
// 解法二 非递归
func letterCombinations_(digits string) []string {
if digits == "" {
return []string{}
}
index := digits[0] - '0'
letter := letterMap[index]
tmp := []string{}
for i := 0; i < len(letter); i++ {
if len(res) == 0 {
res = append(res, "")
}
for j := 0; j < len(res); j++ {
tmp = append(tmp, res[j]+string(letter[i]))
}
}
res = tmp
final++
letterCombinations(digits[1:])
final--
if final == 0 {
tmp = res
res = []string{}
}
return tmp
}
// 解法三 回溯参考回溯模板类似DFS
var result []string
var dict = map[string][]string{
"2": {"a", "b", "c"},
"3": {"d", "e", "f"},
"4": {"g", "h", "i"},
"5": {"j", "k", "l"},
"6": {"m", "n", "o"},
"7": {"p", "q", "r", "s"},
"8": {"t", "u", "v"},
"9": {"w", "x", "y", "z"},
}
func letterCombinationsBT(digits string) []string {
result = []string{}
if digits == "" {
return result
}
letterFunc("", digits)
return result
}
func letterFunc(res string, digits string) {
if digits == "" {
result = append(result, res)
return
}
k := digits[0:1]
digits = digits[1:]
for i := 0; i < len(dict[k]); i++ {
res += dict[k][i]
letterFunc(res, digits)
res = res[0 : len(res)-1]
}
}

View File

@ -26,7 +26,7 @@ func Test_Problem17(t *testing.T) {
qs := []question17{
question17{
{
para17{"23"},
ans17{[]string{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}},
},

View File

@ -27,29 +27,29 @@ func Test_Problem18(t *testing.T) {
qs := []question18{
question18{
{
para18{[]int{1, 1, 1, 1}, 4},
ans18{[][]int{[]int{1, 1, 1, 1}}},
ans18{[][]int{{1, 1, 1, 1}}},
},
question18{
{
para18{[]int{0, 1, 5, 0, 1, 5, 5, -4}, 11},
ans18{[][]int{[]int{-4, 5, 5, 5}, []int{0, 1, 5, 5}}},
ans18{[][]int{{-4, 5, 5, 5}, {0, 1, 5, 5}}},
},
question18{
{
para18{[]int{1, 0, -1, 0, -2, 2}, 0},
ans18{[][]int{[]int{-1, 0, 0, 1}, []int{-2, -1, 1, 2}, []int{-2, 0, 0, 2}}},
ans18{[][]int{{-1, 0, 0, 1}, {-2, -1, 1, 2}, {-2, 0, 0, 2}}},
},
question18{
{
para18{[]int{1, 0, -1, 0, -2, 2, 0, 0, 0, 0}, 0},
ans18{[][]int{[]int{-1, 0, 0, 1}, []int{-2, -1, 1, 2}, []int{-2, 0, 0, 2}, []int{0, 0, 0, 0}}},
ans18{[][]int{{-1, 0, 0, 1}, {-2, -1, 1, 2}, {-2, 0, 0, 2}, {0, 0, 0, 0}}},
},
question18{
{
para18{[]int{1, 0, -1, 0, -2, 2, 0, 0, 0, 0}, 1},
ans18{[][]int{[]int{-1, 0, 0, 2}, []int{-2, 0, 1, 2}, []int{0, 0, 0, 1}}},
ans18{[][]int{{-1, 0, 0, 2}, {-2, 0, 1, 2}, {0, 0, 0, 1}}},
},
}

View File

@ -29,26 +29,26 @@ func Test_Problem19(t *testing.T) {
qs := []question19{
question19{
{
para19{[]int{1, 2, 3, 4, 5}, 1},
ans19{[]int{1, 2, 3, 4}},
},
question19{
{
para19{[]int{1, 2, 3, 4, 5}, 2},
ans19{[]int{1, 2, 3, 5}},
},
question19{
{
para19{[]int{1, 2, 3, 4, 5}, 3},
ans19{[]int{1, 2, 4, 5}},
},
question19{
{
para19{[]int{1, 2, 3, 4, 5}, 4},
ans19{[]int{1, 3, 4, 5}},
},
question19{
{
para19{[]int{1, 2, 3, 4, 5}, 5},
ans19{[]int{2, 3, 4, 5}},
},

View File

@ -26,35 +26,35 @@ func Test_Problem20(t *testing.T) {
qs := []question20{
question20{
{
para20{"()[]{}"},
ans20{true},
},
question20{
{
para20{"(]"},
ans20{false},
},
question20{
{
para20{"({[]})"},
ans20{true},
},
question20{
{
para20{"(){[({[]})]}"},
ans20{true},
},
question20{
{
para20{"((([[[{{{"},
ans20{false},
},
question20{
{
para20{"(())]]"},
ans20{false},
},
question20{
{
para20{""},
ans20{true},
},
question20{
{
para20{"["},
ans20{false},
},

View File

@ -29,42 +29,42 @@ func Test_Problem21(t *testing.T) {
qs := []question21{
question21{
{
para21{[]int{}, []int{}},
ans21{[]int{}},
},
question21{
{
para21{[]int{1}, []int{1}},
ans21{[]int{1, 1}},
},
question21{
{
para21{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}},
ans21{[]int{1, 1, 2, 2, 3, 3, 4, 4}},
},
question21{
{
para21{[]int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}},
ans21{[]int{1, 1, 2, 2, 3, 3, 4, 4, 5, 5}},
},
question21{
{
para21{[]int{1}, []int{9, 9, 9, 9, 9}},
ans21{[]int{1, 9, 9, 9, 9, 9}},
},
question21{
{
para21{[]int{9, 9, 9, 9, 9}, []int{1}},
ans21{[]int{1, 9, 9, 9, 9, 9}},
},
question21{
{
para21{[]int{2, 3, 4}, []int{4, 5, 6}},
ans21{[]int{2, 3, 4, 4, 5, 6}},
},
question21{
{
para21{[]int{1, 3, 8}, []int{1, 7}},
ans21{[]int{1, 1, 3, 7, 8}},
},

View File

@ -26,7 +26,7 @@ func Test_Problem22(t *testing.T) {
qs := []question22{
question22{
{
para22{3},
ans22{[]string{
"((()))",

View File

@ -28,63 +28,63 @@ func Test_Problem23(t *testing.T) {
qs := []question23{
question23{
{
para23{[][]int{}},
ans23{[]int{}},
},
question23{
{
para23{[][]int{
[]int{1},
[]int{1},
{1},
{1},
}},
ans23{[]int{1, 1}},
},
question23{
{
para23{[][]int{
[]int{1, 2, 3, 4},
[]int{1, 2, 3, 4},
{1, 2, 3, 4},
{1, 2, 3, 4},
}},
ans23{[]int{1, 1, 2, 2, 3, 3, 4, 4}},
},
question23{
{
para23{[][]int{
[]int{1, 2, 3, 4, 5},
[]int{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
}},
ans23{[]int{1, 1, 2, 2, 3, 3, 4, 4, 5, 5}},
},
question23{
{
para23{[][]int{
[]int{1},
[]int{9, 9, 9, 9, 9},
{1},
{9, 9, 9, 9, 9},
}},
ans23{[]int{1, 9, 9, 9, 9, 9}},
},
question23{
{
para23{[][]int{
[]int{9, 9, 9, 9, 9},
[]int{1},
{9, 9, 9, 9, 9},
{1},
}},
ans23{[]int{1, 9, 9, 9, 9, 9}},
},
question23{
{
para23{[][]int{
[]int{2, 3, 4},
[]int{4, 5, 6},
{2, 3, 4},
{4, 5, 6},
}},
ans23{[]int{2, 3, 4, 4, 5, 6}},
},
question23{
{
para23{[][]int{
[]int{1, 3, 8},
[]int{1, 7},
{1, 3, 8},
{1, 7},
}},
ans23{[]int{1, 1, 3, 7, 8}},
},

View File

@ -28,22 +28,22 @@ func Test_Problem24(t *testing.T) {
qs := []question24{
question24{
{
para24{[]int{}},
ans24{[]int{}},
},
question24{
{
para24{[]int{1}},
ans24{[]int{1}},
},
question24{
{
para24{[]int{1, 2, 3, 4}},
ans24{[]int{2, 1, 4, 3}},
},
question24{
{
para24{[]int{1, 2, 3, 4, 5}},
ans24{[]int{2, 1, 4, 3, 5}},
},

View File

@ -29,7 +29,7 @@ func Test_Problem25(t *testing.T) {
qs := []question25{
question25{
{
para25{
[]int{1, 2, 3, 4, 5},
3,
@ -37,7 +37,7 @@ func Test_Problem25(t *testing.T) {
ans25{[]int{3, 2, 1, 4, 5}},
},
question25{
{
para25{
[]int{1, 2, 3, 4, 5},
1,

View File

@ -26,22 +26,22 @@ func Test_Problem26(t *testing.T) {
qs := []question26{
question26{
{
para26{[]int{1, 1, 2}},
ans26{2},
},
question26{
{
para26{[]int{0, 0, 1, 1, 1, 1, 2, 3, 4, 4}},
ans26{5},
},
question26{
{
para26{[]int{0, 0, 0, 0, 0}},
ans26{1},
},
question26{
{
para26{[]int{1}},
ans26{1},
},

View File

@ -9,10 +9,8 @@ func removeElement(nums []int, val int) int {
if nums[i] != val {
if i != j {
nums[i], nums[j] = nums[j], nums[i]
j++
} else {
j++
}
j++
}
}
return j

View File

@ -27,32 +27,32 @@ func Test_Problem27(t *testing.T) {
qs := []question27{
question27{
{
para27{[]int{1, 0, 1}, 1},
ans27{1},
},
question27{
{
para27{[]int{0, 1, 0, 3, 0, 12}, 0},
ans27{3},
},
question27{
{
para27{[]int{0, 1, 0, 3, 0, 0, 0, 0, 1, 12}, 0},
ans27{4},
},
question27{
{
para27{[]int{0, 0, 0, 0, 0}, 0},
ans27{0},
},
question27{
{
para27{[]int{1}, 1},
ans27{0},
},
question27{
{
para27{[]int{0, 1, 2, 2, 3, 0, 4, 2}, 2},
ans27{5},
},

View File

@ -27,32 +27,32 @@ func Test_Problem28(t *testing.T) {
qs := []question28{
question28{
{
para28{"abab", "ab"},
ans28{0},
},
question28{
{
para28{"hello", "ll"},
ans28{2},
},
question28{
{
para28{"", "abc"},
ans28{0},
},
question28{
{
para28{"abacbabc", "abc"},
ans28{5},
},
question28{
{
para28{"abacbabc", "abcd"},
ans28{-1},
},
question28{
{
para28{"abacbabc", ""},
ans28{0},
},

View File

@ -27,27 +27,27 @@ func Test_Problem29(t *testing.T) {
qs := []question29{
question29{
{
para29{10, 3},
ans29{3},
},
question29{
{
para29{7, -3},
ans29{-2},
},
question29{
{
para29{-1, 1},
ans29{-1},
},
question29{
{
para29{1, -1},
ans29{-1},
},
question29{
{
para29{2147483647, 3},
ans29{715827882},
},

View File

@ -27,57 +27,57 @@ func Test_Problem30(t *testing.T) {
qs := []question30{
question30{
{
para30{"aaaaaaaa", []string{"aa", "aa", "aa"}},
ans30{[]int{0, 1, 2}},
},
question30{
{
para30{"barfoothefoobarman", []string{"foo", "bar"}},
ans30{[]int{0, 9}},
},
question30{
{
para30{"wordgoodgoodgoodbestword", []string{"word", "good", "best", "word"}},
ans30{[]int{}},
},
question30{
{
para30{"goodgoodgoodgoodgood", []string{"good"}},
ans30{[]int{0, 4, 8, 12, 16}},
},
question30{
{
para30{"barofoothefoolbarman", []string{"foo", "bar"}},
ans30{[]int{}},
},
question30{
{
para30{"bbarffoothefoobarman", []string{"foo", "bar"}},
ans30{[]int{}},
},
question30{
{
para30{"ooroodoofoodtoo", []string{"foo", "doo", "roo", "tee", "oo"}},
ans30{[]int{}},
},
question30{
{
para30{"abc", []string{"a", "b", "c"}},
ans30{[]int{0}},
},
question30{
{
para30{"a", []string{"b"}},
ans30{[]int{}},
},
question30{
{
para30{"ab", []string{"ba"}},
ans30{[]int{}},
},
question30{
{
para30{"n", []string{}},
ans30{[]int{}},
},

View File

@ -0,0 +1,31 @@
package leetcode
func nextPermutation(nums []int) {
i, j := 0, 0
for i = len(nums) - 2; i >= 0; i-- {
if nums[i] < nums[i+1] {
break
}
}
if i >= 0 {
for j = len(nums) - 1; j > i; j-- {
if nums[j] > nums[i] {
break
}
}
swap(&nums, i, j)
}
reverse(&nums, i+1, len(nums)-1)
}
func reverse(nums *[]int, i, j int) {
for i < j {
swap(nums, i, j)
i++
j--
}
}
func swap(nums *[]int, i, j int) {
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
}

View File

@ -0,0 +1,58 @@
package leetcode
import (
"fmt"
"testing"
)
type question31 struct {
para31
ans31
}
// para 是参数
// one 代表第一个参数
type para31 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans31 struct {
one []int
}
func Test_Problem31(t *testing.T) {
qs := []question31{
{
para31{[]int{1, 2, 3}},
ans31{[]int{1, 3, 2}},
},
{
para31{[]int{3, 2, 1}},
ans31{[]int{1, 2, 3}},
},
{
para31{[]int{1, 1, 5}},
ans31{[]int{1, 5, 1}},
},
{
para31{[]int{1}},
ans31{[]int{1}},
},
}
fmt.Printf("------------------------Leetcode Problem 31------------------------\n")
for _, q := range qs {
_, p := q.ans31, q.para31
fmt.Printf("【input】:%v ", p)
nextPermutation(p.nums)
fmt.Printf("【output】:%v\n", p.nums)
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,89 @@
# [31. Next Permutation](https://leetcode.com/problems/next-permutation/)
## 题目
Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory.
**Example 1:**
```
Input: nums = [1,2,3]
Output: [1,3,2]
```
**Example 2:**
```
Input: nums = [3,2,1]
Output: [1,2,3]
```
**Example 3:**
```
Input: nums = [1,1,5]
Output: [1,5,1]
```
**Example 4:**
```
Input: nums = [1]
Output: [1]
```
**Constraints:**
- `1 <= nums.length <= 100`
- `0 <= nums[i] <= 100`
## 题目大意
实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。必须 原地 修改,只允许使用额外常数空间。
## 解题思路
- 题目有 3 个问题需要解决。如何找到下一个排列。不存在下一个排列的时候如何生成最小的排列。如何原地修改。先解决第一个问题,如何找到下一个排列。下一个排列是找到一个大于当前排序的字典序,且变大的幅度最小。那么只能将较小的数与较大数做一次原地交换。并且较小数的下标要尽量靠右,较大数也要尽可能小。原地交换以后,还需要将较大数右边的数按照升序重新排列。这样交换以后,才能生成下一个排列。以排列 [8,9,6,10,7,2] 为例:能找到的符合条件的一对「较小数」与「较大数」的组合为 6 与 7满足「较小数」尽量靠右而「较大数」尽可能小。当完成交换后排列变为 [8,9,7,10,6,2],此时我们可以重排「较小数」右边的序列,序列变为 [8,9,7,2,6,10]。
- 第一步:在 `nums[i]` 中找到 `i` 使得 `nums[i] < nums[i+1]`,此时较小数为 `nums[i]`,并且 `[i+1, n)` 一定为下降区间。第二步:如果找到了这样的 `i` ,则在下降区间 `[i+1, n)` 中从后往前找到第一个 `j` ,使得 `nums[i] < nums[j]` ,此时较大数为 `nums[j]`。第三步,交换 `nums[i]``nums[j]`,此时区间 `[i+1, n)` 一定为降序区间。最后原地交换 `[i+1, n)` 区间内的元素,使其变为升序,无需对该区间进行排序。
- 如果第一步找不到符合条件的下标 `i`,说明当前序列已经是一个最大的排列。那么应该直接执行第三步,生成最小的排列。
## 代码
```go
package leetcode
func nextPermutation(nums []int) {
i, j := 0, 0
for i = len(nums) - 2; i >= 0; i-- {
if nums[i] < nums[i+1] {
break
}
}
if i >= 0 {
for j = len(nums) - 1; j > i; j-- {
if nums[j] > nums[i] {
break
}
}
swap(&nums, i, j)
}
reverse(&nums, i+1, len(nums)-1)
}
func reverse(nums *[]int, i, j int) {
for i < j {
swap(nums, i, j)
i++
j--
}
}
func swap(nums *[]int, i, j int) {
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
}
```

View File

@ -27,17 +27,17 @@ func Test_Problem33(t *testing.T) {
qs := []question33{
question33{
{
para33{[]int{3, 1}, 1},
ans33{1},
},
question33{
{
para33{[]int{4, 5, 6, 7, 0, 1, 2}, 0},
ans33{4},
},
question33{
{
para33{[]int{4, 5, 6, 7, 0, 1, 2}, 3},
ans33{-1},
},

Some files were not shown because too many files have changed in this diff Show More