100 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
595d4cd678 Update README.md
修正区间范围
2020-11-13 23:02:29 +08:00
1676 changed files with 93123 additions and 15038 deletions

1
.gitignore vendored Normal file
View File

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

3324
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

@ -4,7 +4,41 @@ import (
"sort" "sort"
) )
// 解法一 最优解,双指针 + 排序
func threeSum(nums []int) [][]int { 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{} res := [][]int{}
counter := map[int]int{} counter := map[int]int{}
for _, value := range nums { for _, value := range nums {

View File

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

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

@ -10,9 +10,9 @@ Given n non-negative integers representing an elevation map where the width of e
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example: **Example**:
```c ```go
Input: [0,1,0,2,1,0,1,3,2,1,2,1] Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6 Output: 6
``` ```
@ -23,7 +23,9 @@ Output: 6
## 解题思路 ## 解题思路
- 每个数组里面的元素值可以想象成一个左右都有壁的圆柱筒。例如下图中左边的第二个元素 1当前左边最大的元素是 2 ,所以 2 高度的水会装到 1 的上面(因为想象成了左右都有筒壁)。这道题的思路就是左指针从 0 开始往右扫,右指针从最右边开始往左扫。额外还需要 2 个变量分别记住左边最大的高度和右边最大高度。遍历扫数组元素的过程中,如果左指针的高度比右指针的高度小,就不断的移动左指针,否则移动右指针。循环的终止条件就是左右指针碰上以后就结束。只要数组中元素的高度比保存的局部最大高度小,就累加 res 的值,否则更新局部最大高度。最终解就是 res 的值。
![](https://image.ibb.co/d6A2ZU/IMG-0139.jpg) ![](https://image.ibb.co/d6A2ZU/IMG-0139.jpg)
- 抽象一下,本题是想求针对每个 i找到它左边最大值 leftMax右边的最大值 rightMax然后 min(leftMaxrightMax) 为能够接到水的高度。left 和 right 指针是两边往中间移动的游标指针。最傻的解题思路是针对每个下标 i往左循环找到第一个最大值往右循环找到第一个最大值然后把这两个最大值取出最小者即为当前雨水的高度。这样做时间复杂度高浪费了很多循环。i 在从左往右的过程中,是可以动态维护最大值的。右边的最大值用右边的游标指针来维护。从左往右扫一遍下标,和,从两边往中间遍历一遍下标,是相同的结果,每个下标都遍历了一次。
每个数组里面的元素值可以想象成一个左右都有壁的圆柱筒。例如上图中左边的第二个元素 1当前左边最大的元素是 2 ,所以 2 高度的水会装到 1 的上面(因为想象成了左右都有筒壁)。这道题的思路就是左指针从 0 开始往右扫,右指针从最右边开始往左扫。额外还需要 2 个变量分别记住左边最大的高度和右边最大高度。遍历扫数组元素的过程中,如果左指针的高度比右指针的高度小,就不断的移动左指针,否则移动右指针。循环的终止条件就是左右指针碰上以后就结束。只要数组中元素的高度比保存的局部最大高度小,就累加 res 的值,否则更新局部最大高度。最终解就是 res 的值。 ![](https://img.halfrost.com/Leetcode/leetcode_42_1.png)
- 每个 i 的宽度固定为 1所以每个“坑”只需要求出高度即当前这个“坑”能积攒的雨水。最后依次将每个“坑”中的雨水相加即是能接到的雨水数。
![](https://img.halfrost.com/Leetcode/leetcode_42_0.png)

View File

@ -0,0 +1,10 @@
package leetcode
func getRow(rowIndex int) []int {
row := make([]int, rowIndex+1)
row[0] = 1
for i := 1; i <= rowIndex; i++ {
row[i] = row[i-1] * (rowIndex - i + 1) / i
}
return row
}

View File

@ -0,0 +1,47 @@
package leetcode
import (
"fmt"
"testing"
)
type question119 struct {
para119
ans119
}
// para 是参数
// one 代表第一个参数
type para119 struct {
rowIndex int
}
// ans 是答案
// one 代表第一个答案
type ans119 struct {
one []int
}
func Test_Problem119(t *testing.T) {
qs := []question119{
{
para119{3},
ans119{[]int{1, 3, 3, 1}},
},
{
para119{0},
ans119{[]int{1}},
},
}
fmt.Printf("------------------------Leetcode Problem 119------------------------\n")
for _, q := range qs {
_, p := q.ans119, q.para119
fmt.Printf("【input】:%v 【output】:%v\n", p, getRow(p.rowIndex))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,72 @@
# [119. Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)
## 题目
Given an integer `rowIndex`, return the `rowIndexth` row of the Pascal's triangle.
Notice that the row index starts from **0**.
![https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif)
In Pascal's triangle, each number is the sum of the two numbers directly above it.
**Follow up:**
Could you optimize your algorithm to use only *O*(*k*) extra space?
**Example 1:**
```
Input: rowIndex = 3
Output: [1,3,3,1]
```
**Example 2:**
```
Input: rowIndex = 0
Output: [1]
```
**Example 3:**
```
Input: rowIndex = 1
Output: [1,1]
```
**Constraints:**
- `0 <= rowIndex <= 33`
## 题目大意
给定一个非负索引 k其中 k ≤ 33返回杨辉三角的第 k 行。
## 解题思路
- 题目中的三角是杨辉三角,每个数字是 `(a+b)^n` 二项式展开的系数。题目要求我们只能使用 O(k) 的空间。那么需要找到两两项直接的递推关系。由组合知识得知:
$$\begin{aligned}C_{n}^{m} &= \frac{n!}{m!(n-m)!} \\C_{n}^{m-1} &= \frac{n!}{(m-1)!(n-m+1)!}\end{aligned}$$
于是得到递推公式:
$$C_{n}^{m} = C_{n}^{m-1} \times \frac{n-m+1}{m}$$
利用这个递推公式即可以把空间复杂度优化到 O(k)
## 代码
```go
package leetcode
func getRow(rowIndex int) []int {
row := make([]int, rowIndex+1)
row[0] = 1
for i := 1; i <= rowIndex; i++ {
row[i] = row[i-1] * (rowIndex - i + 1) / i
}
return row
}
```

View File

@ -5,9 +5,7 @@ import (
) )
func isPalindrome(s string) bool { func isPalindrome(s string) bool {
s = strings.ToLower(s) s = strings.ToLower(s)
i, j := 0, len(s)-1 i, j := 0, len(s)-1
for i < j { for i < j {
for i < j && !isChar(s[i]) { for i < j && !isChar(s[i]) {
@ -22,7 +20,6 @@ func isPalindrome(s string) bool {
i++ i++
j-- j--
} }
return true return true
} }

View File

@ -0,0 +1,44 @@
package leetcode
// Node define
type Node struct {
Val int
Next *Node
Random *Node
}
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
tempHead := copyNodeToLinkedList(head)
return splitLinkedList(tempHead)
}
func splitLinkedList(head *Node) *Node {
cur := head
head = head.Next
for cur != nil && cur.Next != nil {
cur.Next, cur = cur.Next.Next, cur.Next
}
return head
}
func copyNodeToLinkedList(head *Node) *Node {
cur := head
for cur != nil {
node := &Node{
Val: cur.Val,
Next: cur.Next,
}
cur.Next, cur = node, cur.Next
}
cur = head
for cur != nil {
if cur.Random != nil {
cur.Next.Random = cur.Random.Next
}
cur = cur.Next.Next
}
return head
}

View File

@ -0,0 +1,115 @@
package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question138 struct {
para138
ans138
}
// para 是参数
// one 代表第一个参数
type para138 struct {
head [][]int
}
// ans 是答案
// one 代表第一个答案
type ans138 struct {
one [][]int
}
func Test_Problem138(t *testing.T) {
qs := []question138{
{
para138{[][]int{{7, structures.NULL}, {13, 0}, {11, 4}, {10, 2}, {1, 0}}},
ans138{[][]int{{7, structures.NULL}, {13, 0}, {11, 4}, {10, 2}, {1, 0}}},
},
{
para138{[][]int{{1, 1}, {2, 1}}},
ans138{[][]int{{1, 1}, {2, 1}}},
},
{
para138{[][]int{{3, structures.NULL}, {3, 0}, {3, structures.NULL}}},
ans138{[][]int{{3, structures.NULL}, {3, 0}, {3, structures.NULL}}},
},
{
para138{[][]int{}},
ans138{[][]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 138------------------------\n")
for _, q := range qs {
_, p := q.ans138, q.para138
fmt.Printf("【input】:%v 【output】:%v\n", p, node2Ints(copyRandomList(ints2Node(p.head))))
}
fmt.Printf("\n\n\n")
}
func ints2Node(one [][]int) *Node {
nodesMap := map[int]*Node{}
for index, nodes := range one {
tmp := &Node{Val: nodes[0]}
nodesMap[index] = tmp
}
for index, node := range nodesMap {
if index != len(one)-1 {
node.Next = nodesMap[index+1]
} else {
node.Next = nil
}
}
for index, nodes := range one {
if nodes[1] == structures.NULL {
nodesMap[index].Random = nil
} else {
nodesMap[index].Random = nodesMap[nodes[1]]
}
}
return nodesMap[0]
}
func node2Ints(head *Node) (res [][]int) {
nodesMap, count, cur := map[*Node]int{}, 0, head
if head == nil {
return [][]int{}
}
for cur.Next != nil {
nodesMap[cur] = count
count++
cur = cur.Next
}
nodesMap[cur] = count
tmp := []int{}
cur = head
for cur.Next != nil {
tmp := append(tmp, cur.Val)
if cur.Random == nil {
tmp = append(tmp, structures.NULL)
} else {
tmp = append(tmp, nodesMap[cur.Random])
}
res = append(res, tmp)
cur = cur.Next
}
tmp = append(tmp, cur.Val)
if cur.Random == nil {
tmp = append(tmp, structures.NULL)
} else {
tmp = append(tmp, nodesMap[cur.Random])
}
res = append(res, tmp)
return res
}

View File

@ -0,0 +1,130 @@
# [138. Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/)
## 题目
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a **[deep copy](https://en.wikipedia.org/wiki/Object_copying#Deep_copy)** of the list.
The Linked List is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
- `val`: an integer representing `Node.val`
- `random_index`: the index of the node (range from `0` to `n-1`) where random pointer points to, or `null` if it does not point to any node.
**Example 1:**
![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)
```
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
```
**Example 2:**
![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)
```
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
```
**Example 3:**
![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)
```
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
```
**Example 4:**
```
Input: head = []
Output: []
Explanation: Given linked list is empty (null pointer), so return null.
```
**Constraints:**
- `10000 <= Node.val <= 10000`
- `Node.random` is null or pointing to a node in the linked list.
- The number of nodes will not exceed 1000.
## 题目大意
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
- val一个表示 Node.val 的整数。
- random_index随机指针指向的节点索引范围从 0  n-1如果不指向任何节点则为  null 
## 解题思路
- 这道题严格意义上是数据结构题,根据给定的数据结构,对它进行深拷贝。
- 先将每个节点都复制一份,放在它的 next 节点中。如此穿插的复制一份链表。
![https://img.halfrost.com/Leetcode/leetcode_138_1_0.png](https://img.halfrost.com/Leetcode/leetcode_138_1_0.png)
再将穿插版的链表的 random 指针指向正确的位置。
![https://img.halfrost.com/Leetcode/leetcode_138_2.png](https://img.halfrost.com/Leetcode/leetcode_138_2.png)
再将穿插版的链表的 next 指针指向正确的位置。最后分开这交织在一起的两个链表的头节点,即可分开 2 个链表。
![https://img.halfrost.com/Leetcode/leetcode_138_3.png](https://img.halfrost.com/Leetcode/leetcode_138_3.png)
## 代码
```go
package leetcode
// Node define
type Node struct {
Val int
Next *Node
Random *Node
}
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
tempHead := copyNodeToLinkedList(head)
return splitLinkedList(tempHead)
}
func splitLinkedList(head *Node) *Node {
cur := head
head = head.Next
for cur != nil && cur.Next != nil {
cur.Next, cur = cur.Next.Next, cur.Next
}
return head
}
func copyNodeToLinkedList(head *Node) *Node {
cur := head
for cur != nil {
node := &Node{
Val: cur.Val,
Next: cur.Next,
}
cur.Next, cur = node, cur.Next
}
cur = head
for cur != nil {
if cur.Random != nil {
cur.Next.Random = cur.Random.Next
}
cur = cur.Next.Next
}
return head
}
```

View File

@ -0,0 +1,71 @@
package leetcode
type LRUCache struct {
head, tail *Node
Keys map[int]*Node
Cap int
}
type Node struct {
Key, Val int
Prev, Next *Node
}
func Constructor(capacity int) LRUCache {
return LRUCache{Keys: make(map[int]*Node), Cap: capacity}
}
func (this *LRUCache) Get(key int) int {
if node, ok := this.Keys[key]; ok {
this.Remove(node)
this.Add(node)
return node.Val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if node, ok := this.Keys[key]; ok {
node.Val = value
this.Remove(node)
this.Add(node)
return
} else {
node = &Node{Key: key, Val: value}
this.Keys[key] = node
this.Add(node)
}
if len(this.Keys) > this.Cap {
delete(this.Keys, this.tail.Key)
this.Remove(this.tail)
}
}
func (this *LRUCache) Add(node *Node) {
node.Prev = nil
node.Next = this.head
if this.head != nil {
this.head.Prev = node
}
this.head = node
if this.tail == nil {
this.tail = node
this.tail.Next = nil
}
}
func (this *LRUCache) Remove(node *Node) {
if node == this.head {
this.head = node.Next
node.Next = nil
return
}
if node == this.tail {
this.tail = node.Prev
node.Prev.Next = nil
node.Prev = nil
return
}
node.Prev.Next = node.Next
node.Next.Prev = node.Prev
}

View File

@ -0,0 +1,40 @@
package leetcode
import (
"fmt"
"testing"
)
func Test_Problem146(t *testing.T) {
obj := Constructor(2)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.Put(1, 1)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.Put(2, 2)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 := obj.Get(1)
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
obj.Put(3, 3)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 = obj.Get(2)
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
obj.Put(4, 4)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 = obj.Get(1)
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.Get(3)
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.Get(4)
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
}
func MList2Ints(lru *LRUCache) [][]int {
res := [][]int{}
head := lru.head
for head != nil {
tmp := []int{head.Key, head.Val}
res = append(res, tmp)
head = head.Next
}
return res
}

View File

@ -0,0 +1,134 @@
# [146. LRU Cache](https://leetcode.com/problems/lru-cache/)
## 题目
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
- `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
- `int get(int key)` Return the value of the `key` if the key exists, otherwise return `1`.
- `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
**Follow up:**Could you do `get` and `put` in `O(1)` time complexity?
**Example 1:**
```
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
```
**Constraints:**
- `1 <= capacity <= 3000`
- `0 <= key <= 3000`
- `0 <= value <= 104`
- At most `3 * 104` calls will be made to `get` and `put`.
## 题目大意
运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
- LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
- int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
- void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶你是否可以在 O(1) 时间复杂度内完成这两种操作?
## 解题思路
- 这一题是 LRU 经典面试题,详细解释见[第三章 LRUCache 模板](https://books.halfrost.com/leetcode/ChapterThree/LRUCache/)。
## 代码
```go
package leetcode
type LRUCache struct {
head, tail *Node
Keys map[int]*Node
Cap int
}
type Node struct {
Key, Val int
Prev, Next *Node
}
func Constructor(capacity int) LRUCache {
return LRUCache{Keys: make(map[int]*Node), Cap: capacity}
}
func (this *LRUCache) Get(key int) int {
if node, ok := this.Keys[key]; ok {
this.Remove(node)
this.Add(node)
return node.Val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if node, ok := this.Keys[key]; ok {
node.Val = value
this.Remove(node)
this.Add(node)
return
} else {
node = &Node{Key: key, Val: value}
this.Keys[key] = node
this.Add(node)
}
if len(this.Keys) > this.Cap {
delete(this.Keys, this.tail.Key)
this.Remove(this.tail)
}
}
func (this *LRUCache) Add(node *Node) {
node.Prev = nil
node.Next = this.head
if this.head != nil {
this.head.Prev = node
}
this.head = node
if this.tail == nil {
this.tail = node
this.tail.Next = nil
}
}
func (this *LRUCache) Remove(node *Node) {
if node == this.head {
this.head = node.Next
node.Next = nil
return
}
if node == this.tail {
this.tail = node.Prev
node.Prev.Next = nil
node.Prev = nil
return
}
node.Prev.Next = node.Next
node.Next.Prev = node.Prev
}
```

View File

@ -25,17 +25,17 @@ func sortList(head *ListNode) *ListNode {
return head return head
} }
middleNode := middleNode1(head) middleNode := middleNode(head)
cur = middleNode.Next cur = middleNode.Next
middleNode.Next = nil middleNode.Next = nil
middleNode = cur middleNode = cur
left := sortList(head) left := sortList(head)
right := sortList(middleNode) right := sortList(middleNode)
return mergeTwoLists148(left, right) return mergeTwoLists(left, right)
} }
func middleNode1(head *ListNode) *ListNode { func middleNode(head *ListNode) *ListNode {
if head == nil || head.Next == nil { if head == nil || head.Next == nil {
return head return head
} }
@ -48,21 +48,6 @@ func middleNode1(head *ListNode) *ListNode {
return p1 return p1
} }
func mergeTwoLists148(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
}
l2.Next = mergeTwoLists(l1, l2.Next)
return l2
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil { if l1 == nil {
return l2 return l2

View File

@ -1,12 +1,11 @@
package leetcode package leetcode
// 解法一 // 解法一 快排
func maximumGap(nums []int) int { func maximumGap(nums []int) int {
if len(nums) < 2 { if len(nums) < 2 {
return 0 return 0
} }
quickSort164(nums, 0, len(nums)-1) quickSort164(nums, 0, len(nums)-1)
res := 0 res := 0
for i := 0; i < len(nums)-1; i++ { for i := 0; i < len(nums)-1; i++ {
if (nums[i+1] - nums[i]) > res { if (nums[i+1] - nums[i]) > res {
@ -37,52 +36,42 @@ func quickSort164(a []int, lo, hi int) {
quickSort164(a, p+1, hi) quickSort164(a, p+1, hi)
} }
// 解法二 // 解法二 基数排序
func maximumGap1(nums []int) int { func maximumGap1(nums []int) int {
if nums == nil || len(nums) < 2 { if nums == nil || len(nums) < 2 {
return 0 return 0
} }
// m is the maximal number in nums // m is the maximal number in nums
m := nums[0] m := nums[0]
for i := 1; i < len(nums); i++ { for i := 1; i < len(nums); i++ {
m = max(m, nums[i]) m = max(m, nums[i])
} }
exp := 1 // 1, 10, 100, 1000 ... exp := 1 // 1, 10, 100, 1000 ...
R := 10 // 10 digits R := 10 // 10 digits
aux := make([]int, len(nums)) aux := make([]int, len(nums))
for (m / exp) > 0 { // Go through all digits from LSB to MSB for (m / exp) > 0 { // Go through all digits from LSB to MSB
count := make([]int, R) count := make([]int, R)
for i := 0; i < len(nums); i++ { for i := 0; i < len(nums); i++ {
count[(nums[i]/exp)%10]++ count[(nums[i]/exp)%10]++
} }
for i := 1; i < len(count); i++ { for i := 1; i < len(count); i++ {
count[i] += count[i-1] count[i] += count[i-1]
} }
for i := len(nums) - 1; i >= 0; i-- { for i := len(nums) - 1; i >= 0; i-- {
tmp := count[(nums[i]/exp)%10] tmp := count[(nums[i]/exp)%10]
tmp-- tmp--
aux[tmp] = nums[i] aux[tmp] = nums[i]
count[(nums[i]/exp)%10] = tmp
} }
for i := 0; i < len(nums); i++ { for i := 0; i < len(nums); i++ {
nums[i] = aux[i] nums[i] = aux[i]
} }
exp *= 10 exp *= 10
} }
maxValue := 0 maxValue := 0
for i := 1; i < len(aux); i++ { for i := 1; i < len(aux); i++ {
maxValue = max(maxValue, aux[i]-aux[i-1]) maxValue = max(maxValue, aux[i]-aux[i-1])
} }
return maxValue return maxValue
} }

View File

@ -49,6 +49,11 @@ func Test_Problem164(t *testing.T) {
para164{[]int{2, 435, 214, 64321, 643, 7234, 7, 436523, 7856, 8}}, para164{[]int{2, 435, 214, 64321, 643, 7234, 7, 436523, 7856, 8}},
ans164{372202}, ans164{372202},
}, },
{
para164{[]int{1, 10000000}},
ans164{9999999},
},
} }
fmt.Printf("------------------------Leetcode Problem 164------------------------\n") fmt.Printf("------------------------Leetcode Problem 164------------------------\n")

View File

@ -1,8 +1,8 @@
package leetcode package leetcode
import "container/heap"
import ( import (
"container/heap"
"github.com/halfrost/LeetCode-Go/structures" "github.com/halfrost/LeetCode-Go/structures"
) )

View File

@ -0,0 +1,24 @@
package leetcode
// 解法一 时间复杂度 O(n),空间复杂度 O(1)
func rotate(nums []int, k int) {
k %= len(nums)
reverse(nums)
reverse(nums[:k])
reverse(nums[k:])
}
func reverse(a []int) {
for i, n := 0, len(a); i < n/2; i++ {
a[i], a[n-1-i] = a[n-1-i], a[i]
}
}
// 解法二 时间复杂度 O(n),空间复杂度 O(n)
func rotate1(nums []int, k int) {
newNums := make([]int, len(nums))
for i, v := range nums {
newNums[(i+k)%len(nums)] = v
}
copy(nums, newNums)
}

View File

@ -0,0 +1,50 @@
package leetcode
import (
"fmt"
"testing"
)
type question189 struct {
para189
ans189
}
// para 是参数
// one 代表第一个参数
type para189 struct {
nums []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans189 struct {
one []int
}
func Test_Problem189(t *testing.T) {
qs := []question189{
{
para189{[]int{1, 2, 3, 4, 5, 6, 7}, 3},
ans189{[]int{5, 6, 7, 1, 2, 3, 4}},
},
{
para189{[]int{-1, -100, 3, 99}, 2},
ans189{[]int{3, 99, -1, -100}},
},
}
fmt.Printf("------------------------Leetcode Problem 189------------------------\n")
for _, q := range qs {
_, p := q.ans189, q.para189
fmt.Printf("【input】:%v ", p)
rotate(p.nums, p.k)
fmt.Printf("【output】:%v\n", p.nums)
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,75 @@
# [189. Rotate Array](https://leetcode.com/problems/rotate-array/)
## 题目
Given an array, rotate the array to the right by *k* steps, where *k* is non-negative.
**Follow up:**
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
**Example 1:**
```
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
```
**Example 2:**
```
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
```
**Constraints:**
- `1 <= nums.length <= 2 * 10^4`
- `-2^31 <= nums[i] <= 2^31 - 1`
- `0 <= k <= 10^5`
## 题目大意
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
## 解题思路
- 解法二,使用一个额外的数组,先将原数组下标为 i 的元素移动到 `(i+k) mod n` 的位置,再将剩下的元素拷贝回来即可。
- 解法一,由于题目要求不能使用额外的空间,所以本题最佳解法不是解法二。翻转最终态是,末尾 `k mod n` 个元素移动至了数组头部,剩下的元素右移 `k mod n` 个位置至最尾部。确定了最终态以后再变换就很容易。先将数组中所有元素从头到尾翻转一次,尾部的所有元素都到了头部,然后再将 `[0,(k mod n) 1]` 区间内的元素翻转一次,最后再将 `[k mod n, n 1]` 区间内的元素翻转一次,即可满足题目要求。
## 代码
```go
package leetcode
// 解法一 时间复杂度 O(n),空间复杂度 O(1)
func rotate(nums []int, k int) {
k %= len(nums)
reverse(nums)
reverse(nums[:k])
reverse(nums[k:])
}
func reverse(a []int) {
for i, n := 0, len(a); i < n/2; i++ {
a[i], a[n-1-i] = a[n-1-i], a[i]
}
}
// 解法二 时间复杂度 O(n),空间复杂度 O(n)
func rotate1(nums []int, k int) {
newNums := make([]int, len(nums))
for i, v := range nums {
newNums[(i+k)%len(nums)] = v
}
copy(nums, newNums)
}
```

View File

@ -1,4 +1,4 @@
# [211. Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) # [211. Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/)
## 题目 ## 题目

View File

@ -1,51 +1,38 @@
package leetcode package leetcode
import "sort" // 解法一 桶排序
// 解法一 排序 + 滑动窗口
func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool {
if len(nums) < 2 { if k <= 0 || t < 0 || len(nums) < 2 {
return false return false
} }
elemList := make([]*elem, len(nums)) buckets := map[int]int{}
for i, num := range nums { for i := 0; i < len(nums); i++ {
elemList[i] = &elem{num, i} // Get the ID of the bucket from element value nums[i] and bucket width t + 1
} key := nums[i] / (t + 1)
sort.SliceStable(elemList, func(i, j int) bool { // -7/9 = 0, but need -7/9 = -1
if elemList[i].val != elemList[j].val { if nums[i] < 0 {
return elemList[i].val < elemList[j].val key--
} }
return elemList[i].idx < elemList[j].idx if _, ok := buckets[key]; ok {
}) return true
i, j := 0, 1
for j < len(elemList) {
if elemList[j].val-elemList[i].val <= t {
if abs(elemList[j].idx-elemList[i].idx) <= k {
return true
}
j++
} else {
i++
if j <= i {
j++
}
} }
// check the lower bucket, and have to check the value too
if v, ok := buckets[key-1]; ok && nums[i]-v <= t {
return true
}
// check the upper bucket, and have to check the value too
if v, ok := buckets[key+1]; ok && v-nums[i] <= t {
return true
}
// maintain k size of window
if len(buckets) >= k {
delete(buckets, nums[i-k]/(t+1))
}
buckets[key] = nums[i]
} }
return false return false
} }
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
type elem struct {
val int
idx int
}
// 解法二 滑动窗口 + 剪枝 // 解法二 滑动窗口 + 剪枝
func containsNearbyAlmostDuplicate1(nums []int, k int, t int) bool { func containsNearbyAlmostDuplicate1(nums []int, k int, t int) bool {
if len(nums) <= 1 { if len(nums) <= 1 {
@ -66,3 +53,10 @@ func containsNearbyAlmostDuplicate1(nums []int, k int, t int) bool {
} }
return false return false
} }
func abs(a int) int {
if a > 0 {
return a
}
return -a
}

View File

@ -52,6 +52,11 @@ func Test_Problem220(t *testing.T) {
para220{[]int{1, 5, 9, 1, 5, 9}, 2, 3}, para220{[]int{1, 5, 9, 1, 5, 9}, 2, 3},
ans220{false}, ans220{false},
}, },
{
para220{[]int{1, 2, 1, 1}, 1, 0},
ans220{true},
},
} }
fmt.Printf("------------------------Leetcode Problem 220------------------------\n") fmt.Printf("------------------------Leetcode Problem 220------------------------\n")

View File

@ -32,3 +32,4 @@ Given an array of integers, find out whether there are two distinct indices i 
- 给出一个数组,要求在数组里面找到 2 个索引,`i``j`,使得 `| nums[i] - nums[j] | ≤ t` ,并且 `| i - j | ≤ k` - 给出一个数组,要求在数组里面找到 2 个索引,`i``j`,使得 `| nums[i] - nums[j] | ≤ t` ,并且 `| i - j | ≤ k`
- 这是一道滑动窗口的题目。第一想法就是用 `i``j` 两个指针,针对每个 `i` ,都从 `i + 1` 往后扫完整个数组,判断每个 `i``j` ,判断是否满足题意。`j` 在循环的过程中注意判断剪枝条件 `| i - j | ≤ k`。这个做法的时间复杂度是 O(n^2)。这个做法慢的原因在于滑动窗口的左边界和右边界在滑动过程中不是联动滑动的。 - 这是一道滑动窗口的题目。第一想法就是用 `i``j` 两个指针,针对每个 `i` ,都从 `i + 1` 往后扫完整个数组,判断每个 `i``j` ,判断是否满足题意。`j` 在循环的过程中注意判断剪枝条件 `| i - j | ≤ k`。这个做法的时间复杂度是 O(n^2)。这个做法慢的原因在于滑动窗口的左边界和右边界在滑动过程中不是联动滑动的。
- 于是考虑,如果数组是有序的呢?把数组按照元素值从小到大进行排序,如果元素值相等,就按照 index 从小到大进行排序。在这样有序的数组中找满足题意的 `i``j`,滑动窗口左边界和右边界就是联动的了。窗口的右边界滑到与左边界元素值的差值 ≤ t 的地方,满足了这个条件再判断 `| i - j | ≤ k`,如果右边界与左边界元素值的差值 > t 了,说明该把左边界往右移动了(能这样移动的原因就是因为我们将数组元素大小排序了,右移是增大元素的方向)。移动左边界的时候需要注意左边界不能超过右边界。这样滑动窗口一次滑过整个排序后的数组,就可以判断是否存在满足题意的 `i``j` 。这个做法的时间主要花在排序上了,时间复杂度是 O(n log n)。 - 于是考虑,如果数组是有序的呢?把数组按照元素值从小到大进行排序,如果元素值相等,就按照 index 从小到大进行排序。在这样有序的数组中找满足题意的 `i``j`,滑动窗口左边界和右边界就是联动的了。窗口的右边界滑到与左边界元素值的差值 ≤ t 的地方,满足了这个条件再判断 `| i - j | ≤ k`,如果右边界与左边界元素值的差值 > t 了,说明该把左边界往右移动了(能这样移动的原因就是因为我们将数组元素大小排序了,右移是增大元素的方向)。移动左边界的时候需要注意左边界不能超过右边界。这样滑动窗口一次滑过整个排序后的数组,就可以判断是否存在满足题意的 `i``j` 。这个做法的时间主要花在排序上了,时间复杂度是 O(n log n)。
- 本题最优解是利用桶排序的思想。`| i - j | ≤ k` 这个条件利用一个窗口大小为 k 来维护。重点在 `| nums[i] - nums[j] | ≤ t` 这个条件如何满足。利用桶排序的思想,将 `nums[i]` 所有元素分为 ...,`[0,t]`,`[t+1,2t+1]`,...。每个区间的大小为 `t + 1`。每个元素现在都对应一个桶编号。进行 3 次查找即可确定能否找到满足这个 `| nums[i] - nums[j] | ≤ t` 条件的数对。如果在相同的桶中找到了元素,那么说明能找到这样的 i 和 j。还有 2 种可能对应桶边界的情况。如果存在前一个桶中的元素能使得相差的值也 `≤ t`,这样的数对同样满足题意。最后一种情况是,如果存在后一个桶中的元素能使得相差的值也 `≤ t`,这样的数对同样满足题意。查询 3 次,如果都不存在,说明当前的 i 找不到满足题意的 j。继续循环寻找。循环一遍都找不到满足题意的数对输出 false。

View File

@ -0,0 +1,19 @@
package leetcode
import (
"strconv"
)
func summaryRanges(nums []int) (ans []string) {
for i, n := 0, len(nums); i < n; {
left := i
for i++; i < n && nums[i-1]+1 == nums[i]; i++ {
}
s := strconv.Itoa(nums[left])
if left != i-1 {
s += "->" + strconv.Itoa(nums[i-1])
}
ans = append(ans, s)
}
return
}

View File

@ -0,0 +1,62 @@
package leetcode
import (
"fmt"
"testing"
)
type question228 struct {
para228
ans228
}
// para 是参数
// one 代表第一个参数
type para228 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans228 struct {
ans []string
}
func Test_Problem228(t *testing.T) {
qs := []question228{
{
para228{[]int{0, 1, 2, 4, 5, 7}},
ans228{[]string{"0->2", "4->5", "7"}},
},
{
para228{[]int{0, 2, 3, 4, 6, 8, 9}},
ans228{[]string{"0", "2->4", "6", "8->9"}},
},
{
para228{[]int{}},
ans228{[]string{}},
},
{
para228{[]int{-1}},
ans228{[]string{"-1"}},
},
{
para228{[]int{0}},
ans228{[]string{"0"}},
},
}
fmt.Printf("------------------------Leetcode Problem 228------------------------\n")
for _, q := range qs {
_, p := q.ans228, q.para228
fmt.Printf("【input】:%v 【output】:%v\n", p, summaryRanges(p.nums))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,107 @@
# [228. Summary Ranges](https://leetcode.com/problems/summary-ranges/)
## 题目
You are given a **sorted unique** integer array `nums`.
Return *the **smallest sorted** list of ranges that **cover all the numbers in the array exactly***. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
- `"a->b"` if `a != b`
- `"a"` if `a == b`
**Example 1:**
```
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
```
**Example 2:**
```
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
```
**Example 3:**
```
Input: nums = []
Output: []
```
**Example 4:**
```
Input: nums = [-1]
Output: ["-1"]
```
**Example 5:**
```
Input: nums = [0]
Output: ["0"]
```
**Constraints:**
- `0 <= nums.length <= 20`
- `231 <= nums[i] <= 231 - 1`
- All the values of `nums` are **unique**.
- `nums` is sorted in ascending order.
## 题目大意
给定一个无重复元素的有序整数数组 nums 。
返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表。也就是说nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。
列表中的每个区间范围 [a,b] 应该按如下格式输出:
- "a->b" ,如果 a != b
- "a" ,如果 a == b
## 解题思路
- 简单题。按照题意,用一个游标变量累加寻找连续的区间。一旦出现了中断,就按照题意格式输出。输出的规则有多种,带箭头的区间,单个元素区间,空区间。
## 代码
```go
package leetcode
import (
"strconv"
)
func summaryRanges(nums []int) (ans []string) {
for i, n := 0, len(nums); i < n; {
left := i
for i++; i < n && nums[i-1]+1 == nums[i]; i++ {
}
s := strconv.Itoa(nums[left])
if left != i-1 {
s += "->" + strconv.Itoa(nums[i-1])
}
ans = append(ans, s)
}
return
}
```

View File

@ -0,0 +1,53 @@
package leetcode
//Below is the interface for Iterator, which is already defined for you.
type Iterator struct {
}
func (this *Iterator) hasNext() bool {
// Returns true if the iteration has more elements.
return true
}
func (this *Iterator) next() int {
// Returns the next element in the iteration.
return 0
}
type PeekingIterator struct {
nextEl int
hasEl bool
iter *Iterator
}
func Constructor(iter *Iterator) *PeekingIterator {
return &PeekingIterator{
iter: iter,
}
}
func (this *PeekingIterator) hasNext() bool {
if this.hasEl {
return true
}
return this.iter.hasNext()
}
func (this *PeekingIterator) next() int {
if this.hasEl {
this.hasEl = false
return this.nextEl
} else {
return this.iter.next()
}
}
func (this *PeekingIterator) peek() int {
if this.hasEl {
return this.nextEl
}
this.hasEl = true
this.nextEl = this.iter.next()
return this.nextEl
}

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