mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-07 18:10:29 +08:00
Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
b012a1f9d5 |
13
.github/FUNDING.yml
vendored
13
.github/FUNDING.yml
vendored
@ -1,13 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [halfrost]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
23
ctl/label.go
23
ctl/label.go
@ -10,6 +10,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/halfrost/LeetCode-Go/ctl/util"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@ -17,7 +18,7 @@ var (
|
||||
chapterOneFileOrder = []string{"_index", "Data_Structure", "Algorithm", "Time_Complexity"}
|
||||
chapterOneMenuOrder = []string{"_index", "#关于作者", "Data_Structure", "Algorithm", "Time_Complexity"}
|
||||
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", "Sorting", "Bit_Manipulation", "Union_Find", "Sliding_Window", "Segment_Tree", "Binary_Indexed_Tree"}
|
||||
"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>"
|
||||
@ -54,7 +55,7 @@ var (
|
||||
"Binary_Search": "2.11 Binary Search",
|
||||
"Math": "2.12 Math",
|
||||
"Hash_Table": "2.13 Hash Table",
|
||||
"Sorting": "2.14 ✅ Sorting",
|
||||
"Sort": "2.14 ✅ Sort",
|
||||
"Bit_Manipulation": "2.15 ✅ Bit Manipulation",
|
||||
"Union_Find": "2.16 ✅ Union Find",
|
||||
"Sliding_Window": "2.17 ✅ Sliding Window",
|
||||
@ -75,7 +76,7 @@ var (
|
||||
)
|
||||
|
||||
func getChapterFourFileOrder() ([]string, []int) {
|
||||
solutions, solutionIds := LoadChapterFourDir()
|
||||
solutions, solutionIds := util.LoadChapterFourDir()
|
||||
chapterFourFileOrder := []string{"_index"}
|
||||
chapterFourFileOrder = append(chapterFourFileOrder, solutions...)
|
||||
fmt.Printf("ChapterFour 中包括 _index 有 %v 个文件, len(id) = %v\n", len(chapterFourFileOrder), len(solutionIds))
|
||||
@ -149,7 +150,7 @@ func addPreNextLabel(order, preOrder []string, chapterFourIds []int, preChapter,
|
||||
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, GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter
|
||||
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
|
||||
}
|
||||
@ -157,26 +158,26 @@ func addPreNextLabel(order, preOrder []string, chapterFourIds []int, preChapter,
|
||||
} 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, GetChpaterFourFileNum(chapterFourIds[(index-1)-1]), order[index-1])
|
||||
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, GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter
|
||||
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, 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, GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter
|
||||
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", GetChpaterFourFileNum(chapterFourIds[(index-1)]), path)
|
||||
path = fmt.Sprintf("%v/%v", util.GetChpaterFourFileNum(chapterFourIds[(index-1)]), path)
|
||||
}
|
||||
|
||||
exist, err = needAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path))
|
||||
@ -191,7 +192,7 @@ func addPreNextLabel(order, preOrder []string, chapterFourIds []int, preChapter,
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
WriteFile(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), res)
|
||||
util.WriteFile(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), res)
|
||||
count++
|
||||
}
|
||||
}
|
||||
@ -241,7 +242,7 @@ func delPreNextLabel(order []string, chapterFourIds []int, chapter string) {
|
||||
lineNum = 3
|
||||
}
|
||||
if chapter == "ChapterFour" && index > 0 {
|
||||
path = fmt.Sprintf("%v/%v", GetChpaterFourFileNum(chapterFourIds[(index-1)]), path)
|
||||
path = fmt.Sprintf("%v/%v", util.GetChpaterFourFileNum(chapterFourIds[(index-1)]), path)
|
||||
}
|
||||
|
||||
exist, err := needAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path))
|
||||
@ -262,7 +263,7 @@ func delPreNextLabel(order []string, chapterFourIds []int, chapter string) {
|
||||
// fmt.Println(err)
|
||||
// return
|
||||
// }
|
||||
// WriteFile(fmt.Sprintf("../website/content/ChapterOne/%v.md", v), res)
|
||||
// util.WriteFile(fmt.Sprintf("../website/content/ChapterOne/%v.md", v), res)
|
||||
}
|
||||
|
||||
func needAdd(filePath string) (bool, error) {
|
||||
|
@ -3,7 +3,7 @@
|
||||
|
||||
# 说明
|
||||
|
||||
此版本是 https://books.halfrost.com/leetcode 网页的离线版,由于网页版实时会更新,所以此 PDF 版难免会有一些排版或者错别字。如果读者遇到了,可以到网页版相应页面,点击页面 edit 按钮,提交 pr 进行更改。此 PDF 版本号是 V1.5.20。PDF 永久更新地址是 https://github.com/halfrost/leetcode-go/releases/,以版本号区分不同版本。笔者还是强烈推荐看在线版,有任何错误都会立即更新。如果觉得此书对刷题有一点点帮助,可以给此书点一个 star,鼓励一下笔者早点更新更多题解。
|
||||
此版本是 https://books.halfrost.com/leetcode 网页的离线版,由于网页版实时会更新,所以此 PDF 版难免会有一些排版或者错别字。如果读者遇到了,可以到网页版相应页面,点击页面 edit 按钮,提交 pr 进行更改。此 PDF 版本号是 V1.5.20。PDF 永久更新地址是 https://github.com/halfrost/LeetCode-Go/releases/,以版本号区分不同版本。笔者还是强烈推荐看在线版,有任何错误都会立即更新。如果觉得此书对刷题有一点点帮助,可以给此书点一个 star,鼓励一下笔者早点更新更多题解。
|
||||
|
||||
> 版本号说明,V1.5.20,1 是大版本号,5 代表当前题解中有几百题,目前是 520 题,所以第二个版本号是 5,20 代表当前题解中有几十题,目前是 520 题,所以第三个版本号是 20 。
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@ -14,8 +14,8 @@ type LeetCodeProblemAll struct {
|
||||
AcMedium int32 `json:"ac_medium"`
|
||||
AcHard int32 `json:"ac_hard"`
|
||||
StatStatusPairs []StatStatusPairs `json:"stat_status_pairs"`
|
||||
FrequencyHigh float64 `json:"frequency_high"`
|
||||
FrequencyMid float64 `json:"frequency_mid"`
|
||||
FrequencyHigh int32 `json:"frequency_high"`
|
||||
FrequencyMid int32 `json:"frequency_mid"`
|
||||
CategorySlug string `json:"category_slug"`
|
||||
AcEasyTotal int32
|
||||
AcMediumTotal int32
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@ -29,7 +29,7 @@ func GenerateMdRows(solutionIds []int, mdrows []Mdrow) {
|
||||
FrontendQuestionID: row.FrontendQuestionID,
|
||||
QuestionTitle: strings.TrimSpace(row.QuestionTitle),
|
||||
QuestionTitleSlug: row.QuestionTitleSlug,
|
||||
SolutionPath: fmt.Sprintf("[Go](https://github.com/halfrost/leetcode-go/tree/master/leetcode/%v)", fmt.Sprintf("%04d.%v", solutionIds[i], s7)),
|
||||
SolutionPath: fmt.Sprintf("[Go](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/%v)", fmt.Sprintf("%04d.%v", solutionIds[i], s7)),
|
||||
Acceptance: row.Acceptance,
|
||||
Difficulty: row.Difficulty,
|
||||
Frequency: row.Frequency,
|
||||
@ -52,7 +52,7 @@ func GenerateMdRows(solutionIds []int, mdrows []Mdrow) {
|
||||
// fmt.Printf("mdrows = %v\n\n", mdrows)
|
||||
}
|
||||
|
||||
// | 0001 | Two Sum | [Go](https://github.com/halfrost/leetcode-go/tree/master/leetcode/0001.Two-Sum)| 45.6% | Easy | |
|
||||
// | 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)
|
||||
}
|
@ -1,10 +1,12 @@
|
||||
package main
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/halfrost/LeetCode-Go/ctl/util"
|
||||
)
|
||||
|
||||
// Graphql define
|
||||
@ -30,7 +32,7 @@ type TopicTag struct {
|
||||
TranslatedName string `json:"translatedName"`
|
||||
Slug string `json:"slug"`
|
||||
Questions []Question `json:"questions"`
|
||||
Frequencies string `json:"frequencies"`
|
||||
Frequencies float64 `json:"frequencies"`
|
||||
Typename string `json:"__typename"`
|
||||
}
|
||||
|
||||
@ -152,15 +154,15 @@ func standardizedTitle(orig string, frontendQuestionID int32) string {
|
||||
func GenerateTagMdRows(solutionIds []int, metaMap map[int]TagList, mdrows []Mdrow, internal bool) []TagList {
|
||||
tl := []TagList{}
|
||||
for _, row := range mdrows {
|
||||
if BinarySearch(solutionIds, int(row.FrontendQuestionID)) != -1 {
|
||||
if util.BinarySearch(solutionIds, int(row.FrontendQuestionID)) != -1 {
|
||||
tmp := TagList{}
|
||||
tmp.FrontendQuestionID = row.FrontendQuestionID
|
||||
tmp.QuestionTitle = strings.TrimSpace(row.QuestionTitle)
|
||||
s7 := standardizedTitle(row.QuestionTitle, row.FrontendQuestionID)
|
||||
if internal {
|
||||
tmp.SolutionPath = fmt.Sprintf("[Go]({{< relref \"/ChapterFour/%v/%v.md\" >}})", GetChpaterFourFileNum(int(row.FrontendQuestionID)), fmt.Sprintf("%04d.%v", int(row.FrontendQuestionID), s7))
|
||||
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)", GetChpaterFourFileNum(int(row.FrontendQuestionID)), fmt.Sprintf("%04d.%v", int(row.FrontendQuestionID), s7))
|
||||
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
|
||||
@ -178,8 +180,8 @@ type TagLists struct {
|
||||
TagLists []TagList
|
||||
}
|
||||
|
||||
// | No. | Title | Solution | Difficulty | TimeComplexity | SpaceComplexity |Favorite| Acceptance |
|
||||
// |:--------:|:------- | :--------: | :----------: | :----: | :-----: | :-----: |:-----: |
|
||||
//| 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"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@ -18,8 +18,8 @@ type UserInfo struct {
|
||||
OptimizingEasy int32
|
||||
OptimizingMedium int32
|
||||
OptimizingHard int32
|
||||
FrequencyHigh float64 `json:"frequency_high"`
|
||||
FrequencyMid float64 `json:"frequency_mid"`
|
||||
FrequencyHigh int32 `json:"frequency_high"`
|
||||
FrequencyMid int32 `json:"frequency_mid"`
|
||||
CategorySlug string `json:"category_slug"`
|
||||
}
|
||||
|
20
ctl/pdf.go
20
ctl/pdf.go
@ -3,14 +3,14 @@ package main
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"github.com/halfrost/LeetCode-Go/ctl/util"
|
||||
"github.com/spf13/cobra"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -23,7 +23,7 @@ var (
|
||||
|
||||
# 说明
|
||||
|
||||
此版本是 https://books.halfrost.com/leetcode 网页的离线版,由于网页版实时会更新,所以此 PDF 版难免会有一些排版或者错别字。如果读者遇到了,可以到网页版相应页面,点击页面 edit 按钮,提交 pr 进行更改。此 PDF 版本号是 V%v.%v.%v。PDF 永久更新地址是 https://github.com/halfrost/leetcode-go/releases/,以版本号区分不同版本。笔者还是强烈推荐看在线版,有任何错误都会立即更新。如果觉得此书对刷题有一点点帮助,可以给此书点一个 star,鼓励一下笔者早点更新更多题解。
|
||||
此版本是 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 。
|
||||
|
||||
@ -60,7 +60,7 @@ func generatePDF() {
|
||||
// 先删除 pre-next
|
||||
delPreNext()
|
||||
|
||||
chapterFourFileOrder, _ := LoadChapterFourDir()
|
||||
chapterFourFileOrder, _ := util.LoadChapterFourDir()
|
||||
totalSolutions = len(chapterFourFileOrder)
|
||||
midVersion = totalSolutions / 100
|
||||
lastVersion = totalSolutions % 100
|
||||
@ -79,7 +79,7 @@ func generatePDF() {
|
||||
tmp, err = loadChapter(chapterThreeFileOrder, "./pdftemp", "ChapterThree")
|
||||
pdf = append(pdf, tmp...)
|
||||
// PDF 第四章
|
||||
tmp, err = LoadFile("./pdftemp/ChapterFour/_index.md")
|
||||
tmp, err = util.LoadFile("./pdftemp/ChapterFour/_index.md")
|
||||
pdf = append(pdf, tmp...)
|
||||
tmp, err = loadChapter(chapterFourFileOrder, "../website/content", "ChapterFour")
|
||||
pdf = append(pdf, tmp...)
|
||||
@ -87,10 +87,10 @@ func generatePDF() {
|
||||
fmt.Println(err)
|
||||
}
|
||||
// 生成 PDF
|
||||
WriteFile(fmt.Sprintf("../PDF v%v.%v.%v.md", majorVersion, midVersion, lastVersion), pdf)
|
||||
util.WriteFile(fmt.Sprintf("../PDF v%v.%v.%v.md", majorVersion, midVersion, lastVersion), pdf)
|
||||
// 还原现场
|
||||
addPreNext()
|
||||
DestoryDir("./pdftemp")
|
||||
util.DestoryDir("./pdftemp")
|
||||
}
|
||||
|
||||
func loadChapter(order []string, path, chapter string) ([]byte, error) {
|
||||
@ -109,10 +109,10 @@ func loadChapter(order []string, path, chapter string) ([]byte, error) {
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
tmp, err = LoadFile(fmt.Sprintf("%v/%v/%v/%v.md", path, chapter, GetChpaterFourFileNum(num), v))
|
||||
tmp, err = util.LoadFile(fmt.Sprintf("%v/%v/%v/%v.md", path, chapter, util.GetChpaterFourFileNum(num), v))
|
||||
}
|
||||
} else {
|
||||
tmp, err = LoadFile(fmt.Sprintf("%v/%v/%v.md", path, chapter, v))
|
||||
tmp, err = util.LoadFile(fmt.Sprintf("%v/%v/%v.md", path, chapter, v))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
@ -146,7 +146,7 @@ func prepare(path string) {
|
||||
}
|
||||
// 生成外部链接的 ChapterTwo
|
||||
buildChapterTwo(false)
|
||||
CopyFile("./pdftemp/ChapterTwo/_index.md", "../website/content/ChapterTwo/_index.md")
|
||||
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)
|
||||
|
@ -11,16 +11,18 @@ import (
|
||||
"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", "Sorting", "Bit Manipulation", "Union Find", "Sliding Window", "Segment Tree", "Binary Indexed Tree"}
|
||||
"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", "Sorting", "Bit_Manipulation", "Union_Find", "Sliding_Window", "Segment_Tree", "Binary_Indexed_Tree"}
|
||||
"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", "sorting", "bit-manipulation", "union-find", "sliding-window", "segment-tree", "binary-indexed-tree"}
|
||||
"binary-search", "math", "hash-table", "sort", "bit-manipulation", "union-find", "sliding-window", "segment-tree", "binary-indexed-tree"}
|
||||
)
|
||||
|
||||
func newBuildCommand() *cobra.Command {
|
||||
@ -78,13 +80,13 @@ func newBuildMenu() *cobra.Command {
|
||||
|
||||
func buildREADME() {
|
||||
var (
|
||||
problems []StatStatusPairs
|
||||
lpa LeetCodeProblemAll
|
||||
info UserInfo
|
||||
problems []m.StatStatusPairs
|
||||
lpa m.LeetCodeProblemAll
|
||||
info m.UserInfo
|
||||
)
|
||||
// 请求所有题目信息
|
||||
body := getProblemAllList()
|
||||
problemsMap, optimizingIds := map[int]StatStatusPairs{}, []int{}
|
||||
problemsMap, optimizingIds := map[int]m.StatStatusPairs{}, []int{}
|
||||
err := json.Unmarshal(body, &lpa)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
@ -94,30 +96,30 @@ func buildREADME() {
|
||||
|
||||
// 拼凑 README 需要渲染的数据
|
||||
problems = lpa.StatStatusPairs
|
||||
info = ConvertUserInfoModel(lpa)
|
||||
info = m.ConvertUserInfoModel(lpa)
|
||||
for _, v := range problems {
|
||||
problemsMap[int(v.Stat.FrontendQuestionID)] = v
|
||||
}
|
||||
mdrows := ConvertMdModelFromSsp(problems)
|
||||
sort.Sort(SortByQuestionID(mdrows))
|
||||
solutionIds, _, try := LoadSolutionsDir()
|
||||
GenerateMdRows(solutionIds, mdrows)
|
||||
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 := ConvertMdModelFromIds(problemsMap, optimizingIds)
|
||||
sort.Sort(SortByQuestionID(omdrows))
|
||||
omdrows := m.ConvertMdModelFromIds(problemsMap, optimizingIds)
|
||||
sort.Sort(m.SortByQuestionID(omdrows))
|
||||
|
||||
// 按照模板渲染 README
|
||||
res, err := renderReadme("./template/template.markdown", len(solutionIds), try, Mdrows{Mdrows: mdrows}, Mdrows{Mdrows: omdrows}, info)
|
||||
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
|
||||
}
|
||||
WriteFile("../README.md", res)
|
||||
util.WriteFile("../README.md", res)
|
||||
fmt.Println("write file successful")
|
||||
//makeReadmeFile(mds)
|
||||
}
|
||||
|
||||
func renderReadme(filePath string, total, try int, mdrows, omdrows Mdrows, user UserInfo) ([]byte, error) {
|
||||
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
|
||||
@ -161,12 +163,11 @@ func renderReadme(filePath string, total, try int, mdrows, omdrows Mdrows, user
|
||||
}
|
||||
|
||||
// internal: true 渲染的链接都是 hugo 内部链接,用户生成 hugo web
|
||||
//
|
||||
// false 渲染的链接是外部 HTTPS 链接,用于生成 PDF
|
||||
func buildChapterTwo(internal bool) {
|
||||
var (
|
||||
gr GraphQLResp
|
||||
questions []Question
|
||||
gr m.GraphQLResp
|
||||
questions []m.Question
|
||||
count int
|
||||
)
|
||||
for index, tag := range chapterTwoSlug {
|
||||
@ -178,25 +179,25 @@ func buildChapterTwo(internal bool) {
|
||||
return
|
||||
}
|
||||
questions = gr.Data.TopicTag.Questions
|
||||
mdrows := ConvertMdModelFromQuestions(questions)
|
||||
sort.Sort(SortByQuestionID(mdrows))
|
||||
solutionIds, _, _ := LoadSolutionsDir()
|
||||
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 := GenerateTagMdRows(solutionIds, tl, mdrows, internal)
|
||||
tls := m.GenerateTagMdRows(solutionIds, tl, mdrows, internal)
|
||||
//fmt.Printf("tls = %v\n", tls)
|
||||
// 按照模板渲染 README
|
||||
res, err := renderChapterTwo(fmt.Sprintf("./template/%v.md", chapterTwoFileName[index]), TagLists{TagLists: tls})
|
||||
res, err := renderChapterTwo(fmt.Sprintf("./template/%v.md", chapterTwoFileName[index]), m.TagLists{TagLists: tls})
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
if internal {
|
||||
WriteFile(fmt.Sprintf("../website/content/ChapterTwo/%v.md", chapterTwoFileName[index]), res)
|
||||
util.WriteFile(fmt.Sprintf("../website/content/ChapterTwo/%v.md", chapterTwoFileName[index]), res)
|
||||
} else {
|
||||
WriteFile(fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", chapterTwoFileName[index]), res)
|
||||
util.WriteFile(fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", chapterTwoFileName[index]), res)
|
||||
}
|
||||
|
||||
count++
|
||||
@ -204,13 +205,13 @@ func buildChapterTwo(internal bool) {
|
||||
fmt.Printf("write %v files successful", count)
|
||||
}
|
||||
|
||||
func loadMetaData(filePath string) (map[int]TagList, error) {
|
||||
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]TagList{}
|
||||
reader, metaMap := bufio.NewReader(f), map[int]m.TagList{}
|
||||
|
||||
for {
|
||||
line, _, err := reader.ReadLine()
|
||||
@ -223,7 +224,7 @@ func loadMetaData(filePath string) (map[int]TagList, error) {
|
||||
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] = TagList{
|
||||
metaMap[v] = m.TagList{
|
||||
FrontendQuestionID: int32(v),
|
||||
Acceptance: "",
|
||||
Difficulty: "",
|
||||
@ -234,7 +235,7 @@ func loadMetaData(filePath string) (map[int]TagList, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func renderChapterTwo(filePath string, tls TagLists) ([]byte, error) {
|
||||
func renderChapterTwo(filePath string, tls m.TagLists) ([]byte, error) {
|
||||
f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -270,18 +271,18 @@ func buildBookMenu() {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
WriteFile("../website/content/menu/index.md", res)
|
||||
util.WriteFile("../website/content/menu/index.md", res)
|
||||
fmt.Println("generate Menu successful")
|
||||
}
|
||||
|
||||
// 拷贝 leetcode 目录下的题解 README 文件至第四章对应文件夹中
|
||||
func copyLackFile() {
|
||||
solutionIds, soName, _ := LoadSolutionsDir()
|
||||
_, ch4Ids := LoadChapterFourDir()
|
||||
solutionIds, soName, _ := util.LoadSolutionsDir()
|
||||
_, ch4Ids := util.LoadChapterFourDir()
|
||||
|
||||
needCopy := []string{}
|
||||
for i := 0; i < len(solutionIds); i++ {
|
||||
if BinarySearch(ch4Ids, solutionIds[i]) == -1 {
|
||||
if util.BinarySearch(ch4Ids, solutionIds[i]) == -1 {
|
||||
needCopy = append(needCopy, soName[i])
|
||||
}
|
||||
}
|
||||
@ -293,12 +294,12 @@ func copyLackFile() {
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
err = os.MkdirAll(fmt.Sprintf("../website/content/ChapterFour/%v", GetChpaterFourFileNum(tmp)), os.ModePerm)
|
||||
err = os.MkdirAll(fmt.Sprintf("../website/content/ChapterFour/%v", util.GetChpaterFourFileNum(tmp)), os.ModePerm)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
CopyFile(fmt.Sprintf("../website/content/ChapterFour/%v/%v.md", GetChpaterFourFileNum(tmp), needCopy[i]), fmt.Sprintf("../leetcode/%v/README.md", needCopy[i]))
|
||||
CopyFile(fmt.Sprintf("../website/content/ChapterFour/%v/_index.md", GetChpaterFourFileNum(tmp)), "./template/collapseSection.md")
|
||||
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 {
|
||||
|
@ -3,10 +3,9 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/mozillazg/request"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/mozillazg/request"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -1,17 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
m "github.com/halfrost/LeetCode-Go/ctl/models"
|
||||
"github.com/halfrost/LeetCode-Go/ctl/util"
|
||||
"sort"
|
||||
)
|
||||
|
||||
func statisticalData(problemsMap map[int]StatStatusPairs, solutionIds []int) (easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard int32, optimizingIds []int) {
|
||||
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 DifficultyMap[v.Difficulty.Level] {
|
||||
switch m.DifficultyMap[v.Difficulty.Level] {
|
||||
case "Easy":
|
||||
{
|
||||
easyTotal++
|
||||
if v.Status == "ac" && BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
|
||||
if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
|
||||
optimizingEasy++
|
||||
optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID))
|
||||
}
|
||||
@ -19,7 +21,7 @@ func statisticalData(problemsMap map[int]StatStatusPairs, solutionIds []int) (ea
|
||||
case "Medium":
|
||||
{
|
||||
mediumTotal++
|
||||
if v.Status == "ac" && BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
|
||||
if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
|
||||
optimizingMedium++
|
||||
optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID))
|
||||
}
|
||||
@ -27,7 +29,7 @@ func statisticalData(problemsMap map[int]StatStatusPairs, solutionIds []int) (ea
|
||||
case "Hard":
|
||||
{
|
||||
hardTotal++
|
||||
if v.Status == "ac" && BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
|
||||
if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 {
|
||||
optimizingHard++
|
||||
optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID))
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
---
|
||||
title: 2.14 ✅ Sorting
|
||||
title: 2.14 ✅ Sort
|
||||
type: docs
|
||||
weight: 14
|
||||
---
|
||||
|
||||
# Sorting
|
||||
# Sort
|
||||
|
||||

|
||||
|
@ -10,9 +10,9 @@
|
||||

|
||||
|
||||
<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>
|
||||
<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://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">
|
||||
@ -23,7 +23,7 @@
|
||||
</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>
|
||||
<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">
|
||||
@ -32,7 +32,7 @@
|
||||
<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>
|
||||
<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>
|
||||
@ -42,10 +42,10 @@
|
||||
<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>
|
||||
离线版本的电子书《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>
|
||||
<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》至设备桌面随时学习
|
||||
@ -550,7 +550,7 @@ Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Bit_Mani
|
||||
|
||||

|
||||
|
||||
- 灵活使用并查集的思想,熟练掌握并查集的[模板](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。
|
||||
- 灵活使用并查集的思想,熟练掌握并查集的[模板](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 题。
|
||||
@ -630,10 +630,10 @@ Problems List in [there](https://books.halfrost.com/leetcode/ChapterTwo/Binary_I
|
||||
----------------------------------------------------------------------------------------
|
||||
|
||||
<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>
|
||||
<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/)
|
||||
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/)
|
||||
|
||||
|
||||
|
||||
|
@ -3,12 +3,14 @@ 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 Mdrows) {
|
||||
func makeReadmeFile(mdrows m.Mdrows) {
|
||||
file := "./README.md"
|
||||
os.Remove(file)
|
||||
var b bytes.Buffer
|
||||
@ -18,7 +20,7 @@ func makeReadmeFile(mdrows Mdrows) {
|
||||
fmt.Println(err)
|
||||
}
|
||||
// 保存 README.md 文件
|
||||
WriteFile(file, b.Bytes())
|
||||
util.WriteFile(file, b.Bytes())
|
||||
}
|
||||
|
||||
func readTMPL(path string) string {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package util
|
||||
|
||||
import (
|
||||
"bufio"
|
23
go.mod
23
go.mod
@ -1,24 +1,13 @@
|
||||
module github.com/halfrost/LeetCode-Go
|
||||
|
||||
go 1.19
|
||||
|
||||
replace github.com/halfrost/LeetCode-Go/structures => ./structures
|
||||
|
||||
replace github.com/halfrost/LeetCode-Go/template => ./template
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.2.0
|
||||
github.com/halfrost/LeetCode-Go/structures v0.0.0-20220910233101-aa0e2c897b18
|
||||
github.com/halfrost/LeetCode-Go/template v0.0.0-20220910233504-e2a72e6212ce
|
||||
github.com/mozillazg/request v0.8.0
|
||||
github.com/spf13/cobra v1.5.0
|
||||
)
|
||||
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/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/kr/pretty v0.3.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
golang.org/x/net v0.0.0-20220909164309-bea034e7d591 // 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
303
go.sum
@ -1,36 +1,303 @@
|
||||
github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0=
|
||||
github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
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/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
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/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
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/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
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/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
|
||||
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
|
||||
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/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||
golang.org/x/net v0.0.0-20220909164309-bea034e7d591 h1:D0B/7al0LLrVC8aWF4+oxpv/m8bc7ViFfVS8/gXGdqI=
|
||||
golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
|
||||
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/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
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=
|
||||
|
@ -31,16 +31,15 @@ func lengthOfLongestSubstring1(s string) int {
|
||||
if len(s) == 0 {
|
||||
return 0
|
||||
}
|
||||
var freq [127]int
|
||||
var freq [256]int
|
||||
result, left, right := 0, 0, -1
|
||||
|
||||
for left < len(s) {
|
||||
if right+1 < len(s) && freq[s[right+1]] == 0 {
|
||||
freq[s[right+1]]++
|
||||
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
|
||||
freq[s[right+1]-'a']++
|
||||
right++
|
||||
|
||||
} else {
|
||||
freq[s[left]]--
|
||||
freq[s[left]-'a']--
|
||||
left++
|
||||
}
|
||||
result = max(result, right-left+1)
|
||||
|
@ -1,16 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func longestCommonPrefix(strs []string) string {
|
||||
prefix := strs[0]
|
||||
|
||||
for i := 1; i < len(strs); i++ {
|
||||
for j := 0; j < len(prefix); j++ {
|
||||
if len(strs[i]) <= j || strs[i][j] != prefix[j] {
|
||||
prefix = prefix[0:j]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prefix
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question14 struct {
|
||||
para14
|
||||
ans14
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para14 struct {
|
||||
strs []string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans14 struct {
|
||||
ans string
|
||||
}
|
||||
|
||||
func Test_Problem14(t *testing.T) {
|
||||
|
||||
qs := []question14{
|
||||
|
||||
{
|
||||
para14{[]string{"flower", "flow", "flight"}},
|
||||
ans14{"fl"},
|
||||
},
|
||||
|
||||
{
|
||||
para14{[]string{"dog", "racecar", "car"}},
|
||||
ans14{""},
|
||||
},
|
||||
|
||||
{
|
||||
para14{[]string{"ab", "a"}},
|
||||
ans14{"a"},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 14------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans14, q.para14
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p.strs, longestCommonPrefix(p.strs))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)
|
||||
|
||||
## 题目
|
||||
|
||||
Write a function to find the longest common prefix string amongst an array of strings.
|
||||
|
||||
If there is no common prefix, return an empty string "".
|
||||
|
||||
**Example 1**:
|
||||
|
||||
Input: strs = ["flower","flow","flight"]
|
||||
Output: "fl"
|
||||
|
||||
**Example 2**:
|
||||
|
||||
Input: strs = ["dog","racecar","car"]
|
||||
Output: ""
|
||||
Explanation: There is no common prefix among the input strings.
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- 1 <= strs.length <= 200
|
||||
- 0 <= strs[i].length <= 200
|
||||
- strs[i] consists of only lower-case English letters.
|
||||
|
||||
## 题目大意
|
||||
|
||||
编写一个函数来查找字符串数组中的最长公共前缀。
|
||||
|
||||
如果不存在公共前缀,返回空字符串 ""。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 对 strs 按照字符串长度进行升序排序,求出 strs 中长度最小字符串的长度 minLen
|
||||
- 逐个比较长度最小字符串与其它字符串中的字符,如果不相等就返回 commonPrefix,否则就把该字符加入 commonPrefix
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
func longestCommonPrefix(strs []string) string {
|
||||
prefix := strs[0]
|
||||
|
||||
for i := 1; i < len(strs); i++ {
|
||||
for j := 0; j < len(prefix); j++ {
|
||||
if len(strs[i]) <= j || strs[i][j] != prefix[j] {
|
||||
prefix = prefix[0:j]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prefix
|
||||
}
|
||||
```
|
@ -11,9 +11,6 @@ func threeSumClosest(nums []int, target int) int {
|
||||
if n > 2 {
|
||||
sort.Ints(nums)
|
||||
for i := 0; i < n-2; i++ {
|
||||
if i > 0 && nums[i] == nums[i-1] {
|
||||
continue
|
||||
}
|
||||
for j, k := i+1, n-1; j < k; {
|
||||
sum := nums[i] + nums[j] + nums[k]
|
||||
if abs(sum-target) < diff {
|
||||
|
@ -2,92 +2,7 @@ package leetcode
|
||||
|
||||
import "sort"
|
||||
|
||||
// 解法一 双指针
|
||||
func fourSum(nums []int, target int) (quadruplets [][]int) {
|
||||
sort.Ints(nums)
|
||||
n := len(nums)
|
||||
for i := 0; i < n-3 && nums[i]+nums[i+1]+nums[i+2]+nums[i+3] <= target; i++ {
|
||||
if i > 0 && nums[i] == nums[i-1] || nums[i]+nums[n-3]+nums[n-2]+nums[n-1] < target {
|
||||
continue
|
||||
}
|
||||
for j := i + 1; j < n-2 && nums[i]+nums[j]+nums[j+1]+nums[j+2] <= target; j++ {
|
||||
if j > i+1 && nums[j] == nums[j-1] || nums[i]+nums[j]+nums[n-2]+nums[n-1] < target {
|
||||
continue
|
||||
}
|
||||
for left, right := j+1, n-1; left < right; {
|
||||
if sum := nums[i] + nums[j] + nums[left] + nums[right]; sum == target {
|
||||
quadruplets = append(quadruplets, []int{nums[i], nums[j], nums[left], nums[right]})
|
||||
for left++; left < right && nums[left] == nums[left-1]; left++ {
|
||||
}
|
||||
for right--; left < right && nums[right] == nums[right+1]; right-- {
|
||||
}
|
||||
} else if sum < target {
|
||||
left++
|
||||
} else {
|
||||
right--
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 解法二 kSum
|
||||
func fourSum1(nums []int, target int) [][]int {
|
||||
res, cur := make([][]int, 0), make([]int, 0)
|
||||
sort.Ints(nums)
|
||||
kSum(nums, 0, len(nums)-1, target, 4, cur, &res)
|
||||
return res
|
||||
}
|
||||
|
||||
func kSum(nums []int, left, right int, target int, k int, cur []int, res *[][]int) {
|
||||
if right-left+1 < k || k < 2 || target < nums[left]*k || target > nums[right]*k {
|
||||
return
|
||||
}
|
||||
if k == 2 {
|
||||
// 2 sum
|
||||
twoSum(nums, left, right, target, cur, res)
|
||||
} else {
|
||||
for i := left; i < len(nums); i++ {
|
||||
if i == left || (i > left && nums[i-1] != nums[i]) {
|
||||
next := make([]int, len(cur))
|
||||
copy(next, cur)
|
||||
next = append(next, nums[i])
|
||||
kSum(nums, i+1, len(nums)-1, target-nums[i], k-1, next, res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func twoSum(nums []int, left, right int, target int, cur []int, res *[][]int) {
|
||||
for left < right {
|
||||
sum := nums[left] + nums[right]
|
||||
if sum == target {
|
||||
cur = append(cur, nums[left], nums[right])
|
||||
temp := make([]int, len(cur))
|
||||
copy(temp, cur)
|
||||
*res = append(*res, temp)
|
||||
// reset cur to previous state
|
||||
cur = cur[:len(cur)-2]
|
||||
left++
|
||||
right--
|
||||
for left < right && nums[left] == nums[left-1] {
|
||||
left++
|
||||
}
|
||||
for left < right && nums[right] == nums[right+1] {
|
||||
right--
|
||||
}
|
||||
} else if sum < target {
|
||||
left++
|
||||
} else {
|
||||
right--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 解法三
|
||||
func fourSum2(nums []int, target int) [][]int {
|
||||
func fourSum(nums []int, target int) [][]int {
|
||||
res := [][]int{}
|
||||
counter := map[int]int{}
|
||||
for _, value := range nums {
|
||||
|
@ -1,6 +1,5 @@
|
||||
package leetcode
|
||||
|
||||
// 解法一
|
||||
func nextPermutation(nums []int) {
|
||||
i, j := 0, 0
|
||||
for i = len(nums) - 2; i >= 0; i-- {
|
||||
@ -30,43 +29,3 @@ func reverse(nums *[]int, i, j int) {
|
||||
func swap(nums *[]int, i, j int) {
|
||||
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
|
||||
}
|
||||
|
||||
// 解法二
|
||||
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
|
||||
func nextPermutation1(nums []int) {
|
||||
var n = len(nums)
|
||||
var pIdx = checkPermutationPossibility(nums)
|
||||
if pIdx == -1 {
|
||||
reverse(&nums, 0, n-1)
|
||||
return
|
||||
}
|
||||
|
||||
var rp = len(nums) - 1
|
||||
// start from right most to leftward,find the first number which is larger than PIVOT
|
||||
for rp > 0 {
|
||||
if nums[rp] > nums[pIdx] {
|
||||
swap(&nums, pIdx, rp)
|
||||
break
|
||||
} else {
|
||||
rp--
|
||||
}
|
||||
}
|
||||
// Finally, Reverse all elements which are right from pivot
|
||||
reverse(&nums, pIdx+1, n-1)
|
||||
}
|
||||
|
||||
// checkPermutationPossibility returns 1st occurrence Index where
|
||||
// value is in decreasing order(from right to left)
|
||||
// returns -1 if not found(it's already in its last permutation)
|
||||
func checkPermutationPossibility(nums []int) (idx int) {
|
||||
// search right to left for 1st number(from right) that is not in increasing order
|
||||
var rp = len(nums) - 1
|
||||
for rp > 0 {
|
||||
if nums[rp-1] < nums[rp] {
|
||||
idx = rp - 1
|
||||
return idx
|
||||
}
|
||||
rp--
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
package leetcode
|
||||
|
||||
// 解法一
|
||||
func rotate(matrix [][]int) {
|
||||
length := len(matrix)
|
||||
// rotate by diagonal 对角线变换
|
||||
@ -16,46 +15,3 @@ func rotate(matrix [][]int) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 解法二
|
||||
func rotate1(matrix [][]int) {
|
||||
n := len(matrix)
|
||||
if n == 1 {
|
||||
return
|
||||
}
|
||||
/* rotate clock-wise = 1. transpose matrix => 2. reverse(matrix[i])
|
||||
|
||||
1 2 3 4 1 5 9 13 13 9 5 1
|
||||
5 6 7 8 => 2 6 10 14 => 14 10 6 2
|
||||
9 10 11 12 3 7 11 15 15 11 7 3
|
||||
13 14 15 16 4 8 12 16 16 12 8 4
|
||||
|
||||
*/
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
// transpose, i=rows, j=columns
|
||||
// j = i+1, coz diagonal elements didn't change in a square matrix
|
||||
for j := i + 1; j < n; j++ {
|
||||
swap(matrix, i, j)
|
||||
}
|
||||
// reverse each row of the image
|
||||
matrix[i] = reverse(matrix[i])
|
||||
}
|
||||
}
|
||||
|
||||
// swap changes original slice's i,j position
|
||||
func swap(nums [][]int, i, j int) {
|
||||
nums[i][j], nums[j][i] = nums[j][i], nums[i][j]
|
||||
}
|
||||
|
||||
// reverses a row of image, matrix[i]
|
||||
func reverse(nums []int) []int {
|
||||
var lp, rp = 0, len(nums) - 1
|
||||
|
||||
for lp < rp {
|
||||
nums[lp], nums[rp] = nums[rp], nums[lp]
|
||||
lp++
|
||||
rp--
|
||||
}
|
||||
return nums
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func lengthOfLastWord(s string) int {
|
||||
last := len(s) - 1
|
||||
for last >= 0 && s[last] == ' ' {
|
||||
last--
|
||||
}
|
||||
if last < 0 {
|
||||
return 0
|
||||
}
|
||||
first := last
|
||||
for first >= 0 && s[first] != ' ' {
|
||||
first--
|
||||
}
|
||||
return last - first
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question58 struct {
|
||||
para58
|
||||
ans58
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para58 struct {
|
||||
s string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans58 struct {
|
||||
ans int
|
||||
}
|
||||
|
||||
func Test_Problem58(t *testing.T) {
|
||||
|
||||
qs := []question58{
|
||||
|
||||
{
|
||||
para58{"Hello World"},
|
||||
ans58{5},
|
||||
},
|
||||
|
||||
{
|
||||
para58{" fly me to the moon "},
|
||||
ans58{4},
|
||||
},
|
||||
|
||||
{
|
||||
para58{"luffy is still joyboy"},
|
||||
ans58{6},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 58------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans58, q.para58
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, lengthOfLastWord(p.s))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
# [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Given a string `s` consisting of some words separated by some number of spaces, return *the length of the **last** word in the string.*
|
||||
|
||||
A **word** is a maximal substring consisting of non-space characters only.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input: s = "Hello World"
|
||||
Output: 5
|
||||
Explanation: The last word is "World" with length 5.
|
||||
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: s = " fly me to the moon "
|
||||
Output: 4
|
||||
Explanation: The last word is "moon" with length 4.
|
||||
|
||||
```
|
||||
|
||||
**Example 3:**
|
||||
|
||||
```
|
||||
Input: s = "luffy is still joyboy"
|
||||
Output: 6
|
||||
Explanation: The last word is "joyboy" with length 6.
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `1 <= s.length <= 104`
|
||||
- `s` consists of only English letters and spaces `' '`.
|
||||
- There will be at least one word in `s`.
|
||||
|
||||
## 题目大意
|
||||
|
||||
给你一个字符串 `s`,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。**单词** 是指仅由字母组成、不包含任何空格字符的最大子字符串。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
func lengthOfLastWord(s string) int {
|
||||
last := len(s) - 1
|
||||
for last >= 0 && s[last] == ' ' {
|
||||
last--
|
||||
}
|
||||
if last < 0 {
|
||||
return 0
|
||||
}
|
||||
first := last
|
||||
for first >= 0 && s[first] != ' ' {
|
||||
first--
|
||||
}
|
||||
return last - first
|
||||
}
|
||||
```
|
@ -1,22 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func isNumber(s string) bool {
|
||||
numFlag, dotFlag, eFlag := false, false, false
|
||||
for i := 0; i < len(s); i++ {
|
||||
if '0' <= s[i] && s[i] <= '9' {
|
||||
numFlag = true
|
||||
} else if s[i] == '.' && !dotFlag && !eFlag {
|
||||
dotFlag = true
|
||||
} else if (s[i] == 'e' || s[i] == 'E') && !eFlag && numFlag {
|
||||
eFlag = true
|
||||
numFlag = false // reJudge integer after 'e' or 'E'
|
||||
} else if (s[i] == '+' || s[i] == '-') && (i == 0 || s[i-1] == 'e' || s[i-1] == 'E') {
|
||||
continue
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// avoid case: s == '.' or 'e/E' or '+/-' and etc...
|
||||
// string s must have num
|
||||
return numFlag
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Problem65(t *testing.T) {
|
||||
|
||||
tcs := []struct {
|
||||
s string
|
||||
ans bool
|
||||
}{
|
||||
|
||||
{
|
||||
"0",
|
||||
true,
|
||||
},
|
||||
|
||||
{
|
||||
"e",
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
".",
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
".1",
|
||||
true,
|
||||
},
|
||||
}
|
||||
fmt.Printf("------------------------Leetcode Problem 65------------------------\n")
|
||||
|
||||
for _, tc := range tcs {
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", tc, isNumber(tc.s))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,78 +0,0 @@
|
||||
# [65. Valid Number](https://leetcode.com/problems/valid-number/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
A **valid number** can be split up into these components (in order):
|
||||
|
||||
1. A **decimal number** or an integer.
|
||||
2. (Optional) An 'e' or 'E', followed by an **integer.**
|
||||
|
||||
A **decimal number** can be split up into these components (in order):
|
||||
|
||||
1. (Optional) A sign character (either '+' or '-').
|
||||
2. One of the following formats:
|
||||
1. One or more digits, followed by a dot '.'.
|
||||
2. One or more digits, followed by a dot '.', followed by one or more digits.
|
||||
3. A dot '.', followed by one or more digits.
|
||||
|
||||
An **integer** can be split up into these components (in order):
|
||||
|
||||
1. (Optional) A sign character (either '+' or '-').
|
||||
2. One or more digits.
|
||||
|
||||
For example, all the following are valid numbers: `["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]`, while the following are not valid numbers: `["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].`
|
||||
|
||||
Given a string s, return true if s is a **valid number.**
|
||||
|
||||
**Example:**
|
||||
|
||||
Input: s = "0"
|
||||
Output: true
|
||||
|
||||
Input: s = "e"
|
||||
Output: false
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个字符串S,请根据以上的规则判断该字符串是否是一个有效的数字字符串。
|
||||
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 用三个变量分别标记是否出现过数字、是否出现过'.'和 是否出现过 'e/E'
|
||||
- 从左到右依次遍历字符串中的每一个元素
|
||||
- 如果是数字,则标记数字出现过
|
||||
- 如果是 '.', 则需要 '.'没有出现过,并且 'e/E' 没有出现过,才会进行标记
|
||||
- 如果是 'e/E', 则需要 'e/E'没有出现过,并且前面出现过数字,才会进行标记
|
||||
- 如果是 '+/-', 则需要是第一个字符,或者前一个字符是 'e/E',才会进行标记,并重置数字出现的标识
|
||||
- 最后返回时,需要字符串中至少出现过数字,避免下列case: s == '.' or 'e/E' or '+/e' and etc...
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
func isNumber(s string) bool {
|
||||
numFlag, dotFlag, eFlag := false, false, false
|
||||
for i := 0; i < len(s); i++ {
|
||||
if '0' <= s[i] && s[i] <= '9' {
|
||||
numFlag = true
|
||||
} else if s[i] == '.' && !dotFlag && !eFlag {
|
||||
dotFlag = true
|
||||
} else if (s[i] == 'e' || s[i] == 'E') && !eFlag && numFlag {
|
||||
eFlag = true
|
||||
numFlag = false // reJudge integer after 'e' or 'E'
|
||||
} else if (s[i] == '+' || s[i] == '-') && (i == 0 || s[i-1] == 'e' || s[i-1] == 'E') {
|
||||
continue
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// avoid case: s == '.' or 'e/E' or '+/-' and etc...
|
||||
// string s must have num
|
||||
return numFlag
|
||||
}
|
||||
|
||||
```
|
@ -1,8 +1,8 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"math"
|
||||
import "math"
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
|
@ -18,20 +18,20 @@ type TreeNode = structures.TreeNode
|
||||
|
||||
// 解法一 dfs
|
||||
func isSymmetric(root *TreeNode) bool {
|
||||
if root == nil {
|
||||
return true
|
||||
}
|
||||
return isMirror(root.Left, root.Right)
|
||||
return root == nil || dfs(root.Left, root.Right)
|
||||
}
|
||||
|
||||
func isMirror(left *TreeNode, right *TreeNode) bool {
|
||||
if left == nil && right == nil {
|
||||
func dfs(rootLeft, rootRight *TreeNode) bool {
|
||||
if rootLeft == nil && rootRight == nil {
|
||||
return true
|
||||
}
|
||||
if left == nil || right == nil {
|
||||
if rootLeft == nil || rootRight == nil {
|
||||
return false
|
||||
}
|
||||
return (left.Val == right.Val) && isMirror(left.Left, right.Right) && isMirror(left.Right, right.Left)
|
||||
if rootLeft.Val != rootRight.Val {
|
||||
return false
|
||||
}
|
||||
return dfs(rootLeft.Left, rootRight.Right) && dfs(rootLeft.Right, rootRight.Left)
|
||||
}
|
||||
|
||||
// 解法二
|
||||
|
@ -16,23 +16,7 @@ type TreeNode = structures.TreeNode
|
||||
* }
|
||||
*/
|
||||
|
||||
// 解法一, 直接传入需要的 slice 范围作为输入, 可以避免申请对应 inorder 索引的内存, 内存使用(leetcode test case) 4.7MB -> 4.3MB.
|
||||
func buildTree(preorder []int, inorder []int) *TreeNode {
|
||||
if len(preorder) == 0 {
|
||||
return nil
|
||||
}
|
||||
root := &TreeNode{Val: preorder[0]}
|
||||
for pos, node := range inorder {
|
||||
if node == root.Val {
|
||||
root.Left = buildTree(preorder[1:pos+1], inorder[:pos])
|
||||
root.Right = buildTree(preorder[pos+1:], inorder[pos+1:])
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
// 解法二
|
||||
func buildTree1(preorder []int, inorder []int) *TreeNode {
|
||||
inPos := make(map[int]int)
|
||||
for i := 0; i < len(inorder); i++ {
|
||||
inPos[inorder[i]] = i
|
||||
|
@ -16,25 +16,7 @@ type TreeNode = structures.TreeNode
|
||||
* }
|
||||
*/
|
||||
|
||||
// 解法一, 直接传入需要的 slice 范围作为输入, 可以避免申请对应 inorder 索引的内存, 内存使用(leetcode test case) 4.7MB -> 4.3MB.
|
||||
func buildTree(inorder []int, postorder []int) *TreeNode {
|
||||
postorderLen := len(postorder)
|
||||
if len(inorder) == 0 {
|
||||
return nil
|
||||
}
|
||||
root := &TreeNode{Val: postorder[postorderLen-1]}
|
||||
postorder = postorder[:postorderLen-1]
|
||||
for pos, node := range inorder {
|
||||
if node == root.Val {
|
||||
root.Left = buildTree(inorder[:pos], postorder[:len(inorder[:pos])])
|
||||
root.Right = buildTree(inorder[pos+1:], postorder[len(inorder[:pos]):])
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
// 解法二
|
||||
func buildTree1(inorder []int, postorder []int) *TreeNode {
|
||||
inPos := make(map[int]int)
|
||||
for i := 0; i < len(inorder); i++ {
|
||||
inPos[inorder[i]] = i
|
||||
|
@ -18,21 +18,23 @@ type TreeNode = structures.TreeNode
|
||||
|
||||
// 解法一 非递归
|
||||
func flatten(root *TreeNode) {
|
||||
list := preorder(root)
|
||||
list, cur := []int{}, &TreeNode{}
|
||||
preorder(root, &list)
|
||||
cur = root
|
||||
for i := 1; i < len(list); i++ {
|
||||
prev, cur := list[i-1], list[i]
|
||||
prev.Left, prev.Right = nil, cur
|
||||
cur.Left = nil
|
||||
cur.Right = &TreeNode{Val: list[i], Left: nil, Right: nil}
|
||||
cur = cur.Right
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func preorder(root *TreeNode) (ans []*TreeNode) {
|
||||
func preorder(root *TreeNode, output *[]int) {
|
||||
if root != nil {
|
||||
ans = append(ans, root)
|
||||
ans = append(ans, preorder(root.Left)...)
|
||||
ans = append(ans, preorder(root.Right)...)
|
||||
*output = append(*output, root.Val)
|
||||
preorder(root.Left, output)
|
||||
preorder(root.Right, output)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 解法二 递归
|
||||
|
@ -15,13 +15,13 @@ type question114 struct {
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para114 struct {
|
||||
one []string
|
||||
one []int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans114 struct {
|
||||
one []string
|
||||
one []int
|
||||
}
|
||||
|
||||
func Test_Problem114(t *testing.T) {
|
||||
@ -29,18 +29,8 @@ func Test_Problem114(t *testing.T) {
|
||||
qs := []question114{
|
||||
|
||||
{
|
||||
para114{[]string{"1", "2", "5", "3", "4", "null", "6"}},
|
||||
ans114{[]string{"1", "null", "2", "null", "3", "null", "4", "null", "5", "null", "6"}},
|
||||
},
|
||||
|
||||
{
|
||||
para114{[]string{"0"}},
|
||||
ans114{[]string{"0"}},
|
||||
},
|
||||
|
||||
{
|
||||
para114{[]string{"1", "2", "3", "4", "5", "6"}},
|
||||
ans114{[]string{"1", "2", "4", "5", "3", "6", "null"}},
|
||||
para114{[]int{1, 2, 3, 4, 5, 6}},
|
||||
ans114{[]int{1, 2, 3, 4, 5, 6}},
|
||||
},
|
||||
}
|
||||
|
||||
@ -49,10 +39,9 @@ func Test_Problem114(t *testing.T) {
|
||||
for _, q := range qs {
|
||||
_, p := q.ans114, q.para114
|
||||
fmt.Printf("【input】:%v \n", p)
|
||||
rootOne := structures.Strings2TreeNode(p.one)
|
||||
rootOne := structures.Ints2TreeNode(p.one)
|
||||
flatten(rootOne)
|
||||
fmt.Printf("【levelorder output】:%v \n", structures.Tree2LevelOrderStrings(rootOne))
|
||||
fmt.Printf("【preorder output】:%v \n", structures.Tree2PreOrderStrings(rootOne))
|
||||
fmt.Printf("【output】:%v \n", structures.Tree2Preorder(rootOne))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
||||
|
@ -1,52 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
type Node struct {
|
||||
Val int
|
||||
Left *Node
|
||||
Right *Node
|
||||
Next *Node
|
||||
}
|
||||
|
||||
// 解法一:迭代
|
||||
func connect(root *Node) *Node {
|
||||
if root == nil {
|
||||
return root
|
||||
}
|
||||
q := []*Node{root}
|
||||
for len(q) > 0 {
|
||||
var p []*Node
|
||||
// 遍历这一层的所有节点
|
||||
for i, node := range q {
|
||||
if i+1 < len(q) {
|
||||
node.Next = q[i+1]
|
||||
}
|
||||
if node.Left != nil {
|
||||
p = append(p, node.Left)
|
||||
}
|
||||
if node.Right != nil {
|
||||
p = append(p, node.Right)
|
||||
}
|
||||
}
|
||||
q = p
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
// 解法二 递归
|
||||
func connect2(root *Node) *Node {
|
||||
if root == nil {
|
||||
return nil
|
||||
}
|
||||
connectTwoNode(root.Left, root.Right)
|
||||
return root
|
||||
}
|
||||
|
||||
func connectTwoNode(node1, node2 *Node) {
|
||||
if node1 == nil || node2 == nil {
|
||||
return
|
||||
}
|
||||
node1.Next = node2
|
||||
connectTwoNode(node1.Left, node1.Right)
|
||||
connectTwoNode(node2.Left, node2.Right)
|
||||
connectTwoNode(node1.Right, node2.Left)
|
||||
}
|
@ -1,117 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question116 struct {
|
||||
para116
|
||||
ans116
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para116 struct {
|
||||
one *Node
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans116 struct {
|
||||
one *Node
|
||||
}
|
||||
|
||||
func newQuestionNode() *Node {
|
||||
node7 := &Node{}
|
||||
node7.Val = 7
|
||||
|
||||
node6 := &Node{}
|
||||
node6.Val = 6
|
||||
|
||||
node5 := &Node{}
|
||||
node5.Val = 5
|
||||
|
||||
node4 := &Node{}
|
||||
node4.Val = 4
|
||||
|
||||
node3 := &Node{}
|
||||
node3.Val = 3
|
||||
|
||||
node2 := &Node{}
|
||||
node2.Val = 2
|
||||
|
||||
node1 := &Node{}
|
||||
node1.Val = 1
|
||||
|
||||
node1.Left = node2
|
||||
node1.Right = node3
|
||||
|
||||
node2.Left = node4
|
||||
node2.Right = node5
|
||||
|
||||
node3.Left = node6
|
||||
node3.Right = node7
|
||||
return node1
|
||||
}
|
||||
|
||||
func newResultNode() *Node {
|
||||
node7 := &Node{}
|
||||
node7.Val = 7
|
||||
|
||||
node6 := &Node{}
|
||||
node6.Val = 6
|
||||
|
||||
node5 := &Node{}
|
||||
node5.Val = 5
|
||||
|
||||
node4 := &Node{}
|
||||
node4.Val = 4
|
||||
|
||||
node3 := &Node{}
|
||||
node3.Val = 3
|
||||
|
||||
node2 := &Node{}
|
||||
node2.Val = 2
|
||||
|
||||
node1 := &Node{}
|
||||
node1.Val = 1
|
||||
|
||||
node1.Left = node2
|
||||
node1.Right = node3
|
||||
|
||||
node2.Left = node4
|
||||
node2.Right = node5
|
||||
|
||||
node3.Left = node6
|
||||
node3.Right = node7
|
||||
|
||||
node1.Next = nil
|
||||
node2.Next = node3
|
||||
node3.Next = nil
|
||||
node4.Next = node5
|
||||
node5.Next = node6
|
||||
node6.Next = node7
|
||||
node7.Next = nil
|
||||
|
||||
return node1
|
||||
}
|
||||
|
||||
func Test_Problem116(t *testing.T) {
|
||||
|
||||
qs := []question116{
|
||||
{
|
||||
para116{newQuestionNode()},
|
||||
ans116{newResultNode()},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 116------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans116, q.para116
|
||||
fmt.Printf("【input】:%v ", p.one)
|
||||
fmt.Printf("【output】:%v \n", connect(p.one))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,118 +0,0 @@
|
||||
# [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
|
||||
|
||||
```
|
||||
struct Node {
|
||||
int val;
|
||||
Node *left;
|
||||
Node *right;
|
||||
Node *next;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
|
||||
|
||||
Initially, all next pointers are set to `NULL`.
|
||||
|
||||
**Follow up:**
|
||||
|
||||
- You may only use constant extra space.
|
||||
- Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
|
||||
|
||||
**Example 1:**
|
||||
|
||||

|
||||
|
||||
```
|
||||
Input: root = [1,2,3,4,5,6,7]
|
||||
Output: [1,#,2,3,#,4,5,6,7,#]
|
||||
Explanation:Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- The number of nodes in the given tree is less than `4096`.
|
||||
- `1000 <= node.val <= 1000`
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
|
||||
|
||||
```jsx
|
||||
struct Node {
|
||||
int val;
|
||||
Node *left;
|
||||
Node *right;
|
||||
Node *next;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。初始状态下,所有 next 指针都被设置为 NULL。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 本质上是二叉树的层序遍历,基于广度优先搜索,将每层的节点放入队列,并遍历队列进行连接。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
type Node struct {
|
||||
Val int
|
||||
Left *Node
|
||||
Right *Node
|
||||
Next *Node
|
||||
}
|
||||
|
||||
//解法一:迭代
|
||||
func connect(root *Node) *Node {
|
||||
if root == nil {
|
||||
return root
|
||||
}
|
||||
q := []*Node{root}
|
||||
for len(q) > 0 {
|
||||
var p []*Node
|
||||
// 遍历这一层的所有节点
|
||||
for i, node := range q {
|
||||
if i+1 < len(q) {
|
||||
node.Next = q[i+1]
|
||||
}
|
||||
if node.Left != nil {
|
||||
p = append(p, node.Left)
|
||||
}
|
||||
if node.Right != nil {
|
||||
p = append(p, node.Right)
|
||||
}
|
||||
}
|
||||
q = p
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
// 解法二 递归
|
||||
func connect2(root *Node) *Node {
|
||||
if root == nil {
|
||||
return nil
|
||||
}
|
||||
connectTwoNode(root.Left, root.Right)
|
||||
return root
|
||||
}
|
||||
|
||||
func connectTwoNode(node1, node2 *Node) {
|
||||
if node1 == nil || node2 == nil {
|
||||
return
|
||||
}
|
||||
node1.Next = node2
|
||||
connectTwoNode(node1.Left, node1.Right)
|
||||
connectTwoNode(node2.Left, node2.Right)
|
||||
connectTwoNode(node1.Right, node2.Left)
|
||||
}
|
||||
```
|
@ -1,8 +1,8 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"math"
|
||||
import "math"
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
|
@ -1,20 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func candy(ratings []int) int {
|
||||
candies := make([]int, len(ratings))
|
||||
for i := 1; i < len(ratings); i++ {
|
||||
if ratings[i] > ratings[i-1] {
|
||||
candies[i] += candies[i-1] + 1
|
||||
}
|
||||
}
|
||||
for i := len(ratings) - 2; i >= 0; i-- {
|
||||
if ratings[i] > ratings[i+1] && candies[i] <= candies[i+1] {
|
||||
candies[i] = candies[i+1] + 1
|
||||
}
|
||||
}
|
||||
total := 0
|
||||
for _, candy := range candies {
|
||||
total += candy + 1
|
||||
}
|
||||
return total
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question135 struct {
|
||||
para135
|
||||
ans135
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para135 struct {
|
||||
ratings []int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans135 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
func Test_Problem135(t *testing.T) {
|
||||
|
||||
qs := []question135{
|
||||
|
||||
{
|
||||
para135{[]int{1, 0, 2}},
|
||||
ans135{5},
|
||||
},
|
||||
|
||||
{
|
||||
para135{[]int{1, 2, 2}},
|
||||
ans135{4},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 135------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans135, q.para135
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, candy(p.ratings))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
# [135. Candy](https://leetcode.com/problems/candy/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
|
||||
|
||||
You are giving candies to these children subjected to the following requirements:
|
||||
|
||||
- Each child must have at least one candy.
|
||||
- Children with a higher rating get more candies than their neighbors.
|
||||
|
||||
Return *the minimum number of candies you need to have to distribute the candies to the children*.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input: ratings = [1,0,2]
|
||||
Output: 5
|
||||
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: ratings = [1,2,2]
|
||||
Output: 4
|
||||
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
|
||||
The third child gets 1 candy because it satisfies the above two conditions.
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `n == ratings.length`
|
||||
- `1 <= n <= 2 * 10^4`
|
||||
- `0 <= ratings[i] <= 2 * 10^4`
|
||||
|
||||
## 题目大意
|
||||
|
||||
老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。你需要按照以下要求,帮助老师给这些孩子分发糖果:
|
||||
|
||||
- 每个孩子至少分配到 1 个糖果。
|
||||
- 评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。
|
||||
|
||||
那么这样下来,老师至少需要准备多少颗糖果呢?
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 本题的突破口在于,评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果,这句话。这个规则可以理解为 2 条规则,想象成按身高排队,站在下标为 0 的地方往后“看”,评分高即为个子高的,应该比前面个子矮(评分低)的分到糖果多;站在下标为 n - 1 的地方往后“看”,评分高即为个子高的,同样应该比前面个子矮(评分低)的分到糖果多。你可能会有疑问,规则都是一样的,为什么会出现至少需要多少糖果呢?因为可能出现评分一样高的同学。扫描数组两次,处理出每一个学生分别满足左规则或右规则时,最少需要被分得的糖果数量。每个人最终分得的糖果数量即为这两个数量的最大值。两次遍历结束,将所有糖果累加起来即为至少需要准备的糖果数。由于每个人至少分配到 1 个糖果,所以每个人糖果数再加一。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
func candy(ratings []int) int {
|
||||
candies := make([]int, len(ratings))
|
||||
for i := 1; i < len(ratings); i++ {
|
||||
if ratings[i] > ratings[i-1] {
|
||||
candies[i] += candies[i-1] + 1
|
||||
}
|
||||
}
|
||||
for i := len(ratings) - 2; i >= 0; i-- {
|
||||
if ratings[i] > ratings[i+1] && candies[i] <= candies[i+1] {
|
||||
candies[i] = candies[i+1] + 1
|
||||
}
|
||||
}
|
||||
total := 0
|
||||
for _, candy := range candies {
|
||||
total += candy + 1
|
||||
}
|
||||
return total
|
||||
}
|
||||
```
|
@ -26,4 +26,4 @@ Your algorithm should have a linear runtime complexity. Could you implement it w
|
||||
## 解题思路
|
||||
|
||||
- 题目要求不能使用辅助空间,并且时间复杂度只能是线性的。
|
||||
- 题目为什么要强调有一个数字出现一次,其他的出现两次?我们想到了异或运算的性质:任何一个数字异或它自己都等于0。也就是说,如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现一次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。
|
||||
- 题目为什么要强调有一个数字出现一次,其他的出现两次?我们想到了异或运算的性质:任何一个数字异或它自己都等于0。也就是说,如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现依次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。
|
||||
|
@ -9,16 +9,17 @@ type ListNode = structures.ListNode
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
* struct ListNode {
|
||||
* int val;
|
||||
* ListNode *next;
|
||||
* ListNode(int x) : val(x), next(NULL) {}
|
||||
* };
|
||||
*/
|
||||
|
||||
func hasCycle(head *ListNode) bool {
|
||||
fast := head
|
||||
slow := head
|
||||
for fast != nil && fast.Next != nil {
|
||||
for slow != nil && fast != nil && fast.Next != nil {
|
||||
fast = fast.Next.Next
|
||||
slow = slow.Next
|
||||
if fast == slow {
|
||||
|
@ -1,54 +1,6 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
type question141 struct {
|
||||
para141
|
||||
ans141
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para141 struct {
|
||||
one []int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans141 struct {
|
||||
one bool
|
||||
}
|
||||
import "testing"
|
||||
|
||||
func Test_Problem141(t *testing.T) {
|
||||
|
||||
qs := []question141{
|
||||
|
||||
{
|
||||
para141{[]int{3, 2, 0, -4}},
|
||||
ans141{false},
|
||||
},
|
||||
|
||||
{
|
||||
para141{[]int{1, 2}},
|
||||
ans141{false},
|
||||
},
|
||||
|
||||
{
|
||||
para141{[]int{1}},
|
||||
ans141{false},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 141------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans141, q.para141
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, hasCycle(structures.Ints2List(p.one)))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
||||
|
@ -31,4 +31,4 @@ Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
|
||||
|
||||
更好的做法是结合之前几道题的操作:链表逆序,找中间结点。
|
||||
|
||||
先找到链表的中间结点,然后利用逆序区间的操作,如 [第 92 题](https://github.com/halfrost/leetcode-go/tree/master/leetcode/0092.Reverse-Linked-List-II) 里的 reverseBetween() 操作,只不过这里的反转区间是从中点一直到末尾。最后利用 2 个指针,一个指向头结点,一个指向中间结点,开始拼接最终的结果。这种做法的时间复杂度是 O(n),空间复杂度是 O(1)。
|
||||
先找到链表的中间结点,然后利用逆序区间的操作,如 [第 92 题](https://github.com/halfrost/LeetCode-Go/tree/master/leetcode/0092.Reverse-Linked-List-II) 里的 reverseBetween() 操作,只不过这里的反转区间是从中点一直到末尾。最后利用 2 个指针,一个指向头结点,一个指向中间结点,开始拼接最终的结果。这种做法的时间复杂度是 O(n),空间复杂度是 O(1)。
|
@ -1,8 +1,8 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
import "fmt"
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
|
@ -2,7 +2,6 @@ package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@ -24,6 +23,7 @@ type ans190 struct {
|
||||
}
|
||||
|
||||
func Test_Problem190(t *testing.T) {
|
||||
|
||||
qs := []question190{
|
||||
|
||||
{
|
||||
@ -41,12 +41,7 @@ func Test_Problem190(t *testing.T) {
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans190, q.para190
|
||||
input := strconv.FormatUint(uint64(p.one), 2) // 32位无符号整数转换为二进制字符串
|
||||
input = fmt.Sprintf("%0*v", 32, input) // 格式化输出32位,保留前置0
|
||||
output := reverseBits(p.one)
|
||||
outputBin := strconv.FormatUint(uint64(output), 2) // 32位无符号整数转换为二进制字符串
|
||||
outputBin = fmt.Sprintf("%0*v", 32, outputBin) // 格式化输出32位,保留前置0
|
||||
fmt.Printf("【input】:%v 【output】:%v (%v)\n", input, output, outputBin)
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, reverseBits(p.one))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
||||
|
@ -2,7 +2,6 @@ package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@ -41,9 +40,7 @@ func Test_Problem191(t *testing.T) {
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans191, q.para191
|
||||
input := strconv.FormatUint(uint64(p.one), 2) // 32位无符号整数转换为二进制字符串
|
||||
input = fmt.Sprintf("%0*v", 32, input) // 格式化输出32位,保留前置0
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", input, hammingWeight(p.one))
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, hammingWeight(p.one))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
||||
|
@ -1,26 +1,27 @@
|
||||
package leetcode
|
||||
|
||||
func isHappy(n int) bool {
|
||||
if n == 0 {
|
||||
return false
|
||||
}
|
||||
res := 0
|
||||
num := n
|
||||
record := map[int]int{}
|
||||
for n != 1 {
|
||||
record[n] = n
|
||||
n = getSquareOfDigits(n)
|
||||
for _, previous := range record {
|
||||
if n == previous {
|
||||
for {
|
||||
for num != 0 {
|
||||
res += (num % 10) * (num % 10)
|
||||
num = num / 10
|
||||
}
|
||||
if _, ok := record[res]; !ok {
|
||||
if res == 1 {
|
||||
return true
|
||||
}
|
||||
record[res] = res
|
||||
num = res
|
||||
res = 0
|
||||
continue
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getSquareOfDigits(n int) int {
|
||||
squareOfDigits := 0
|
||||
temporary := n
|
||||
for temporary != 0 {
|
||||
remainder := temporary % 10
|
||||
squareOfDigits += remainder * remainder
|
||||
temporary /= 10
|
||||
}
|
||||
return squareOfDigits
|
||||
}
|
||||
|
@ -35,16 +35,6 @@ func Test_Problem202(t *testing.T) {
|
||||
para202{19},
|
||||
ans202{true},
|
||||
},
|
||||
|
||||
{
|
||||
para202{2},
|
||||
ans202{false},
|
||||
},
|
||||
|
||||
{
|
||||
para202{3},
|
||||
ans202{false},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 202------------------------\n")
|
||||
|
@ -29,5 +29,5 @@ You may assume k is always valid, 1 ≤ k ≤ array's length.
|
||||
|
||||
## 解题思路
|
||||
|
||||
在快速选择 quickselect 的 partition 操作中,每次 partition 操作结束都会返回一个点,这个标定点的下标和最终排序之后有序数组中这个元素所在的下标是一致的。利用这个特性,我们可以不断的划分数组区间,最终找到第 K 大的元素。执行一次 partition 操作以后,如果这个元素的下标比 K 小,那么接着就在后边的区间继续执行 partition 操作;如果这个元素的下标比 K 大,那么就在左边的区间继续执行 partition 操作;如果相等就直接输出这个下标对应的数组元素即可。
|
||||
在快排的 partition 操作中,每次 partition 操作结束都会返回一个点,这个标定点的下标和最终排序之后有序数组中这个元素所在的下标是一致的。利用这个特性,我们可以不断的划分数组区间,最终找到第 K 大的元素。执行一次 partition 操作以后,如果这个元素的下标比 K 小,那么接着就在后边的区间继续执行 partition 操作;如果这个元素的下标比 K 大,那么就在左边的区间继续执行 partition 操作;如果相等就直接输出这个下标对应的数组元素即可。
|
||||
|
||||
|
@ -81,7 +81,7 @@ func (bit *BinaryIndexedTree) Query(index int) int {
|
||||
return sum
|
||||
}
|
||||
|
||||
// 解法二 线段树 Segment Tree,时间复杂度 O(n log n)
|
||||
// 解法三 线段树 Segment Tree,时间复杂度 O(n log n)
|
||||
func getSkyline1(buildings [][]int) [][]int {
|
||||
st, ans, lastHeight, check := template.SegmentTree{}, [][]int{}, 0, false
|
||||
posMap, pos := discretization218(buildings)
|
||||
|
@ -15,26 +15,8 @@ type ListNode = structures.ListNode
|
||||
* }
|
||||
*/
|
||||
|
||||
// 解法一
|
||||
func isPalindrome(head *ListNode) bool {
|
||||
slice := []int{}
|
||||
for head != nil {
|
||||
slice = append(slice, head.Val)
|
||||
head = head.Next
|
||||
}
|
||||
for i, j := 0, len(slice)-1; i < j; {
|
||||
if slice[i] != slice[j] {
|
||||
return false
|
||||
}
|
||||
i++
|
||||
j--
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 解法二
|
||||
// 此题和 143 题 Reorder List 思路基本一致
|
||||
func isPalindrome1(head *ListNode) bool {
|
||||
func isPalindrome234(head *ListNode) bool {
|
||||
if head == nil || head.Next == nil {
|
||||
return true
|
||||
}
|
||||
@ -46,6 +28,7 @@ func isPalindrome1(head *ListNode) bool {
|
||||
p1 = p1.Next
|
||||
p2 = p2.Next.Next
|
||||
}
|
||||
|
||||
// 反转链表后半部分 1->2->3->4->5->6 to 1->2->3->6->5->4
|
||||
preMiddle := p1
|
||||
preCurrent := p1.Next
|
||||
@ -55,6 +38,7 @@ func isPalindrome1(head *ListNode) bool {
|
||||
current.Next = preMiddle.Next
|
||||
preMiddle.Next = current
|
||||
}
|
||||
|
||||
// 扫描表,判断是否是回文
|
||||
p1 = head
|
||||
p2 = preMiddle.Next
|
||||
@ -75,15 +59,18 @@ func isPalindrome1(head *ListNode) bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// L2ss define
|
||||
func L2ss(head *ListNode) []int {
|
||||
res := []int{}
|
||||
|
||||
for head != nil {
|
||||
res = append(res, head.Val)
|
||||
head = head.Next
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
@ -83,7 +83,7 @@ func Test_Problem234(t *testing.T) {
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans234, q.para234
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, isPalindrome(structures.Ints2List(p.one)))
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, isPalindrome234(structures.Ints2List(p.one)))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
||||
|
@ -15,6 +15,14 @@ type ListNode = structures.ListNode
|
||||
* }
|
||||
*/
|
||||
func deleteNode(node *ListNode) {
|
||||
node.Val = node.Next.Val
|
||||
node.Next = node.Next.Next
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
cur := node
|
||||
for cur.Next.Next != nil {
|
||||
cur.Val = cur.Next.Val
|
||||
cur = cur.Next
|
||||
}
|
||||
cur.Val = cur.Next.Val
|
||||
cur.Next = nil
|
||||
}
|
||||
|
@ -1,64 +1,35 @@
|
||||
# [237. Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Write a function to **delete a node** in a singly-linked list. You will **not** be given access to the `head` of the list, instead you will be given access to **the node to be deleted** directly.
|
||||
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
|
||||
|
||||
It is **guaranteed** that the node to be deleted is **not a tail node** in the list.
|
||||
Given linked list -- head = [4,5,1,9], which looks like following:
|
||||
|
||||
**Example 1:**
|
||||

|
||||
|
||||

|
||||
Example 1:
|
||||
|
||||
```
|
||||
```c
|
||||
Input: head = [4,5,1,9], node = 5
|
||||
Output: [4,1,9]
|
||||
Explanation:You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
|
||||
|
||||
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
Example 2:
|
||||
|
||||

|
||||
|
||||
```
|
||||
```c
|
||||
Input: head = [4,5,1,9], node = 1
|
||||
Output: [4,5,9]
|
||||
Explanation:You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
|
||||
|
||||
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
|
||||
```
|
||||
|
||||
**Example 3:**
|
||||
Note:
|
||||
|
||||
```
|
||||
Input: head = [1,2,3,4], node = 3
|
||||
Output: [1,2,4]
|
||||
|
||||
```
|
||||
|
||||
**Example 4:**
|
||||
|
||||
```
|
||||
Input: head = [0,1], node = 0
|
||||
Output: [1]
|
||||
|
||||
```
|
||||
|
||||
**Example 5:**
|
||||
|
||||
```
|
||||
Input: head = [-3,5,-99], node = -3
|
||||
Output: [5,-99]
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- The number of the nodes in the given list is in the range `[2, 1000]`.
|
||||
- `1000 <= Node.val <= 1000`
|
||||
- The value of each node in the list is **unique**.
|
||||
- The `node` to be deleted is **in the list** and is **not a tail** node
|
||||
- The linked list will have at least two elements.
|
||||
- All of the nodes' values will be unique.
|
||||
- The given node will not be the tail and it will always be a valid node of the linked list.
|
||||
- Do not return anything from your function.
|
||||
|
||||
## 题目大意
|
||||
|
||||
@ -67,28 +38,3 @@ Output: [5,-99]
|
||||
## 解题思路
|
||||
|
||||
其实就是把后面的结点都覆盖上来即可。或者直接当前结点的值等于下一个结点,Next 指针指向下下个结点,这样做也可以,只不过中间有一个结点不被释放,内存消耗多一些。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
// ListNode define
|
||||
type ListNode = structures.ListNode
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
func deleteNode(node *ListNode) {
|
||||
node.Val = node.Next.Val
|
||||
node.Next = node.Next.Next
|
||||
}
|
||||
```
|
@ -24,17 +24,44 @@ func isAnagram(s string, t string) bool {
|
||||
|
||||
// 解法二
|
||||
func isAnagram1(s string, t string) bool {
|
||||
hash := map[rune]int{}
|
||||
for _, value := range s {
|
||||
hash[value]++
|
||||
if s == "" && t == "" {
|
||||
return true
|
||||
}
|
||||
for _, value := range t {
|
||||
hash[value]--
|
||||
if s == "" || t == "" {
|
||||
return false
|
||||
}
|
||||
for _, value := range hash {
|
||||
if value != 0 {
|
||||
sBytes := []byte(s)
|
||||
tBytes := []byte(t)
|
||||
if len(sBytes) != len(tBytes) {
|
||||
return false
|
||||
}
|
||||
quickSortByte(sBytes, 0, len(sBytes)-1)
|
||||
quickSortByte(tBytes, 0, len(tBytes)-1)
|
||||
|
||||
for i := 0; i < len(sBytes); i++ {
|
||||
if sBytes[i] != tBytes[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func partitionByte(a []byte, lo, hi int) int {
|
||||
pivot := a[hi]
|
||||
i := lo - 1
|
||||
for j := lo; j < hi; j++ {
|
||||
if a[j] > pivot {
|
||||
i++
|
||||
a[j], a[i] = a[i], a[j]
|
||||
}
|
||||
}
|
||||
a[i+1], a[hi] = a[hi], a[i+1]
|
||||
return i + 1
|
||||
}
|
||||
func quickSortByte(a []byte, lo, hi int) {
|
||||
if lo >= hi {
|
||||
return
|
||||
}
|
||||
p := partitionByte(a, lo, hi)
|
||||
quickSortByte(a, lo, p-1)
|
||||
quickSortByte(a, p+1, hi)
|
||||
}
|
||||
|
@ -45,21 +45,6 @@ func Test_Problem242(t *testing.T) {
|
||||
para242{"rat", "car"},
|
||||
ans242{false},
|
||||
},
|
||||
|
||||
{
|
||||
para242{"a", "ab"},
|
||||
ans242{false},
|
||||
},
|
||||
|
||||
{
|
||||
para242{"ab", "a"},
|
||||
ans242{false},
|
||||
},
|
||||
|
||||
{
|
||||
para242{"aa", "bb"},
|
||||
ans242{false},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 242------------------------\n")
|
||||
|
@ -2,7 +2,9 @@ package leetcode
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
|
@ -31,12 +31,12 @@ func Test_Problem297(t *testing.T) {
|
||||
ans297{[]int{}},
|
||||
},
|
||||
{
|
||||
para297{[]int{1, 2, 3, -1, -1, 4, 5}},
|
||||
ans297{[]int{1, 2, 3, -1, -1, 4, 5}},
|
||||
para297{[]int{1,2,3,-1,-1,4,5}},
|
||||
ans297{[]int{1,2,3,-1,-1,4,5}},
|
||||
},
|
||||
{
|
||||
para297{[]int{1, 2}},
|
||||
ans297{[]int{1, 2}},
|
||||
para297{[]int{1,2}},
|
||||
ans297{[]int{1,2}},
|
||||
},
|
||||
}
|
||||
|
||||
|
@ -1,31 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import "strconv"
|
||||
|
||||
func getHint(secret string, guess string) string {
|
||||
cntA, cntB := 0, 0
|
||||
mpS := make(map[byte]int)
|
||||
var strG []byte
|
||||
n := len(secret)
|
||||
var ans string
|
||||
for i := 0; i < n; i++ {
|
||||
if secret[i] == guess[i] {
|
||||
cntA++
|
||||
} else {
|
||||
mpS[secret[i]] += 1
|
||||
strG = append(strG, guess[i])
|
||||
}
|
||||
}
|
||||
for _, v := range strG {
|
||||
if _, ok := mpS[v]; ok {
|
||||
if mpS[v] > 1 {
|
||||
mpS[v] -= 1
|
||||
} else {
|
||||
delete(mpS, v)
|
||||
}
|
||||
cntB++
|
||||
}
|
||||
}
|
||||
ans += strconv.Itoa(cntA) + "A" + strconv.Itoa(cntB) + "B"
|
||||
return ans
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question299 struct {
|
||||
para299
|
||||
ans299
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para299 struct {
|
||||
secret string
|
||||
guess string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans299 struct {
|
||||
ans string
|
||||
}
|
||||
|
||||
func Test_Problem299(t *testing.T) {
|
||||
|
||||
qs := []question299{
|
||||
|
||||
{
|
||||
para299{"1807", "7810"},
|
||||
ans299{"1A3B"},
|
||||
},
|
||||
|
||||
{
|
||||
para299{"1123", "0111"},
|
||||
ans299{"1A1B"},
|
||||
},
|
||||
|
||||
{
|
||||
para299{"1", "0"},
|
||||
ans299{"0A0B"},
|
||||
},
|
||||
|
||||
{
|
||||
para299{"1", "1"},
|
||||
ans299{"1A0B"},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 299------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans299, q.para299
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, getHint(p.secret, p.guess))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
# [299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You are playing the Bulls and Cows game with your friend.
|
||||
|
||||
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
|
||||
|
||||
The number of "bulls", which are digits in the guess that are in the correct position.
|
||||
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
|
||||
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
|
||||
|
||||
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input: secret = "1807", guess = "7810"
|
||||
Output: "1A3B"
|
||||
Explanation: Bulls are connected with a '|' and cows are underlined:
|
||||
"1807"
|
||||
|
|
||||
"7810"
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: secret = "1123", guess = "0111"
|
||||
Output: "1A1B"
|
||||
Explanation: Bulls are connected with a '|' and cows are underlined:
|
||||
"1123" "1123"
|
||||
| or |
|
||||
"0111" "0111"
|
||||
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
|
||||
```
|
||||
|
||||
**Example 3:**
|
||||
|
||||
```
|
||||
Input: secret = "1", guess = "0"
|
||||
Output: "0A0B"
|
||||
```
|
||||
|
||||
**Example 4:**
|
||||
|
||||
```
|
||||
Input: secret = "1", guess = "1"
|
||||
Output: "1A0B"
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- 1 <= secret.length, guess.length <= 1000
|
||||
- secret.length == guess.length
|
||||
- secret and guess consist of digits only.
|
||||
|
||||
## 题目大意
|
||||
|
||||
你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下:
|
||||
|
||||
写出一个秘密数字,并请朋友猜这个数字是多少。朋友每猜测一次,你就会给他一个包含下述信息的提示:
|
||||
|
||||
猜测数字中有多少位属于数字和确切位置都猜对了(称为 "Bulls", 公牛),
|
||||
有多少位属于数字猜对了但是位置不对(称为 "Cows", 奶牛)。也就是说,这次猜测中有多少位非公牛数字可以通过重新排列转换成公牛数字。
|
||||
给你一个秘密数字secret 和朋友猜测的数字guess ,请你返回对朋友这次猜测的提示。
|
||||
|
||||
提示的格式为 "xAyB" ,x 是公牛个数, y 是奶牛个数,A 表示公牛,B表示奶牛。
|
||||
|
||||
请注意秘密数字和朋友猜测的数字都可能含有重复数字。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 计算下标一致并且对应下标的元素一致的个数,即 x
|
||||
- secret 和 guess 分别去除 x 个公牛的元素,剩下 secret 和 guess 求共同的元素个数就是 y
|
||||
- 把 x, y 转换成字符串,分别与 "A" 和 "B" 进行拼接返回结果
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
import "strconv"
|
||||
|
||||
func getHint(secret string, guess string) string {
|
||||
cntA, cntB := 0, 0
|
||||
mpS := make(map[byte]int)
|
||||
var strG []byte
|
||||
n := len(secret)
|
||||
var ans string
|
||||
for i := 0; i < n; i++ {
|
||||
if secret[i] == guess[i] {
|
||||
cntA++
|
||||
} else {
|
||||
mpS[secret[i]] += 1
|
||||
strG = append(strG, guess[i])
|
||||
}
|
||||
}
|
||||
for _, v := range strG {
|
||||
if _, ok := mpS[v]; ok {
|
||||
if mpS[v] > 1 {
|
||||
mpS[v] -= 1
|
||||
} else {
|
||||
delete(mpS, v)
|
||||
}
|
||||
cntB++
|
||||
}
|
||||
}
|
||||
ans += strconv.Itoa(cntA) + "A" + strconv.Itoa(cntB) + "B"
|
||||
return ans
|
||||
}
|
||||
```
|
@ -1,69 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
var (
|
||||
res []string
|
||||
mp map[string]int
|
||||
n int
|
||||
length int
|
||||
maxScore int
|
||||
str string
|
||||
)
|
||||
|
||||
func removeInvalidParentheses(s string) []string {
|
||||
lmoves, rmoves, lcnt, rcnt := 0, 0, 0, 0
|
||||
for _, v := range s {
|
||||
if v == '(' {
|
||||
lmoves++
|
||||
lcnt++
|
||||
} else if v == ')' {
|
||||
if lmoves != 0 {
|
||||
lmoves--
|
||||
} else {
|
||||
rmoves++
|
||||
}
|
||||
rcnt++
|
||||
}
|
||||
}
|
||||
n = len(s)
|
||||
length = n - lmoves - rmoves
|
||||
res = []string{}
|
||||
mp = make(map[string]int)
|
||||
maxScore = min(lcnt, rcnt)
|
||||
str = s
|
||||
backtrace(0, "", lmoves, rmoves, 0)
|
||||
return res
|
||||
}
|
||||
|
||||
func backtrace(i int, cur string, lmoves int, rmoves int, score int) {
|
||||
if lmoves < 0 || rmoves < 0 || score < 0 || score > maxScore {
|
||||
return
|
||||
}
|
||||
if lmoves == 0 && rmoves == 0 {
|
||||
if len(cur) == length {
|
||||
if _, ok := mp[cur]; !ok {
|
||||
res = append(res, cur)
|
||||
mp[cur] = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
if i == n {
|
||||
return
|
||||
}
|
||||
if str[i] == '(' {
|
||||
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
|
||||
backtrace(i+1, cur, lmoves-1, rmoves, score)
|
||||
} else if str[i] == ')' {
|
||||
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
|
||||
backtrace(i+1, cur, lmoves, rmoves-1, score)
|
||||
} else {
|
||||
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question301 struct {
|
||||
para301
|
||||
ans301
|
||||
}
|
||||
|
||||
// s 是参数
|
||||
type para301 struct {
|
||||
s string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans301 struct {
|
||||
ans []string
|
||||
}
|
||||
|
||||
func Test_Problem301(t *testing.T) {
|
||||
|
||||
qs := []question301{
|
||||
|
||||
{
|
||||
para301{"()())()"},
|
||||
ans301{[]string{"(())()", "()()()"}},
|
||||
},
|
||||
|
||||
{
|
||||
para301{"(a)())()"},
|
||||
ans301{[]string{"(a())()", "(a)()()"}},
|
||||
},
|
||||
|
||||
{
|
||||
para301{")("},
|
||||
ans301{[]string{""}},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 301------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans301, q.para301
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, removeInvalidParentheses(p.s))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,131 +0,0 @@
|
||||
# [301. Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
|
||||
|
||||
Return all the possible results. You may return the answer in any order.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
Input: s = "()())()"
|
||||
Output: ["(())()","()()()"]
|
||||
|
||||
**Example 2:**
|
||||
|
||||
Input: s = "(a)())()"
|
||||
Output: ["(a())()","(a)()()"]
|
||||
|
||||
**Example 3:**
|
||||
|
||||
Input: s = ")("
|
||||
Output: [""]
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- 1 <= s.length <= 25
|
||||
- s consists of lowercase English letters and parentheses '(' and ')'.
|
||||
- There will be at most 20 parentheses in s.
|
||||
|
||||
## 题目大意
|
||||
|
||||
给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。
|
||||
|
||||
返回所有可能的结果。答案可以按 任意顺序 返回。
|
||||
|
||||
说明:
|
||||
|
||||
- 1 <= s.length <= 25
|
||||
- s 由小写英文字母以及括号 '(' 和 ')' 组成
|
||||
- s 中至多含 20 个括号
|
||||
|
||||
|
||||
## 解题思路
|
||||
|
||||
回溯和剪枝
|
||||
- 计算最大得分数maxScore,合法字符串的长度length,左括号和右括号的移除次数lmoves,rmoves
|
||||
- 加一个左括号的得分加1;加一个右括号的得分减1
|
||||
- 对于一个合法的字符串,左括号等于右括号,得分最终为0;
|
||||
- 搜索过程中出现以下任何一种情况都直接返回
|
||||
- 得分值为负数
|
||||
- 得分大于最大得分数
|
||||
- 得分小于0
|
||||
- lmoves小于0
|
||||
- rmoves小于0
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
var (
|
||||
res []string
|
||||
mp map[string]int
|
||||
n int
|
||||
length int
|
||||
maxScore int
|
||||
str string
|
||||
)
|
||||
|
||||
func removeInvalidParentheses(s string) []string {
|
||||
lmoves, rmoves, lcnt, rcnt := 0, 0, 0, 0
|
||||
for _, v := range s {
|
||||
if v == '(' {
|
||||
lmoves++
|
||||
lcnt++
|
||||
} else if v == ')' {
|
||||
if lmoves != 0 {
|
||||
lmoves--
|
||||
} else {
|
||||
rmoves++
|
||||
}
|
||||
rcnt++
|
||||
}
|
||||
}
|
||||
n = len(s)
|
||||
length = n - lmoves - rmoves
|
||||
res = []string{}
|
||||
mp = make(map[string]int)
|
||||
maxScore = min(lcnt, rcnt)
|
||||
str = s
|
||||
backtrace(0, "", lmoves, rmoves, 0)
|
||||
return res
|
||||
}
|
||||
|
||||
func backtrace(i int, cur string, lmoves int, rmoves int, score int) {
|
||||
if lmoves < 0 || rmoves < 0 || score < 0 || score > maxScore {
|
||||
return
|
||||
}
|
||||
if lmoves == 0 && rmoves == 0 {
|
||||
if len(cur) == length {
|
||||
if _, ok := mp[cur]; !ok {
|
||||
res = append(res, cur)
|
||||
mp[cur] = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
if i == n {
|
||||
return
|
||||
}
|
||||
if str[i] == '(' {
|
||||
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
|
||||
backtrace(i+1, cur, lmoves-1, rmoves, score)
|
||||
} else if str[i] == ')' {
|
||||
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
|
||||
backtrace(i+1, cur, lmoves, rmoves-1, score)
|
||||
} else {
|
||||
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
```
|
@ -35,7 +35,7 @@ func max(a int, b int) int {
|
||||
return b
|
||||
}
|
||||
|
||||
// Propagate for rest of the string
|
||||
//Propagate for rest of the string
|
||||
func recursiveCheck(num string, x1 int, x2 int, left int) bool {
|
||||
if left == len(num) {
|
||||
return true
|
||||
|
@ -1,7 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import "math"
|
||||
|
||||
func bulbSwitch(n int) int {
|
||||
return int(math.Sqrt(float64(n)))
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question319 struct {
|
||||
para319
|
||||
ans319
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para319 struct {
|
||||
n int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans319 struct {
|
||||
ans int
|
||||
}
|
||||
|
||||
func Test_Problem319(t *testing.T) {
|
||||
|
||||
qs := []question319{
|
||||
|
||||
{
|
||||
para319{3},
|
||||
ans319{1},
|
||||
},
|
||||
|
||||
{
|
||||
para319{0},
|
||||
ans319{0},
|
||||
},
|
||||
|
||||
{
|
||||
para319{1},
|
||||
ans319{1},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 319------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans319, q.para319
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, bulbSwitch(p.n))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
# [319. Bulb Switcher](https://leetcode.com/problems/bulb-switcher/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
|
||||
|
||||
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
|
||||
|
||||
Return the number of bulbs that are on after n rounds.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
Input: n = 3
|
||||
Output: 1
|
||||
Explanation: At first, the three bulbs are [off, off, off].
|
||||
After the first round, the three bulbs are [on, on, on].
|
||||
After the second round, the three bulbs are [on, off, on].
|
||||
After the third round, the three bulbs are [on, off, off].
|
||||
So you should return 1 because there is only one bulb is on.
|
||||
|
||||
**Example 2:**
|
||||
|
||||
Input: n = 0
|
||||
Output: 0
|
||||
|
||||
**Example 3:**
|
||||
|
||||
Input: n = 1
|
||||
Output: 1
|
||||
|
||||
## 题目大意
|
||||
|
||||
初始时有 n 个灯泡处于关闭状态。第一轮,你将会打开所有灯泡。接下来的第二轮,你将会每两个灯泡关闭一个。
|
||||
|
||||
第三轮,你每三个灯泡就切换一个灯泡的开关(即,打开变关闭,关闭变打开)。第 i 轮,你每 i 个灯泡就切换一个灯泡的开关。直到第 n 轮,你只需要切换最后一个灯泡的开关。
|
||||
|
||||
找出并返回 n 轮后有多少个亮着的灯泡。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 计算 1 到 n 中有奇数个约数的个数
|
||||
- 1 到 n 中的某个数 x 有奇数个约数,也即 x 是完全平方数
|
||||
- 计算 1 到 n 中完全平方数的个数 sqrt(n)
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
import "math"
|
||||
|
||||
func bulbSwitch(n int) int {
|
||||
return int(math.Sqrt(float64(n)))
|
||||
}
|
||||
|
||||
```
|
@ -31,4 +31,4 @@ Note:
|
||||
|
||||
## 解题思路
|
||||
|
||||
这道题思路也是一样的,分别把奇数节点和偶数节点都放在 2 个链表中,最后首尾拼接就是答案。
|
||||
这道题思路也是一样的,分别把奇数和偶数都放在 2 个链表中,最后首尾拼接就是答案。
|
@ -1,49 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import "sort"
|
||||
|
||||
type SummaryRanges struct {
|
||||
nums []int
|
||||
mp map[int]int
|
||||
}
|
||||
|
||||
func Constructor() SummaryRanges {
|
||||
return SummaryRanges{
|
||||
nums: []int{},
|
||||
mp: map[int]int{},
|
||||
}
|
||||
}
|
||||
|
||||
func (this *SummaryRanges) AddNum(val int) {
|
||||
if _, ok := this.mp[val]; !ok {
|
||||
this.mp[val] = 1
|
||||
this.nums = append(this.nums, val)
|
||||
}
|
||||
sort.Ints(this.nums)
|
||||
}
|
||||
|
||||
func (this *SummaryRanges) GetIntervals() [][]int {
|
||||
n := len(this.nums)
|
||||
var ans [][]int
|
||||
if n == 0 {
|
||||
return ans
|
||||
}
|
||||
if n == 1 {
|
||||
ans = append(ans, []int{this.nums[0], this.nums[0]})
|
||||
return ans
|
||||
}
|
||||
start, end := this.nums[0], this.nums[0]
|
||||
ans = append(ans, []int{start, end})
|
||||
index := 0
|
||||
for i := 1; i < n; i++ {
|
||||
if this.nums[i] == end+1 {
|
||||
end = this.nums[i]
|
||||
ans[index][1] = end
|
||||
} else {
|
||||
start, end = this.nums[i], this.nums[i]
|
||||
ans = append(ans, []int{start, end})
|
||||
index++
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question352 struct {
|
||||
para352
|
||||
ans352
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para352 struct {
|
||||
para string
|
||||
num int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans352 struct {
|
||||
ans [][]int
|
||||
}
|
||||
|
||||
func Test_Problem352(t *testing.T) {
|
||||
|
||||
qs := []question352{
|
||||
|
||||
{
|
||||
para352{"addNum", 1},
|
||||
ans352{[][]int{{1, 1}}},
|
||||
},
|
||||
|
||||
{
|
||||
para352{"addNum", 3},
|
||||
ans352{[][]int{{1, 1}, {3, 3}}},
|
||||
},
|
||||
|
||||
{
|
||||
para352{"addNum", 7},
|
||||
ans352{[][]int{{1, 1}, {3, 3}, {7, 7}}},
|
||||
},
|
||||
|
||||
{
|
||||
para352{"addNum", 2},
|
||||
ans352{[][]int{{1, 3}, {7, 7}}},
|
||||
},
|
||||
|
||||
{
|
||||
para352{"addNum", 6},
|
||||
ans352{[][]int{{1, 3}, {6, 7}}},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 352------------------------\n")
|
||||
|
||||
obj := Constructor()
|
||||
for _, q := range qs {
|
||||
_, p := q.ans352, q.para352
|
||||
obj.AddNum(p.num)
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, obj.GetIntervals())
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,108 +0,0 @@
|
||||
# [352. Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.
|
||||
|
||||
Implement the SummaryRanges class:
|
||||
|
||||
- SummaryRanges() Initializes the object with an empty stream.
|
||||
- void addNum(int val) Adds the integer val to the stream.
|
||||
- int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi].
|
||||
|
||||
**Example 1:**
|
||||
|
||||
Input
|
||||
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
|
||||
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
|
||||
Output
|
||||
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
|
||||
|
||||
Explanation
|
||||
SummaryRanges summaryRanges = new SummaryRanges();
|
||||
summaryRanges.addNum(1); // arr = [1]
|
||||
summaryRanges.getIntervals(); // return [[1, 1]]
|
||||
summaryRanges.addNum(3); // arr = [1, 3]
|
||||
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
|
||||
summaryRanges.addNum(7); // arr = [1, 3, 7]
|
||||
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
|
||||
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
|
||||
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
|
||||
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
|
||||
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
|
||||
|
||||
**Constraints**
|
||||
|
||||
- 0 <= val <= 10000
|
||||
- At most 3 * 10000 calls will be made to addNum and getIntervals.
|
||||
|
||||
## 题目大意
|
||||
|
||||
给你一个由非负整数a1, a2, ..., an 组成的数据流输入,请你将到目前为止看到的数字总结为不相交的区间列表。
|
||||
|
||||
实现 SummaryRanges 类:
|
||||
|
||||
- SummaryRanges() 使用一个空数据流初始化对象。
|
||||
- void addNum(int val) 向数据流中加入整数 val 。
|
||||
- int[][] getIntervals() 以不相交区间[starti, endi] 的列表形式返回对数据流中整数的总结
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 使用字典过滤掉重复的数字
|
||||
- 把过滤后的数字放到nums中,并进行排序
|
||||
- 使用nums构建不重复的区间
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
import "sort"
|
||||
|
||||
type SummaryRanges struct {
|
||||
nums []int
|
||||
mp map[int]int
|
||||
}
|
||||
|
||||
func Constructor() SummaryRanges {
|
||||
return SummaryRanges{
|
||||
nums: []int{},
|
||||
mp : map[int]int{},
|
||||
}
|
||||
}
|
||||
|
||||
func (this *SummaryRanges) AddNum(val int) {
|
||||
if _, ok := this.mp[val]; !ok {
|
||||
this.mp[val] = 1
|
||||
this.nums = append(this.nums, val)
|
||||
}
|
||||
sort.Ints(this.nums)
|
||||
}
|
||||
|
||||
func (this *SummaryRanges) GetIntervals() [][]int {
|
||||
n := len(this.nums)
|
||||
var ans [][]int
|
||||
if n == 0 {
|
||||
return ans
|
||||
}
|
||||
if n == 1 {
|
||||
ans = append(ans, []int{this.nums[0], this.nums[0]})
|
||||
return ans
|
||||
}
|
||||
start, end := this.nums[0], this.nums[0]
|
||||
ans = append(ans, []int{start, end})
|
||||
index := 0
|
||||
for i := 1; i < n; i++ {
|
||||
if this.nums[i] == end + 1 {
|
||||
end = this.nums[i]
|
||||
ans[index][1] = end
|
||||
} else {
|
||||
start, end = this.nums[i], this.nums[i]
|
||||
ans = append(ans, []int{start, end})
|
||||
index++
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
```
|
@ -8,7 +8,6 @@ package leetcode
|
||||
// 模运算性质五:ab % p = ((a % p) * ( b % p)) % p, 其中 ab 是一个数字,如:2874,98374 等等
|
||||
// 举个例子
|
||||
// 12345^678 % 1337 = (12345^670 * 12345^8) % 1337
|
||||
//
|
||||
// = ((12345^670 % 1337) * (12345^8 % 1337)) % 1337 ---> 利用性质 三
|
||||
// = (((12345^67)^10 % 1337) * (12345^8 % 1337)) % 1337 ---> 乘方性质
|
||||
// = ((12345^67 % 1337)^10) % 1337 * (12345^8 % 1337)) % 1337 ---> 利用性质 四
|
||||
|
@ -1,48 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
// ListNode define
|
||||
type ListNode = structures.ListNode
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
type Solution struct {
|
||||
head *ListNode
|
||||
}
|
||||
|
||||
/*
|
||||
- @param head The linked list's head.
|
||||
Note that the head is guaranteed to be not null, so it contains at least one node.
|
||||
*/
|
||||
func Constructor(head *ListNode) Solution {
|
||||
return Solution{head: head}
|
||||
}
|
||||
|
||||
/** Returns a random node's value. */
|
||||
func (this *Solution) GetRandom() int {
|
||||
scope, selectPoint, curr := 1, 0, this.head
|
||||
for curr != nil {
|
||||
if rand.Float64() < 1.0/float64(scope) {
|
||||
selectPoint = curr.Val
|
||||
}
|
||||
scope += 1
|
||||
curr = curr.Next
|
||||
}
|
||||
return selectPoint
|
||||
}
|
||||
|
||||
/**
|
||||
* Your Solution object will be instantiated and called as such:
|
||||
* obj := Constructor(head);
|
||||
* param_1 := obj.GetRandom();
|
||||
*/
|
@ -1,28 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
func Test_Problem382(t *testing.T) {
|
||||
header := structures.Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0})
|
||||
obj := Constructor(header)
|
||||
fmt.Printf("obj = %v\n", structures.List2Ints(header))
|
||||
param1 := obj.GetRandom()
|
||||
fmt.Printf("param_1 = %v\n", param1)
|
||||
param1 = obj.GetRandom()
|
||||
fmt.Printf("param_1 = %v\n", param1)
|
||||
param1 = obj.GetRandom()
|
||||
fmt.Printf("param_1 = %v\n", param1)
|
||||
param1 = obj.GetRandom()
|
||||
fmt.Printf("param_1 = %v\n", param1)
|
||||
param1 = obj.GetRandom()
|
||||
fmt.Printf("param_1 = %v\n", param1)
|
||||
param1 = obj.GetRandom()
|
||||
fmt.Printf("param_1 = %v\n", param1)
|
||||
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,105 +0,0 @@
|
||||
# [382. Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
|
||||
|
||||
Implement the `Solution` class:
|
||||
|
||||
- `Solution(ListNode head)` Initializes the object with the integer array nums.
|
||||
- `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen.
|
||||
|
||||
**Example 1:**
|
||||
|
||||

|
||||
|
||||
```
|
||||
Input
|
||||
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
|
||||
[[[1, 2, 3]], [], [], [], [], []]
|
||||
Output
|
||||
[null, 1, 3, 2, 2, 3]
|
||||
|
||||
Explanation
|
||||
Solution solution = new Solution([1, 2, 3]);
|
||||
solution.getRandom(); // return 1
|
||||
solution.getRandom(); // return 3
|
||||
solution.getRandom(); // return 2
|
||||
solution.getRandom(); // return 2
|
||||
solution.getRandom(); // return 3
|
||||
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- The number of nodes in the linked list will be in the range `[1, 104]`.
|
||||
- `-10^4 <= Node.val <= 10^4`
|
||||
- At most `10^4` calls will be made to `getRandom`.
|
||||
|
||||
**Follow up:**
|
||||
|
||||
- What if the linked list is extremely large and its length is unknown to you?
|
||||
- Could you solve this efficiently without using extra space?
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
|
||||
|
||||
进阶: 如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
|
||||
|
||||
## 解题思路
|
||||
|
||||
- rand.Float64() 可以返回 [0.0,1.0) 之间的随机数。利用这个函数完成我们的随机化取节点的过程。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
// ListNode define
|
||||
type ListNode = structures.ListNode
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
type Solution struct {
|
||||
head *ListNode
|
||||
}
|
||||
|
||||
/** @param head The linked list's head.
|
||||
Note that the head is guaranteed to be not null, so it contains at least one node. */
|
||||
func Constructor(head *ListNode) Solution {
|
||||
return Solution{head: head}
|
||||
}
|
||||
|
||||
/** Returns a random node's value. */
|
||||
func (this *Solution) GetRandom() int {
|
||||
scope, selectPoint, curr := 1, 0, this.head
|
||||
for curr != nil {
|
||||
if rand.Float64() < 1.0/float64(scope) {
|
||||
selectPoint = curr.Val
|
||||
}
|
||||
scope += 1
|
||||
curr = curr.Next
|
||||
}
|
||||
return selectPoint
|
||||
}
|
||||
|
||||
/**
|
||||
* Your Solution object will be instantiated and called as such:
|
||||
* obj := Constructor(head);
|
||||
* param_1 := obj.GetRandom();
|
||||
*/
|
||||
```
|
@ -1,18 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func canConstruct(ransomNote string, magazine string) bool {
|
||||
if len(ransomNote) > len(magazine) {
|
||||
return false
|
||||
}
|
||||
var cnt [26]int
|
||||
for _, v := range magazine {
|
||||
cnt[v-'a']++
|
||||
}
|
||||
for _, v := range ransomNote {
|
||||
cnt[v-'a']--
|
||||
if cnt[v-'a'] < 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question383 struct {
|
||||
para383
|
||||
ans383
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para383 struct {
|
||||
ransomNote string
|
||||
magazine string
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans383 struct {
|
||||
ans bool
|
||||
}
|
||||
|
||||
func Test_Problem383(t *testing.T) {
|
||||
|
||||
qs := []question383{
|
||||
|
||||
{
|
||||
para383{"a", "b"},
|
||||
ans383{false},
|
||||
},
|
||||
|
||||
{
|
||||
para383{"aa", "ab"},
|
||||
ans383{false},
|
||||
},
|
||||
|
||||
{
|
||||
para383{"aa", "aab"},
|
||||
ans383{true},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 383------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans383, q.para383
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, canConstruct(p.ransomNote, p.magazine))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,64 +0,0 @@
|
||||
# [383. Ransom Note](https://leetcode.com/problems/ransom-note/)
|
||||
|
||||
## 题目
|
||||
|
||||
Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
|
||||
|
||||
Each letter in magazine can only be used once in ransomNote.
|
||||
|
||||
**Example 1**:
|
||||
|
||||
Input: ransomNote = "a", magazine = "b"
|
||||
Output: false
|
||||
|
||||
**Example 2**:
|
||||
|
||||
Input: ransomNote = "aa", magazine = "ab"
|
||||
Output: false
|
||||
|
||||
**Example 3**:
|
||||
|
||||
Input: ransomNote = "aa", magazine = "aab"
|
||||
Output: true
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- 1 <= ransomNote.length, magazine.length <= 100000
|
||||
- ransomNote and magazine consist of lowercase English letters.
|
||||
|
||||
## 题目大意
|
||||
|
||||
为了不在赎金信中暴露字迹,从杂志上搜索各个需要的字母,组成单词来表达意思。
|
||||
|
||||
给你一个赎金信 (ransomNote) 字符串和一个杂志(magazine)字符串,判断 ransomNote 能不能由 magazines 里面的字符构成。
|
||||
|
||||
如果可以构成,返回 true ;否则返回 false 。
|
||||
|
||||
magazine 中的每个字符只能在 ransomNote 中使用一次。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- ransomNote 和 magazine 都是由小写字母组成,所以用数组进行简单的字符统计
|
||||
|
||||
## 代码
|
||||
|
||||
````go
|
||||
package leetcode
|
||||
|
||||
func canConstruct(ransomNote string, magazine string) bool {
|
||||
if len(ransomNote) > len(magazine) {
|
||||
return false
|
||||
}
|
||||
var cnt [26]int
|
||||
for _, v := range magazine {
|
||||
cnt[v-'a']++
|
||||
}
|
||||
for _, v := range ransomNote {
|
||||
cnt[v-'a']--
|
||||
if cnt[v-'a'] < 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
````
|
@ -1,28 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import "math/rand"
|
||||
|
||||
type Solution struct {
|
||||
nums []int
|
||||
}
|
||||
|
||||
func Constructor(nums []int) Solution {
|
||||
return Solution{
|
||||
nums: nums,
|
||||
}
|
||||
}
|
||||
|
||||
/** Resets the array to its original configuration and return it. */
|
||||
func (this *Solution) Reset() []int {
|
||||
return this.nums
|
||||
}
|
||||
|
||||
/** Returns a random shuffling of the array. */
|
||||
func (this *Solution) Shuffle() []int {
|
||||
arr := make([]int, len(this.nums))
|
||||
copy(arr, this.nums)
|
||||
rand.Shuffle(len(arr), func(i, j int) {
|
||||
arr[i], arr[j] = arr[j], arr[i]
|
||||
})
|
||||
return arr
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question384 struct {
|
||||
para384
|
||||
ans384
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para384 struct {
|
||||
ops []string
|
||||
value [][]int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans384 struct {
|
||||
ans [][]int
|
||||
}
|
||||
|
||||
func Test_Problem384(t *testing.T) {
|
||||
|
||||
qs := []question384{
|
||||
|
||||
{
|
||||
para384{ops: []string{"Solution", "shuffle", "reset", "shuffle"}, value: [][]int{{1, 2, 3}, {}, {}, {}}},
|
||||
ans384{[][]int{nil, {3, 1, 2}, {1, 2, 3}, {1, 3, 2}}},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 384------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
sol := Constructor(nil)
|
||||
_, p := q.ans384, q.para384
|
||||
for _, op := range p.ops {
|
||||
if op == "Solution" {
|
||||
sol = Constructor(q.value[0])
|
||||
} else if op == "reset" {
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", op, sol.Reset())
|
||||
} else {
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", op, sol.Shuffle())
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
# [384.Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)
|
||||
|
||||
## 题目
|
||||
|
||||
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
|
||||
|
||||
Implement the Solution class:
|
||||
|
||||
- Solution(int[] nums) Initializes the object with the integer array nums.
|
||||
- int[] reset() Resets the array to its original configuration and returns it.
|
||||
- int[] shuffle() Returns a random shuffling of the array.
|
||||
|
||||
**Example 1**:
|
||||
|
||||
Input
|
||||
["Solution", "shuffle", "reset", "shuffle"]
|
||||
[[[1, 2, 3]], [], [], []]
|
||||
Output
|
||||
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
|
||||
|
||||
Explanation
|
||||
Solution solution = new Solution([1, 2, 3]);
|
||||
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
|
||||
// Any permutation of [1,2,3] must be equally likely to be returned.
|
||||
// Example: return [3, 1, 2]
|
||||
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
|
||||
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- 1 <= nums.length <= 200
|
||||
- -1000000 <= nums[i] <= 1000000
|
||||
- All the elements of nums are unique.
|
||||
- At most 5 * 10000 calls in total will be made to reset and shuffle.
|
||||
|
||||
## 题目大意
|
||||
|
||||
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
|
||||
|
||||
实现 Solution class:
|
||||
|
||||
- Solution(int[] nums) 使用整数数组 nums 初始化对象
|
||||
- int[] reset() 重设数组到它的初始状态并返回
|
||||
- int[] shuffle() 返回数组随机打乱后的结果
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 使用 rand.Shuffle 进行数组随机打乱
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
import "math/rand"
|
||||
|
||||
type Solution struct {
|
||||
nums []int
|
||||
}
|
||||
|
||||
func Constructor(nums []int) Solution {
|
||||
return Solution{
|
||||
nums: nums,
|
||||
}
|
||||
}
|
||||
|
||||
/** Resets the array to its original configuration and return it. */
|
||||
func (this *Solution) Reset() []int {
|
||||
return this.nums
|
||||
}
|
||||
|
||||
/** Returns a random shuffling of the array. */
|
||||
func (this *Solution) Shuffle() []int {
|
||||
arr := make([]int, len(this.nums))
|
||||
copy(arr, this.nums)
|
||||
rand.Shuffle(len(arr), func(i, j int) {
|
||||
arr[i], arr[j] = arr[j], arr[i]
|
||||
})
|
||||
return arr
|
||||
}
|
||||
```
|
@ -1,18 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func lastRemaining(n int) int {
|
||||
start, dir, step := 1, true, 1
|
||||
for n > 1 {
|
||||
if dir { // 正向
|
||||
start += step
|
||||
} else { // 反向
|
||||
if n%2 == 1 {
|
||||
start += step
|
||||
}
|
||||
}
|
||||
dir = !dir
|
||||
n >>= 1
|
||||
step <<= 1
|
||||
}
|
||||
return start
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question390 struct {
|
||||
para390
|
||||
ans390
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para390 struct {
|
||||
n int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans390 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
func Test_Problem390(t *testing.T) {
|
||||
|
||||
qs := []question390{
|
||||
|
||||
{
|
||||
para390{9},
|
||||
ans390{6},
|
||||
},
|
||||
|
||||
{
|
||||
para390{1},
|
||||
ans390{1},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 390------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans390, q.para390
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, lastRemaining(p.n))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
# [390. Elimination Game](https://leetcode.com/problems/elimination-game/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`:
|
||||
|
||||
- Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
|
||||
- Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.
|
||||
- Keep repeating the steps again, alternating left to right and right to left, until a single number remains.
|
||||
|
||||
Given the integer `n`, return *the last number that remains in* `arr`.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input: n = 9
|
||||
Output: 6
|
||||
Explanation:
|
||||
arr = [1, 2,3, 4,5, 6,7, 8,9]
|
||||
arr = [2,4, 6,8]
|
||||
arr = [2, 6]
|
||||
arr = [6]
|
||||
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```
|
||||
Input: n = 1
|
||||
Output: 1
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `1 <= n <= 109`
|
||||
|
||||
## 题目大意
|
||||
|
||||
列表 arr 由在范围 [1, n] 中的所有整数组成,并按严格递增排序。请你对 arr 应用下述算法:
|
||||
|
||||
- 从左到右,删除第一个数字,然后每隔一个数字删除一个,直到到达列表末尾。
|
||||
- 重复上面的步骤,但这次是从右到左。也就是,删除最右侧的数字,然后剩下的数字每隔一个删除一个。
|
||||
- 不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。
|
||||
|
||||
给你整数 n ,返回 arr 最后剩下的数字。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 模拟题。按照题意,第一轮从左往右删除数字,第二轮从右往左删除数字。题目要求最后剩下的数字,模拟过程中不需要真的删除元素。只需要标记起始元素,该轮步长和方向即可。最后总元素只剩下一个即为所求。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
func lastRemaining(n int) int {
|
||||
start, dir, step := 1, true, 1
|
||||
for n > 1 {
|
||||
if dir { // 正向
|
||||
start += step
|
||||
} else { // 反向
|
||||
if n%2 == 1 {
|
||||
start += step
|
||||
}
|
||||
}
|
||||
dir = !dir
|
||||
n >>= 1
|
||||
step <<= 1
|
||||
}
|
||||
return start
|
||||
}
|
||||
```
|
@ -1,53 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
type point struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
|
||||
func isRectangleCover(rectangles [][]int) bool {
|
||||
minX, minY, maxA, maxB := rectangles[0][0], rectangles[0][1], rectangles[0][2], rectangles[0][3]
|
||||
area := 0
|
||||
cnt := make(map[point]int)
|
||||
for _, v := range rectangles {
|
||||
x, y, a, b := v[0], v[1], v[2], v[3]
|
||||
area += (a - x) * (b - y)
|
||||
minX = min(minX, x)
|
||||
minY = min(minY, y)
|
||||
maxA = max(maxA, a)
|
||||
maxB = max(maxB, b)
|
||||
cnt[point{x, y}]++
|
||||
cnt[point{a, b}]++
|
||||
cnt[point{x, b}]++
|
||||
cnt[point{a, y}]++
|
||||
}
|
||||
if area != (maxA-minX)*(maxB-minY) ||
|
||||
cnt[point{minX, minY}] != 1 || cnt[point{maxA, maxB}] != 1 ||
|
||||
cnt[point{minX, maxB}] != 1 || cnt[point{maxA, minY}] != 1 {
|
||||
return false
|
||||
}
|
||||
delete(cnt, point{minX, minY})
|
||||
delete(cnt, point{maxA, maxB})
|
||||
delete(cnt, point{minX, maxB})
|
||||
delete(cnt, point{maxA, minY})
|
||||
for _, v := range cnt {
|
||||
if v != 2 && v != 4 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question391 struct {
|
||||
para391
|
||||
ans391
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para391 struct {
|
||||
rectangles [][]int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans391 struct {
|
||||
ans bool
|
||||
}
|
||||
|
||||
func Test_Problem391(t *testing.T) {
|
||||
|
||||
qs := []question391{
|
||||
|
||||
{
|
||||
para391{[][]int{{1, 1, 3, 3}, {3, 1, 4, 2}, {3, 2, 4, 4}, {1, 3, 2, 4}, {2, 3, 3, 4}}},
|
||||
ans391{true},
|
||||
},
|
||||
|
||||
{
|
||||
para391{[][]int{{1, 1, 2, 3}, {1, 3, 2, 4}, {3, 1, 4, 2}, {3, 2, 4, 4}}},
|
||||
ans391{false},
|
||||
},
|
||||
|
||||
{
|
||||
para391{[][]int{{1, 1, 3, 3}, {3, 1, 4, 2}, {1, 3, 2, 4}, {3, 2, 4, 4}}},
|
||||
ans391{false},
|
||||
},
|
||||
|
||||
{
|
||||
para391{[][]int{{1, 1, 3, 3}, {3, 1, 4, 2}, {1, 3, 2, 4}, {2, 2, 4, 4}}},
|
||||
ans391{false},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 391------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans391, q.para391
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, isRectangleCover(p.rectangles))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
# [391. Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/)
|
||||
|
||||
## 题目
|
||||
|
||||
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
|
||||
|
||||
Return true if all the rectangles together form an exact cover of a rectangular region.
|
||||
|
||||
**Example1:**
|
||||
|
||||

|
||||
|
||||
Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]
|
||||
Output: true
|
||||
Explanation: All 5 rectangles together form an exact cover of a rectangular region.
|
||||
|
||||
**Example2:**
|
||||
|
||||

|
||||
|
||||
Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]
|
||||
Output: false
|
||||
Explanation: Because there is a gap between the two rectangular regions.
|
||||
|
||||
**Example3:**
|
||||
|
||||

|
||||
|
||||
Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]
|
||||
Output: false
|
||||
Explanation: Because there is a gap in the top center.
|
||||
|
||||
**Example4:**
|
||||
|
||||

|
||||
|
||||
Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]
|
||||
Output: false
|
||||
Explanation: Because two of the rectangles overlap with each other.
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- 1 <= rectangles.length <= 2 * 10000
|
||||
- rectangles[i].length == 4
|
||||
- -100000 <= xi, yi, ai, bi <= 100000
|
||||
|
||||
## 题目大意
|
||||
|
||||
给你一个数组 rectangles ,其中 rectangles[i] = [xi, yi, ai, bi] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (xi, yi) ,右上顶点是 (ai, bi) 。
|
||||
|
||||
如果所有矩形一起精确覆盖了某个矩形区域,则返回 true ;否则,返回 false 。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 矩形区域的面积等于所有矩形的面积之和并且满足矩形区域四角的顶点只能出现一次,且其余顶点的出现次数只能是两次或四次则返回 true,否则返回 false
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
type point struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
|
||||
func isRectangleCover(rectangles [][]int) bool {
|
||||
minX, minY, maxA, maxB := rectangles[0][0], rectangles[0][1], rectangles[0][2], rectangles[0][3]
|
||||
area := 0
|
||||
cnt := make(map[point]int)
|
||||
for _, v := range rectangles {
|
||||
x, y, a, b := v[0], v[1], v[2], v[3]
|
||||
area += (a - x) * (b - y)
|
||||
minX = min(minX, x)
|
||||
minY = min(minY, y)
|
||||
maxA = max(maxA, a)
|
||||
maxB = max(maxB, b)
|
||||
cnt[point{x, y}]++
|
||||
cnt[point{a, b}]++
|
||||
cnt[point{x, b}]++
|
||||
cnt[point{a, y}]++
|
||||
}
|
||||
if area != (maxA - minX) * (maxB - minY) ||
|
||||
cnt[point{minX, minY}] != 1 || cnt[point{maxA, maxB}] != 1 ||
|
||||
cnt[point{minX, maxB}] != 1 || cnt[point{maxA, minY}] != 1 {
|
||||
return false
|
||||
}
|
||||
delete(cnt, point{minX, minY})
|
||||
delete(cnt, point{maxA, maxB})
|
||||
delete(cnt, point{minX, maxB})
|
||||
delete(cnt, point{maxA, minY})
|
||||
for _, v := range cnt {
|
||||
if v != 2 && v != 4 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
```
|
@ -1,18 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
func maxRotateFunction(nums []int) int {
|
||||
n := len(nums)
|
||||
var sum, f int
|
||||
for i, num := range nums {
|
||||
sum += num
|
||||
f += i * num // F(0)
|
||||
}
|
||||
ans := f
|
||||
for i := 1; i < n; i++ {
|
||||
f += sum - n*nums[n-i] // F(i) = F(i-1) + sum - n*nums[n-i]
|
||||
if f > ans {
|
||||
ans = f
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question396 struct {
|
||||
para396
|
||||
ans396
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para396 struct {
|
||||
one []int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans396 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
func Test_Problem396(t *testing.T) {
|
||||
|
||||
qs := []question396{
|
||||
{
|
||||
para396{[]int{4, 3, 2, 6}},
|
||||
ans396{26},
|
||||
},
|
||||
|
||||
{
|
||||
para396{[]int{100}},
|
||||
ans396{0},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 396------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans396, q.para396
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, maxRotateFunction(p.one))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
@ -1,110 +0,0 @@
|
||||
# [396. Rotate Function](https://leetcode.com/problems/rotate-function/)
|
||||
|
||||
## 题目
|
||||
|
||||
You are given an integer array `nums` of length `n`.
|
||||
|
||||
Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow:
|
||||
|
||||
- `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]`.
|
||||
|
||||
Return the maximum value of `F(0), F(1), ..., F(n-1)`.
|
||||
|
||||
The test cases are generated so that the answer fits in a **32-bit** integer.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```c
|
||||
Input: nums = [4,3,2,6]
|
||||
Output: 26
|
||||
Explanation:
|
||||
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
|
||||
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
|
||||
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
|
||||
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
|
||||
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```c
|
||||
Input: nums = [100]
|
||||
Output: 0
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `n == nums.length`
|
||||
- `1 <= n <= 105`
|
||||
- `-100 <= nums[i] <= 100`
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个长度为`n`的整数数组`nums`,设`arrk`是数组`nums`顺时针旋转`k`个位置后的数组。
|
||||
|
||||
定义`nums`的旋转函数`F`为:
|
||||
|
||||
- `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]`
|
||||
|
||||
返回`F(0), F(1), ..., F(n-1)`中的最大值。
|
||||
|
||||
## 解题思路
|
||||
|
||||
**抽象化观察:**
|
||||
|
||||
```c
|
||||
nums = [A0, A1, A2, A3]
|
||||
|
||||
sum = A0 + A1 + A2+ A3
|
||||
F(0) = 0*A0 +0*A0 + 1*A1 + 2*A2 + 3*A3
|
||||
|
||||
F(1) = 0*A3 + 1*A0 + 2*A1 + 3*A2
|
||||
= F(0) + (A0 + A1 + A2) - 3*A3
|
||||
= F(0) + (sum-A3) - 3*A3
|
||||
= F(0) + sum - 4*A3
|
||||
|
||||
F(2) = 0*A2 + 1*A3 + 2*A0 + 3*A1
|
||||
= F(1) + A3 + A0 + A1 - 3*A2
|
||||
= F(1) + sum - 4*A2
|
||||
|
||||
F(3) = 0*A1 + 1*A2 + 2*A3 + 3*A0
|
||||
= F(2) + A2 + A3 + A0 - 3*A1
|
||||
= F(2) + sum - 4*A1
|
||||
|
||||
// 记sum为nums数组中所有元素和
|
||||
// 可以猜测当0 ≤ i < n时存在公式:
|
||||
F(i) = F(i-1) + sum - n * A(n-i)
|
||||
```
|
||||
|
||||
**数学归纳法证明迭代公式:**
|
||||
|
||||
根据题目中给定的旋转函数公式可得已知条件:
|
||||
|
||||
- `F(0) = 0×nums[0] + 1×nums[1] + ... + (n−1)×nums[n−1]`;
|
||||
|
||||
- `F(1) = 1×nums[0] + 2×nums[1] + ... + 0×nums[n-1]`。
|
||||
|
||||
令数组`nums`中所有元素和为`sum`,用数学归纳法验证:当`1 ≤ k < n`时,`F(k) = F(k-1) + sum - n×nums[n-k]`成立。
|
||||
|
||||
**归纳奠基**:证明`k=1`时命题成立。
|
||||
|
||||
```c
|
||||
F(1) = 1×nums[0] + 2×nums[1] + ... + 0×nums[n-1]
|
||||
= F(0) + sum - n×nums[n-1]
|
||||
```
|
||||
|
||||
**归纳假设**:假设`F(k) = F(k-1) + sum - n×nums[n-k]`成立。
|
||||
|
||||
**归纳递推**:由归纳假设推出`F(k+1) = F(k) + sum - n×nums[n-(k+1)]`成立,则假设的递推公式成立。
|
||||
|
||||
```c
|
||||
F(k+1) = (k+1)×nums[0] + k×nums[1] + ... + 0×nums[n-1]
|
||||
= F(k) + sum - n×nums[n-(k+1)]
|
||||
```
|
||||
|
||||
因此可以得到递推公式:
|
||||
|
||||
- 当`n = 0`时,`F(0) = 0×nums[0] + 1×nums[1] + ... + (n−1)×nums[n−1]`
|
||||
- 当`1 ≤ k < n`时,`F(k) = F(k-1) + sum - n×nums[n-k]`成立。
|
||||
|
||||
循环遍历`0 ≤ k < n`,计算出不同的`F(k)`并不断更新最大值,就能求出`F(0), F(1), ..., F(n-1)`中的最大值。
|
@ -1,19 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import "math"
|
||||
|
||||
func findNthDigit(n int) int {
|
||||
if n <= 9 {
|
||||
return n
|
||||
}
|
||||
bits := 1
|
||||
for n > 9*int(math.Pow10(bits-1))*bits {
|
||||
n -= 9 * int(math.Pow10(bits-1)) * bits
|
||||
bits++
|
||||
}
|
||||
idx := n - 1
|
||||
start := int(math.Pow10(bits - 1))
|
||||
num := start + idx/bits
|
||||
digitIdx := idx % bits
|
||||
return num / int(math.Pow10(bits-digitIdx-1)) % 10
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question400 struct {
|
||||
para400
|
||||
ans400
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
type para400 struct {
|
||||
n int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
type ans400 struct {
|
||||
ans int
|
||||
}
|
||||
|
||||
func Test_Problem400(t *testing.T) {
|
||||
|
||||
qs := []question400{
|
||||
|
||||
{
|
||||
para400{3},
|
||||
ans400{3},
|
||||
},
|
||||
|
||||
{
|
||||
para400{11},
|
||||
ans400{0},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 400------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans400, q.para400
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p.n, findNthDigit(p.n))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user