├── .gitignore
├── problems
├── 0127.word-ladder
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0435.non-overlapping-intervals
│ ├── run.go
│ ├── run_test.go
│ └── README.md
├── 0009.palindrome-number
│ ├── README.md
│ ├── run_test.go
│ └── run.go
├── 0090.subsets-ii
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0146.lru-cache
│ ├── run_test.go
│ └── README.md
├── 0038.count-and-say
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0039.combination-sum
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0046.permute
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0213.house-robber-ii
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0283.move-zeroes
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0338.counting-bits
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0064.minimum-path-sum
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0092.reverse-linked-list-2
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0142.linked-list-cycle-ii
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0455.assign-cookies
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0832.flipping-an-image
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0888.fair-candy-swap
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0042.trapping-rain-water
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0234.palindrome-linked-list
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0480.sliding-window-median
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0617.merge-two-binary-trees
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0098.validate-binary-search-tree
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0354.russian-doll-envelopes
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0128.longest-consecutive-sequence
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0131.palindrome-partitioning
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0303.range-sum-query-immutable
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0304.range-sum-query-2d-immutable
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0387.first-unique-character-in-a-string
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0102.binary-tree-level-order-traversal
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0069.sqrt
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0424.longest-repeating-character-replacement
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0022.generate-parentheses
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0034.find-first-and-last-position-of-element-in-sorted-array
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0010.regular-expression-matching
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0029.divide-two-integers
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0012.integer-to-roman
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0028.implement-strstr
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0206.reverse-linked-list
│ ├── README.md
│ ├── run.go
│ └── run_test.go
├── 0006.zigzag-conversion
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0027.remove-element
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0013.roman-to-integer
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0077.combinations
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0007.reverse-integer
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0392.is-subsequence
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0026.remove-duplicates-from-sorted-array
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0020.valid-parentheses
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0088.merge-sorted-array
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0169.majority-element
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0101.symmetric-tree
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0470.implement-rand10-using-rand7
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0097.interleaving-string
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0215.kth-largest-element-in-an-array
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0043.multiply-strings
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0136.single-number
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0014.longest-common-prefix
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0032.longest-valid-parentheses
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0141.linked-list-cycle
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0011.container-with-most-water
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0240.search-a-2D-matrix2
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0542.01-matrix
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0050.pow
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0018.4sum
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0160.intersection-of-two-linked-lists
│ ├── run_test.go
│ └── run.go
├── 0015.3sum
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0017.letter-combinations-of-a-phone-number
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0004.median-of-two-sorted-arrays
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0023.merge-k-sorted-lists
│ ├── README.md
│ ├── run_test.go
│ └── run.go
├── 0083.remove-duplicates-from-sorted-list
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0053.maximum-subarray
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0148.sort-list
│ ├── run_test.go
│ └── README.md
├── 0016.3sum-closest
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0082.remove-duplicates-from-sorted-list2
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0024.swap-nodes-in-pairs
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0005.longest-palindromic-substring
│ ├── README.md
│ └── run_test.go
├── 0155.min-stack
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0003.longest-substring-without-repeating-characters
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0008.string-to-integer
│ ├── README.md
│ ├── run_test.go
│ └── run.go
├── 0058.length-of-last-word
│ ├── run.go
│ ├── run_test.go
│ └── README.md
├── 0236.lowest-common-ancestor-of-a-binary-tree
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0144.binary-tree-preorder-traversal
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0164.maximum-gap
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0021.merge-two-sorted-lists
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0033.search-in-rotated-sorted-array
│ ├── run.go
│ ├── run_test.go
│ └── README.md
├── 0226.invert-binary-tree
│ ├── run.go
│ ├── README.md
│ └── run_test.go
├── 0019.remove-nth-node-from-end-of-list
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0001.two-sum
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0100.same-tree
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0031.next-permutation
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0035.search-insert-position
│ ├── run.go
│ ├── run_test.go
│ └── README.md
├── 0112.path-sum
│ ├── README.md
│ ├── run.go
│ └── run_test.go
├── 0347.top-k-frequent-elements
│ ├── README.md
│ ├── run_test.go
│ └── run.go
├── 0002.add-two-numbers
│ ├── README.md
│ ├── run_test.go
│ └── run.go
├── 0094.binary-tree-inorder-traversal
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── 0235.lowest-common-ancestor-of-a-binary-search-tree
│ ├── run_test.go
│ ├── run.go
│ └── README.md
├── 0145.binary-tree-postorder-traversal
│ ├── README.md
│ ├── run_test.go
│ └── run.go
├── 0030.substrings-with-concatenation-of-all-words
│ ├── run_test.go
│ └── README.md
└── 0025.reverse-nodes-in-k-group
│ ├── run_test.go
│ ├── README.md
│ └── run.go
├── go.mod
├── create
├── run.exe
└── run.go
├── static
└── image
│ ├── 304.png
│ ├── binarytree.png
│ ├── 160_statement.png
│ ├── circularlinkedlist.png
│ └── binarysearchtree_improved.png
└── structure
├── lists.go
└── init.go
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 |
--------------------------------------------------------------------------------
/problems/0127.word-ladder/run_test.go:
--------------------------------------------------------------------------------
1 | package ladder
2 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/itcuihao/leetcode-go
2 |
3 | go 1.13
4 |
--------------------------------------------------------------------------------
/create/run.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itcuihao/leetcode-go/HEAD/create/run.exe
--------------------------------------------------------------------------------
/static/image/304.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itcuihao/leetcode-go/HEAD/static/image/304.png
--------------------------------------------------------------------------------
/problems/0435.non-overlapping-intervals/run.go:
--------------------------------------------------------------------------------
1 |
2 | package intervals
3 |
4 | func Run() {
5 |
6 | }
7 |
--------------------------------------------------------------------------------
/static/image/binarytree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itcuihao/leetcode-go/HEAD/static/image/binarytree.png
--------------------------------------------------------------------------------
/static/image/160_statement.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itcuihao/leetcode-go/HEAD/static/image/160_statement.png
--------------------------------------------------------------------------------
/problems/0009.palindrome-number/README.md:
--------------------------------------------------------------------------------
1 | Determine whether an integer is a palindrome. Do this without extra space.
2 |
3 |
--------------------------------------------------------------------------------
/static/image/circularlinkedlist.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itcuihao/leetcode-go/HEAD/static/image/circularlinkedlist.png
--------------------------------------------------------------------------------
/problems/0090.subsets-ii/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package ii
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0146.lru-cache/run_test.go:
--------------------------------------------------------------------------------
1 | package cache
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | Run()
7 | }
8 |
--------------------------------------------------------------------------------
/problems/0038.count-and-say/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package say
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0039.combination-sum/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package sum
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0046.permute/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package permute
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0213.house-robber-ii/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package ii
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0283.move-zeroes/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package zeroes
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0338.counting-bits/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package bits
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/static/image/binarysearchtree_improved.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itcuihao/leetcode-go/HEAD/static/image/binarysearchtree_improved.png
--------------------------------------------------------------------------------
/problems/0064.minimum-path-sum/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package sum
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0092.reverse-linked-list-2/run_test.go:
--------------------------------------------------------------------------------
1 | package reverse
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | Run()
7 | }
8 |
--------------------------------------------------------------------------------
/problems/0127.word-ladder/run.go:
--------------------------------------------------------------------------------
1 | package ladder
2 |
3 | func ladderLength(beginWord string, endWord string, wordList []string) int {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/problems/0142.linked-list-cycle-ii/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package ii
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0455.assign-cookies/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package cookies
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0832.flipping-an-image/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package image
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0888.fair-candy-swap/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package swap
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0042.trapping-rain-water/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package water
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0234.palindrome-linked-list/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package list
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0480.sliding-window-median/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package median
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0617.merge-two-binary-trees/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package trees
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0098.validate-binary-search-tree/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package tree
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0354.russian-doll-envelopes/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package envelopes
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0128.longest-consecutive-sequence/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package sequence
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0131.palindrome-partitioning/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package partitioning
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0303.range-sum-query-immutable/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package immutable
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0304.range-sum-query-2d-immutable/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package immutable
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0387.first-unique-character-in-a-string/run_test.go:
--------------------------------------------------------------------------------
1 | package string
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | Run()
7 | }
8 |
--------------------------------------------------------------------------------
/problems/0435.non-overlapping-intervals/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package intervals
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0102.binary-tree-level-order-traversal/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package traversal
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0069.sqrt/run_test.go:
--------------------------------------------------------------------------------
1 | package sqrt
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | i := 9
7 | s := mySqrt(i)
8 | t.Log(s)
9 | }
10 |
--------------------------------------------------------------------------------
/problems/0424.longest-repeating-character-replacement/run_test.go:
--------------------------------------------------------------------------------
1 |
2 | package replacement
3 |
4 | import "testing"
5 |
6 | func TestRun(t *testing.T) {
7 | Run()
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0022.generate-parentheses/run_test.go:
--------------------------------------------------------------------------------
1 | package parentheses
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | n := 3
7 | generateParenthesis(n)
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0034.find-first-and-last-position-of-element-in-sorted-array/run_test.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | Run()
7 | }
8 |
--------------------------------------------------------------------------------
/problems/0480.sliding-window-median/run.go:
--------------------------------------------------------------------------------
1 | package median
2 |
3 | func Run() {
4 |
5 | }
6 |
7 | func medianSlidingWindow(nums []int, k int) []float64 {
8 | return nil
9 | }
10 |
--------------------------------------------------------------------------------
/problems/0010.regular-expression-matching/run_test.go:
--------------------------------------------------------------------------------
1 | package matching
2 |
3 | import "testing"
4 |
5 | func TestIsMatching(t *testing.T) {
6 | s := "ab"
7 | t.Log(isMatch(s, "*"))
8 | }
9 |
--------------------------------------------------------------------------------
/problems/0029.divide-two-integers/run_test.go:
--------------------------------------------------------------------------------
1 | package integers
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 | i := divide(10, 3)
9 | t.Log(i)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0012.integer-to-roman/run_test.go:
--------------------------------------------------------------------------------
1 | package roman
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | fmt.Println(intToRoman(1992))
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0028.implement-strstr/run_test.go:
--------------------------------------------------------------------------------
1 | package strstr
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 | i := strStr("hello", "ll")
9 | t.Log(i)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0206.reverse-linked-list/README.md:
--------------------------------------------------------------------------------
1 | Reverse a singly linked list.
2 |
3 | ```text
4 | 反转一个单链表。
5 |
6 | 示例:
7 |
8 | 输入: 1->2->3->4->5->NULL
9 | 输出: 5->4->3->2->1->NULL
10 | ```
--------------------------------------------------------------------------------
/problems/0006.zigzag-conversion/run_test.go:
--------------------------------------------------------------------------------
1 | package conversion
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestConvert(t *testing.T) {
8 | s := "abcde"
9 | t.Log(convert(s, 3))
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0027.remove-element/run_test.go:
--------------------------------------------------------------------------------
1 | package element
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 | n := []int{3, 2, 2, 3}
9 | removeElement(n, 3)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0013.roman-to-integer/run_test.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRomanToInt(t *testing.T) {
9 | fmt.Println(romanToInt("XIV"))
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0077.combinations/run_test.go:
--------------------------------------------------------------------------------
1 | package combinations
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | n := 4
7 | k := 2
8 | res := combine(n, k)
9 | t.Log(res)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0007.reverse-integer/run_test.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | import "testing"
4 |
5 | func TestReverse(t *testing.T) {
6 | // x := 123
7 | x := -123
8 | // x := 1534236469
9 | t.Log(reverse(x))
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0392.is-subsequence/run_test.go:
--------------------------------------------------------------------------------
1 | package subsequence
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | s := "abc"
7 | x := "ahbgdc"
8 | b := isSubsequence(s, x)
9 | t.Log(b)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0064.minimum-path-sum/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0064.minimum-path-sum
3 |
4 | ```text
5 | 64. 最小路径和
6 |
7 | 难度:中等
8 |
9 | 给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
10 |
11 | 说明:每次只能向下或者向右移动一步。
12 | ```
--------------------------------------------------------------------------------
/problems/0026.remove-duplicates-from-sorted-array/run_test.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 | s := []int{1, 1, 3, 4, 4}
9 | t.Log(removeDuplicates(s))
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0020.valid-parentheses/run_test.go:
--------------------------------------------------------------------------------
1 | package parentheses
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 |
10 | s := "[({})]"
11 | r := isValid(s)
12 | fmt.Println(r)
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0009.palindrome-number/run_test.go:
--------------------------------------------------------------------------------
1 | package number
2 |
3 | import "testing"
4 |
5 | func TestIsPalindrome(t *testing.T) {
6 | // i := 1221
7 | // i := -1221
8 | // i := 123123
9 | i := 1000021
10 | t.Log(isPalindrome(i))
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0088.merge-sorted-array/run_test.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | n1 := []int{1, 2, 3, 0, 0, 0}
7 | m := 3
8 | n2 := []int{2, 5, 6}
9 | n := 3
10 | merge(n1, m, n2, n)
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0169.majority-element/run_test.go:
--------------------------------------------------------------------------------
1 | package element
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | n := []int{1, 2, 3, 4, 2, 2, 2}
7 | // k := majorityElement(n)
8 | k := majorityElement2(n)
9 | t.Log(k)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0101.symmetric-tree/run_test.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | tree := structure.BinaryTree101
10 | b := isSymmetric(tree)
11 | t.Log(b)
12 | }
13 |
--------------------------------------------------------------------------------
/problems/0470.implement-rand10-using-rand7/run_test.go:
--------------------------------------------------------------------------------
1 | package rand7
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | r := rand10()
7 | t.Log(r)
8 | }
9 | func TestRand7(t *testing.T) {
10 | r := rand7()
11 | t.Log(r)
12 | }
13 |
--------------------------------------------------------------------------------
/problems/0097.interleaving-string/run_test.go:
--------------------------------------------------------------------------------
1 | package string
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | s1 := "aabcc"
7 | s2 := "dbbca"
8 | s3 := "aadbbcbcac"
9 |
10 | is := isInterleave(s1, s2, s3)
11 | t.Log(is)
12 | }
13 |
--------------------------------------------------------------------------------
/problems/0215.kth-largest-element-in-an-array/run_test.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 |
7 | nums := []int{3, 2, 3, 1, 2, 4, 5, 5, 6}
8 | k := 4
9 | m := findKthLargest(nums, k)
10 | t.Log(m)
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0043.multiply-strings/run_test.go:
--------------------------------------------------------------------------------
1 | package strings
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | a := "1234123473241297384743921847192"
7 | b := "342148720845718049587238457835729"
8 | c := multiply(a, b)
9 | t.Log(c)
10 | }
11 |
--------------------------------------------------------------------------------
/problems/0136.single-number/run_test.go:
--------------------------------------------------------------------------------
1 | package number
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | n := []int{1, 2, 2, 4, 4}
7 | // s := singleNumber(n)
8 | // s := singleNumber1(n)
9 | s := singleNumber2(n)
10 | t.Log(s)
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0014.longest-common-prefix/run_test.go:
--------------------------------------------------------------------------------
1 | package prefix
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | strs := []string{
10 | "abcd",
11 | "ab",
12 | }
13 | fmt.Println(longestCommonPrefix(strs))
14 | }
15 |
--------------------------------------------------------------------------------
/problems/0032.longest-valid-parentheses/run_test.go:
--------------------------------------------------------------------------------
1 | package parentheses
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 |
9 | s := "()()"
10 |
11 | l := longestValidParentheses(s)
12 | if l != 4 {
13 | t.Error("not")
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0141.linked-list-cycle/run_test.go:
--------------------------------------------------------------------------------
1 | package cycle
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/itcuihao/leetcode-go/structure"
7 | )
8 |
9 | func TestRun(t *testing.T) {
10 | l := structure.ListNodeCycle
11 | b := hasCycle(l)
12 | t.Log(b)
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0011.container-with-most-water/run_test.go:
--------------------------------------------------------------------------------
1 | package water
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestMaxArea(t *testing.T) {
9 | height := []int{10, 10, 2}
10 | a := maxArea(height)
11 | fmt.Println(a)
12 | t.Logf("value:%v", a)
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0240.search-a-2D-matrix2/run_test.go:
--------------------------------------------------------------------------------
1 | package matrix2
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | m := [][]int{
7 | []int{1, 2, 3},
8 | []int{3, 4, 5},
9 | }
10 | target := 4
11 | is := searchMatrix(m, target)
12 | t.Log(is)
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0542.01-matrix/run_test.go:
--------------------------------------------------------------------------------
1 | package matrix
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | matrix := [][]int{
7 | []int{0, 0, 0},
8 | []int{0, 1, 0},
9 | []int{1, 1, 1},
10 | }
11 | a := updateMatrix(matrix)
12 | t.Logf("%+v", a)
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0028.implement-strstr/run.go:
--------------------------------------------------------------------------------
1 | package strstr
2 |
3 | func strStr(haystack string, needle string) int {
4 | lh, ln := len(haystack), len(needle)
5 | for i := 0; i <= lh; i++ {
6 | if haystack[i:i+ln] == needle {
7 | return i
8 | }
9 | }
10 | return -1
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0050.pow/run_test.go:
--------------------------------------------------------------------------------
1 | package pow
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | x := 2.00
7 | n := 3
8 | p := MyPow(x, n)
9 | t.Log(p)
10 | }
11 | func TestRun2(t *testing.T) {
12 | x := 2.00
13 | n := 2
14 | p := MyPow2(x, n)
15 | t.Log(p)
16 | }
17 |
--------------------------------------------------------------------------------
/problems/0069.sqrt/run.go:
--------------------------------------------------------------------------------
1 | package sqrt
2 |
3 | func mySqrt(x int) int {
4 | if x <= 1 {
5 | return x
6 | }
7 |
8 | l, h := 0, x
9 | for l < h {
10 | m := l + (h-l)/2
11 | if x/m >= m {
12 | l = m + 1
13 | } else {
14 | h = m
15 | }
16 | }
17 |
18 | return h - 1
19 | }
20 |
--------------------------------------------------------------------------------
/problems/0018.4sum/run_test.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 |
10 | target := 0
11 |
12 | // nums := []int{1, 0, -1, 0, -2, 2}
13 | nums := []int{0, 0, 0, 0}
14 | s := fourSum(nums, target)
15 | fmt.Println(s)
16 | }
17 |
--------------------------------------------------------------------------------
/problems/0160.intersection-of-two-linked-lists/run_test.go:
--------------------------------------------------------------------------------
1 | package lists
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | a := structure.ListNodeA
10 | b := structure.ListNodeB
11 | c := getIntersectionNode(b, a)
12 | t.Log(c)
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0015.3sum/run_test.go:
--------------------------------------------------------------------------------
1 | package threesum
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | nums := []int{-1, 0, 1, 2, -1, -4}
10 | // nums := []int{0, 0, 0, 0}
11 | // nums := []int{-1, 0, 1, 0}
12 | s := threeSum(nums)
13 | fmt.Println(s)
14 | }
15 |
--------------------------------------------------------------------------------
/problems/0017.letter-combinations-of-a-phone-number/run_test.go:
--------------------------------------------------------------------------------
1 | package closest
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 |
10 | target := "23"
11 |
12 | // s := letterCombinations(target)
13 | s := letterCombinationsDFS(target)
14 | fmt.Println(s)
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0088.merge-sorted-array/run.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import (
4 | "fmt"
5 | "sort"
6 | )
7 |
8 | func merge(nums1 []int, m int, nums2 []int, n int) {
9 | nums1 = nums1[:m]
10 | nums2 = nums2[:n]
11 |
12 | nums1 = append(nums1, nums2...)
13 | sort.Ints(nums1)
14 | fmt.Println(nums1)
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0004.median-of-two-sorted-arrays/run_test.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | import "testing"
4 |
5 | // go test -v -test.run TestFindMedianSortedArrays
6 | func TestFindMedianSortedArrays(t *testing.T) {
7 | n1 := []int{1, 3}
8 | n2 := []int{2, 4}
9 | f := findMedianSortedArrays(n1, n2)
10 | t.Log(f)
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0023.merge-k-sorted-lists/README.md:
--------------------------------------------------------------------------------
1 | # 23.Merge k Sorted Lists
2 |
3 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
4 |
5 | Example:
6 |
7 | ```
8 | Input:
9 | [
10 | 1->4->5,
11 | 1->3->4,
12 | 2->6
13 | ]
14 | Output: 1->1->2->3->4->4->5->6
15 | ```
--------------------------------------------------------------------------------
/problems/0027.remove-element/run.go:
--------------------------------------------------------------------------------
1 | package element
2 |
3 | func removeElement(nums []int, val int) int {
4 | if len(nums) == 0 {
5 | return 0
6 | }
7 | i := 0
8 | for _, v := range nums {
9 | if v != val {
10 | nums[i] = v
11 | i++
12 | }
13 | }
14 | nums = nums[:i]
15 | return len(nums)
16 | }
17 |
--------------------------------------------------------------------------------
/problems/0083.remove-duplicates-from-sorted-list/run_test.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | l := structure.ListNode82
10 | dl := deleteDuplicates(l)
11 | for dl != nil {
12 | t.Log(dl.Val)
13 | dl = dl.Next
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0007.reverse-integer/README.md:
--------------------------------------------------------------------------------
1 | Given a 32-bit signed integer, reverse digits of an integer.
2 |
3 | Example 1:
4 |
5 | ```
6 | Input: 123
7 | Output: 321
8 | ```
9 |
10 | Example 2:
11 |
12 | ```
13 | Input: -123
14 | Output: -321
15 | ```
16 |
17 | Example 3:
18 |
19 | ```
20 | Input: 120
21 | Output: 21
22 | ```
--------------------------------------------------------------------------------
/problems/0053.maximum-subarray/run_test.go:
--------------------------------------------------------------------------------
1 | package subarray
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | s := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
7 | t.Log(maxSubArray(s))
8 | }
9 |
10 | func TestRun2(t *testing.T) {
11 | s := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
12 | t.Log(maxSubArrayDp(s))
13 | }
14 |
--------------------------------------------------------------------------------
/problems/0148.sort-list/run_test.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import (
4 | "fmt"
5 | "leetcode-go/structure"
6 | "testing"
7 | )
8 |
9 | func TestRun(t *testing.T) {
10 | head := structure.ListNodeB
11 | l := sortListMerge(head)
12 | for l != nil {
13 | fmt.Println(l.Val)
14 | fmt.Println(l.Next)
15 | l = l.Next
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/problems/0016.3sum-closest/run_test.go:
--------------------------------------------------------------------------------
1 | package closest
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | nums := []int{-1, 0, 1, 2, -1, -4}
10 | target := 4
11 | // nums := []int{0, 0, 0, 0}
12 | // nums := []int{-1, 0, 1, 0}
13 | s := threeSumClosest(nums, target)
14 | fmt.Println(s)
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0022.generate-parentheses/README.md:
--------------------------------------------------------------------------------
1 | # 22.Generate Parentheses
2 |
3 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
4 |
5 | For example, given n = 3, a solution set is:
6 |
7 | ```
8 | [
9 | "((()))",
10 | "(()())",
11 | "(())()",
12 | "()(())",
13 | "()()()"
14 | ]
15 | ```
--------------------------------------------------------------------------------
/problems/0082.remove-duplicates-from-sorted-list2/run_test.go:
--------------------------------------------------------------------------------
1 | package list2
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/itcuihao/leetcode-go/structure"
7 | )
8 |
9 | func TestRun(t *testing.T) {
10 | l := structure.ListNode82
11 | dl := deleteDuplicates(l)
12 | for dl != nil {
13 | t.Log(dl.Val)
14 | dl = dl.Next
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/problems/0387.first-unique-character-in-a-string/run.go:
--------------------------------------------------------------------------------
1 | package string
2 |
3 | func firstUniqChar(s string) int {
4 | if s == "" {
5 | return -1
6 | }
7 | check := make(map[rune]int)
8 | for _, v := range s {
9 | check[v]++
10 | }
11 | for k, v := range s {
12 | if check[v] == 1 {
13 | return k
14 | }
15 | }
16 | return -1
17 | }
18 |
--------------------------------------------------------------------------------
/problems/0206.reverse-linked-list/run.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import "github.com/itcuihao/leetcode-go/structure"
4 |
5 | func reverseList(head *structure.ListNode) *structure.ListNode {
6 |
7 | var p *structure.ListNode
8 | for head != nil {
9 | temp := head.Next
10 | head.Next = p
11 | p = head
12 | head = temp
13 | }
14 | return p
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0128.longest-consecutive-sequence/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0128.longest-consecutive-sequence
3 |
4 | 给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
5 |
6 | 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
7 |
8 |
9 |
10 | 示例 1:
11 |
12 | 输入:nums = [100,4,200,1,3,2]
13 | 输出:4
14 | 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
15 | 示例 2:
16 |
17 | 输入:nums = [0,3,7,2,5,8,4,6,0,1]
18 | 输出:9
19 |
--------------------------------------------------------------------------------
/problems/0024.swap-nodes-in-pairs/run_test.go:
--------------------------------------------------------------------------------
1 | package pairs
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | var ls *ListNode
7 | ls = &ListNode{
8 | Val: 1,
9 | Next: &ListNode{
10 | Val: 2,
11 | Next: &ListNode{
12 | Val: 3,
13 | Next: &ListNode{
14 | Val: 4,
15 | },
16 | },
17 | },
18 | }
19 |
20 | swapPairs(ls)
21 | }
22 |
--------------------------------------------------------------------------------
/problems/0005.longest-palindromic-substring/README.md:
--------------------------------------------------------------------------------
1 | # 题干
2 |
3 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
4 |
5 | Example:
6 |
7 | ```
8 | Input: "babad"
9 |
10 | Output: "bab"
11 |
12 | Note: "aba" is also a valid answer.
13 | ```
14 | Example:
15 |
16 | ```
17 | Input: "cbbd"
18 |
19 | Output: "bb"
20 | ```
--------------------------------------------------------------------------------
/problems/0092.reverse-linked-list-2/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0092.reverse-linked-list-2
3 |
4 | ```
5 | 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
6 |
7 | 说明:
8 | 1 ≤ m ≤ n ≤ 链表长度。
9 |
10 | 示例:
11 |
12 | 输入: 1->2->3->4->5->NULL, m = 2, n = 4
13 | 输出: 1->4->3->2->5->NULL
14 |
15 | 来源:力扣(LeetCode)
16 | 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
17 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
18 | ```
--------------------------------------------------------------------------------
/problems/0155.min-stack/run_test.go:
--------------------------------------------------------------------------------
1 | package stack
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | minStack := Constructor()
7 | //minStack.Push(-2)
8 | //minStack.Push(0)
9 | //minStack.Push(-1)
10 | a := minStack.GetMin()
11 | t.Log(a)
12 |
13 | a = minStack.Top()
14 | t.Log(a)
15 | minStack.Pop()
16 |
17 | a = minStack.GetMin()
18 | t.Log(a)
19 | }
20 |
--------------------------------------------------------------------------------
/problems/0234.palindrome-linked-list/run.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import "github.com/itcuihao/leetcode-go/structure"
4 |
5 | func Run() {
6 |
7 | }
8 |
9 | /**
10 | * Definition for singly-linked list.
11 | * type ListNode struct {
12 | * Val int
13 | * Next *ListNode
14 | * }
15 | */
16 | func isPalindrome(head *structure.ListNode) bool {
17 |
18 | return false
19 | }
20 |
--------------------------------------------------------------------------------
/problems/0003.longest-substring-without-repeating-characters/run_test.go:
--------------------------------------------------------------------------------
1 | package characters
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | // go test -v -test.run TestLengthOfLongestSubstring
8 | func TestLengthOfLongestSubstring(t *testing.T) {
9 | // s := "abca"
10 | // s := "abcabcbb"
11 | // s := "dvdf"
12 | s := "pwwkew"
13 | // s := "c"
14 | t.Log(lengthOfLongestSubstring(s))
15 | }
16 |
--------------------------------------------------------------------------------
/problems/0009.palindrome-number/run.go:
--------------------------------------------------------------------------------
1 | package number
2 |
3 | import (
4 | "strconv"
5 | )
6 |
7 | func isPalindrome(i int) bool {
8 | if i < 0 {
9 | return false
10 | }
11 | s := strconv.Itoa(i)
12 | ls := len(s)
13 | if ls == 1 {
14 | return true
15 | }
16 | for j := 0; j < ls/2; j++ {
17 | if s[j] != s[ls-j-1] {
18 | return false
19 | }
20 | }
21 | return true
22 | }
23 |
--------------------------------------------------------------------------------
/problems/0234.palindrome-linked-list/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0234.palindrome-linked-list
3 |
4 | ```text
5 | 请判断一个链表是否为回文链表。
6 |
7 | 示例 1:
8 |
9 | 输入: 1->2
10 | 输出: false
11 | 示例 2:
12 |
13 | 输入: 1->2->2->1
14 | 输出: true
15 | 进阶:
16 | 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
17 |
18 | 来源:力扣(LeetCode)
19 | 链接:https://leetcode-cn.com/problems/palindrome-linked-list
20 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
21 | ```
--------------------------------------------------------------------------------
/problems/0008.string-to-integer/README.md:
--------------------------------------------------------------------------------
1 | Implement atoi to convert a string to an integer.
2 |
3 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
4 |
5 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
--------------------------------------------------------------------------------
/problems/0283.move-zeroes/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0283.move-zeroes
3 |
4 | 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
5 |
6 | 请注意 ,必须在不复制数组的情况下原地对数组进行操作。
7 |
8 |
9 |
10 | 示例 1:
11 |
12 | 输入: nums = [0,1,0,3,12]
13 | 输出: [1,3,12,0,0]
14 | 示例 2:
15 |
16 | 输入: nums = [0]
17 | 输出: [0]
18 |
19 |
20 | 提示:
21 |
22 | 1 <= nums.length <= 104
23 | -231 <= nums[i] <= 231 - 1
24 |
25 |
26 | 进阶:你能尽量减少完成的操作次数吗?
--------------------------------------------------------------------------------
/problems/0011.container-with-most-water/README.md:
--------------------------------------------------------------------------------
1 | # 题干
2 |
3 | ```discription
4 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
5 | ```
6 |
7 | > 求数组之间最大面积,从数组两端往中间计算
--------------------------------------------------------------------------------
/problems/0026.remove-duplicates-from-sorted-array/run.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | func removeDuplicates(nums []int) int {
4 | l := len(nums)
5 |
6 | if l <= 1 {
7 | return l
8 | }
9 |
10 | res := 1
11 |
12 | for i := 1; i < l; i++ {
13 | if nums[i] == nums[i-1] {
14 | continue
15 | }
16 |
17 | if res != i {
18 | nums[res] = nums[i]
19 | }
20 |
21 | res++
22 | }
23 | return res
24 | }
25 |
--------------------------------------------------------------------------------
/problems/0058.length-of-last-word/run.go:
--------------------------------------------------------------------------------
1 | package word
2 |
3 | import (
4 | "strings"
5 | )
6 |
7 | func lengthOfLastWord(s string) int {
8 | s = strings.TrimSpace(s)
9 | if s == "" {
10 | return 0
11 | }
12 | var last []byte
13 | l := len(s) - 1
14 |
15 | for i := l; i >= 0; i-- {
16 | if s[i] == 32 {
17 | break
18 | }
19 | last = append(last, s[i])
20 | }
21 | return len(last)
22 | }
23 |
--------------------------------------------------------------------------------
/problems/0236.lowest-common-ancestor-of-a-binary-tree/run_test.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | root := structure.BinaryTree
10 | q := &structure.TreeNode{
11 | Val: 5,
12 | }
13 | p := &structure.TreeNode{
14 | Val: 0,
15 | }
16 | ancestor := lowestCommonAncestor(root, q, p)
17 |
18 | t.Log(ancestor)
19 | }
20 |
--------------------------------------------------------------------------------
/problems/0016.3sum-closest/README.md:
--------------------------------------------------------------------------------
1 | Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
2 |
3 | Example:
4 |
5 | ```eg
6 | Given array nums = [-1, 2, 1, -4], and target = 1.
7 |
8 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
9 | ```
--------------------------------------------------------------------------------
/problems/0024.swap-nodes-in-pairs/README.md:
--------------------------------------------------------------------------------
1 | # 24.Swap Nodes in Pairs
2 |
3 | Given a linked list, swap every two adjacent nodes and return its head.
4 |
5 | Example:
6 |
7 | ```
8 | Given 1->2->3->4, you should return the list as 2->1->4->3.
9 | ```
10 |
11 | Note:
12 |
13 | Your algorithm should use only constant extra space.
14 | You may not modify the values in the list's nodes, only nodes itself may be changed.
--------------------------------------------------------------------------------
/problems/0144.binary-tree-preorder-traversal/run_test.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | import "testing"
4 |
5 | var tn = &TreeNode{
6 | Val: 1,
7 | Right: &TreeNode{
8 | Val: 2,
9 | Left: &TreeNode{
10 | Val: 3,
11 | },
12 | },
13 | }
14 |
15 | func TestPreorderTraversal(t *testing.T) {
16 | t.Log(preorderTraversal(tn))
17 | }
18 | func TestPreorderFor(t *testing.T) {
19 | t.Log(preorderFor(tn))
20 | }
21 |
--------------------------------------------------------------------------------
/problems/0169.majority-element/run.go:
--------------------------------------------------------------------------------
1 | package element
2 |
3 | import "sort"
4 |
5 | func majorityElement(nums []int) int {
6 | c := make(map[int]int)
7 | for _, v := range nums {
8 | c[v]++
9 | }
10 | for k, v := range c {
11 | if v > len(nums)/2 {
12 | return k
13 | }
14 | }
15 | return 0
16 | }
17 | func majorityElement2(nums []int) int {
18 | sort.Ints(nums)
19 | return nums[len(nums)/2]
20 | }
21 |
--------------------------------------------------------------------------------
/problems/0008.string-to-integer/run_test.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | import "testing"
4 |
5 | func TestMyAtoi(t *testing.T) {
6 | // s := "-123a..."
7 | // s := " 010"
8 | // s := "-2147483648"
9 | s := "2147483648"
10 | t.Log(myAtoi(s))
11 | }
12 |
13 | func TestAtoi(t *testing.T) {
14 | s := "-123a..."
15 | // s := " 010"
16 | // s := "-2147483648"
17 | // s := "2147483648"
18 | t.Log(atoi(s))
19 | }
20 |
--------------------------------------------------------------------------------
/problems/0164.maximum-gap/run_test.go:
--------------------------------------------------------------------------------
1 | package gap
2 |
3 | import "testing"
4 |
5 | var (
6 | a = []int{3, 5, 9, 1}
7 | )
8 |
9 | func TestRun(t *testing.T) {
10 | maxSub := maximumGap(a)
11 | t.Log(maxSub)
12 | }
13 |
14 | func TestQuick(t *testing.T) {
15 | quickSort(a, 0, len(a)-1)
16 | t.Log(a)
17 | }
18 |
19 | func TestP(t *testing.T) {
20 | i := partition(a, 1, len(a)-1)
21 | t.Log(i)
22 | t.Log(a)
23 | }
24 |
--------------------------------------------------------------------------------
/problems/0392.is-subsequence/run.go:
--------------------------------------------------------------------------------
1 | package subsequence
2 |
3 | func isSubsequence(s string, t string) bool {
4 | ls := len(s)
5 | lt := len(t)
6 | if ls == 0 && lt > 0 {
7 | return true
8 | }
9 | if ls > 0 && lt == 0 {
10 | return false
11 | }
12 | i, j := 0, 0
13 | for i < ls && j < lt {
14 | if s[i] == t[j] {
15 | i++
16 | j++
17 | } else {
18 | j++
19 | }
20 | }
21 | return i == ls
22 | }
23 |
--------------------------------------------------------------------------------
/problems/0015.3sum/README.md:
--------------------------------------------------------------------------------
1 | Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
2 |
3 | Note:
4 |
5 | The solution set must not contain duplicate triplets.
6 |
7 | Example:
8 |
9 | ```
10 | Given array nums = [-1, 0, 1, 2, -1, -4],
11 |
12 | A solution set is:
13 | [
14 | [-1, 0, 1],
15 | [-1, -1, 2]
16 | ]
17 | ```
--------------------------------------------------------------------------------
/problems/0102.binary-tree-level-order-traversal/run.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | import "github.com/itcuihao/leetcode-go/structure"
4 |
5 | func Run() {
6 |
7 | }
8 |
9 | /**
10 | * Definition for a binary tree node.
11 | * type TreeNode struct {
12 | * Val int
13 | * Left *TreeNode
14 | * Right *TreeNode
15 | * }
16 | */
17 | func levelOrder(root *structure.TreeNode) [][]int {
18 |
19 | return nil
20 | }
21 |
--------------------------------------------------------------------------------
/problems/0338.counting-bits/run.go:
--------------------------------------------------------------------------------
1 | package bits
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | bits := countBits(5)
7 | fmt.Println(bits)
8 | }
9 |
10 | func countBits(num int) []int {
11 | bits := make([]int, num+1)
12 | for i := 0; i <= num; i++ {
13 | bits[i] = oneCount(i)
14 | }
15 | return bits
16 | }
17 |
18 | func oneCount(n int) int {
19 | c := 0
20 | for ; n > 0; n &= n - 1 {
21 | c++
22 | }
23 | return c
24 | }
25 |
--------------------------------------------------------------------------------
/problems/0046.permute/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0046.permute
3 |
4 | ```
5 | 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
6 |
7 |
8 |
9 | 示例 1:
10 |
11 | 输入:nums = [1,2,3]
12 | 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
13 | 示例 2:
14 |
15 | 输入:nums = [0,1]
16 | 输出:[[0,1],[1,0]]
17 | 示例 3:
18 |
19 | 输入:nums = [1]
20 | 输出:[[1]]
21 |
22 |
23 | 提示:
24 |
25 | 1 <= nums.length <= 6
26 | -10 <= nums[i] <= 10
27 | nums 中的所有整数 互不相同
28 | ```
--------------------------------------------------------------------------------
/problems/0617.merge-two-binary-trees/run.go:
--------------------------------------------------------------------------------
1 | package trees
2 |
3 | import "github.com/itcuihao/leetcode-go/structure"
4 |
5 | func Run() {
6 |
7 | }
8 |
9 | /**
10 | * Definition for a binary tree node.
11 | * type TreeNode struct {
12 | * Val int
13 | * Left *TreeNode
14 | * Right *TreeNode
15 | * }
16 | */
17 | func mergeTrees(t1 *structure.TreeNode, t2 *structure.TreeNode) *structure.TreeNode {
18 | return nil
19 | }
20 |
--------------------------------------------------------------------------------
/problems/0142.linked-list-cycle-ii/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0142.linked-list-cycle-ii
3 |
4 | ```text
5 | 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
6 |
7 | 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
8 |
9 | 说明:不允许修改给定的链表。
10 |
11 | 进阶:
12 |
13 | 你是否可以使用 O(1) 空间解决此题?
14 |
15 | 来源:力扣(LeetCode)
16 | 链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
17 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
18 | ```
--------------------------------------------------------------------------------
/problems/0014.longest-common-prefix/run.go:
--------------------------------------------------------------------------------
1 | package prefix
2 |
3 | func longestCommonPrefix(strs []string) string {
4 | if len(strs) == 0 {
5 | return ""
6 | }
7 |
8 | p := strs[0]
9 | for _, v := range strs {
10 | if len(p) > len(v) {
11 | p = v
12 | }
13 | }
14 |
15 | for k, v := range p {
16 | for j := 0; j < len(strs); j++ {
17 | if strs[j][k] != byte(v) {
18 | return strs[j][:k]
19 | }
20 | }
21 | }
22 | return p
23 | }
24 |
--------------------------------------------------------------------------------
/problems/0021.merge-two-sorted-lists/run_test.go:
--------------------------------------------------------------------------------
1 | package lists
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | l1 := &ListNode{
7 | Val: 1,
8 | Next: &ListNode{
9 | Val: 2,
10 | Next: &ListNode{
11 | Val: 4,
12 | },
13 | },
14 | }
15 | l2 := &ListNode{
16 | Val: 1,
17 | Next: &ListNode{
18 | Val: 3,
19 | Next: &ListNode{
20 | Val: 4,
21 | },
22 | },
23 | }
24 | printList(mergeTwoLists(l1, l2))
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0012.integer-to-roman/run.go:
--------------------------------------------------------------------------------
1 | package roman
2 |
3 | func intToRoman(num int) string {
4 | d := [4][]string{
5 | []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
6 | []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
7 | []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
8 | []string{"", "M", "MM", "MMM"},
9 | }
10 | return d[3][num/1000] + d[2][num/100%10] + d[1][num/10%10] + d[0][num%10]
11 | }
12 |
--------------------------------------------------------------------------------
/problems/0206.reverse-linked-list/run_test.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/itcuihao/leetcode-go/structure"
7 | )
8 |
9 | func TestRun(t *testing.T) {
10 | l := &structure.ListNode{
11 | Val: 1,
12 | Next: &structure.ListNode{
13 | Val: 2,
14 | Next: &structure.ListNode{
15 | Val: 3,
16 | },
17 | },
18 | }
19 |
20 | lr := reverseList(l)
21 | for lr != nil {
22 | t.Log(lr.Val)
23 | lr = lr.Next
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0283.move-zeroes/run.go:
--------------------------------------------------------------------------------
1 | package zeroes
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func Run() {
8 | n := []int{0, 0, 0, 1}
9 | moveZeroes(n)
10 | fmt.Println(n)
11 | }
12 |
13 | func moveZeroes(nums []int) {
14 | l := len(nums)
15 | if l == 0 {
16 | return
17 | }
18 | left, right := 0, 0
19 | for i := 0; i < l; i++ {
20 | if nums[right] != 0 {
21 | nums[left], nums[right] = nums[right], nums[left]
22 | left++
23 | }
24 | right++
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/problems/0004.median-of-two-sorted-arrays/README.md:
--------------------------------------------------------------------------------
1 | # 题干
2 |
3 | There are two sorted arrays nums1 and nums2 of size m and n respectively.
4 |
5 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
6 |
7 | Example 1:
8 |
9 | ```eg
10 | nums1 = [1, 3]
11 | nums2 = [2]
12 |
13 | The median is 2.0
14 | ```
15 |
16 | Example 2:
17 |
18 | ```eg
19 | nums1 = [1, 2]
20 | nums2 = [3, 4]
21 |
22 | The median is (2 + 3)/2 = 2.5
23 | ```
24 |
--------------------------------------------------------------------------------
/problems/0050.pow/README.md:
--------------------------------------------------------------------------------
1 | # 0050.Pow
2 |
3 | ```English
4 | Implement pow(x, n), which calculates x raised to the power n (xn).
5 |
6 | Example 1:
7 |
8 | Input: 2.00000, 10
9 | Output: 1024.00000
10 | Example 2:
11 |
12 | Input: 2.10000, 3
13 | Output: 9.26100
14 | Example 3:
15 |
16 | Input: 2.00000, -2
17 | Output: 0.25000
18 | Explanation: 2-2 = 1/22 = 1/4 = 0.25
19 | Note:
20 |
21 | -100.0 < x < 100.0
22 | n is a 32-bit signed integer, within the range [−231, 231 − 1]
23 | ```
--------------------------------------------------------------------------------
/problems/0014.longest-common-prefix/README.md:
--------------------------------------------------------------------------------
1 | Write a function to find the longest common prefix string amongst an array of strings.
2 |
3 | If there is no common prefix, return an empty string "".
4 |
5 | Example 1:
6 |
7 | Input: ["flower","flow","flight"]
8 | Output: "fl"
9 | Example 2:
10 |
11 | Input: ["dog","racecar","car"]
12 | Output: ""
13 | Explanation: There is no common prefix among the input strings.
14 | Note:
15 |
16 | All given inputs are in lowercase letters a-z.
17 |
18 | > 选取最短的串去进行比较
--------------------------------------------------------------------------------
/structure/lists.go:
--------------------------------------------------------------------------------
1 | package structure
2 |
3 | import "fmt"
4 |
5 | // ListNode 链表
6 | type ListNode struct {
7 | Val int
8 | Next *ListNode
9 | }
10 |
11 | func (l *ListNode) Print() {
12 | fmt.Println("start")
13 | for l != nil {
14 | fmt.Printf("%v -> ", l.Val)
15 | l = l.Next
16 | }
17 | fmt.Println("\nend")
18 | }
19 |
20 | // Lists 链表
21 | type Lists []*ListNode
22 |
23 | // TreeNode 树节点
24 | type TreeNode struct {
25 | Val int
26 | Left *TreeNode
27 | Right *TreeNode
28 | }
29 |
--------------------------------------------------------------------------------
/problems/0077.combinations/run.go:
--------------------------------------------------------------------------------
1 | package combinations
2 |
3 | func combine(n int, k int) [][]int {
4 |
5 | tmp := make([]int, k)
6 | var res [][]int
7 |
8 | var dfs func(int, int)
9 | dfs = func(index, begin int) {
10 | if index == k {
11 | cur := make([]int, k)
12 | copy(cur, tmp)
13 | res = append(res, cur)
14 | return
15 | }
16 | for i := begin; i <= n+1-k+index; i++ {
17 | tmp[index] = i
18 | dfs(index+1, i+1)
19 | }
20 | }
21 |
22 | dfs(0, 1)
23 | return res
24 | }
25 |
--------------------------------------------------------------------------------
/problems/0022.generate-parentheses/run.go:
--------------------------------------------------------------------------------
1 | package parentheses
2 |
3 | import "fmt"
4 |
5 | func generateParenthesis(n int) []string {
6 |
7 | data := []string{}
8 | dfs("", n, n, &data)
9 | fmt.Println(data)
10 | return data
11 | }
12 |
13 | func dfs(cur string, l, r int, data *[]string) {
14 |
15 | if l == 0 && r == 0 {
16 | *data = append(*data, cur)
17 | return
18 | }
19 | if l > 0 {
20 | dfs(cur+"(", l-1, r, data)
21 | }
22 | if r > 0 && l < r {
23 | dfs(cur+")", l, r-1, data)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0102.binary-tree-level-order-traversal/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0102.binary-tree-level-order-traversal
3 |
4 | ```text
5 | 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
6 |
7 |
8 |
9 | 示例:
10 | 二叉树:[3,9,20,null,null,15,7],
11 |
12 | 3
13 | / \
14 | 9 20
15 | / \
16 | 15 7
17 | 返回其层序遍历结果:
18 |
19 | [
20 | [3],
21 | [9,20],
22 | [15,7]
23 | ]
24 |
25 | 来源:力扣(LeetCode)
26 | 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal
27 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
28 | ```
--------------------------------------------------------------------------------
/problems/0240.search-a-2D-matrix2/run.go:
--------------------------------------------------------------------------------
1 | package matrix2
2 |
3 | func searchMatrix(matrix [][]int, target int) bool {
4 | m := len(matrix)
5 | if m == 0 {
6 | return false
7 | }
8 | n := len(matrix[0])
9 | if n == 0 {
10 | return false
11 | }
12 |
13 | r, c := 0, n-1
14 | for r < m && c >= 0 {
15 | switch {
16 | case matrix[r][c] > target:
17 | c--
18 | case matrix[r][c] < target:
19 | r++
20 | case matrix[r][c] == target:
21 | return true
22 | }
23 | }
24 |
25 | return false
26 | }
27 |
--------------------------------------------------------------------------------
/problems/0033.search-in-rotated-sorted-array/run.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | func search(nums []int, target int) int {
4 | ln := len(nums)
5 | if ln == 0 {
6 | return -1
7 | }
8 |
9 | n := -1
10 |
11 | for i := 0; i < ln; i++ {
12 | if nums[i] > target {
13 | break
14 | } else if nums[i] == target {
15 | n = i
16 | }
17 | }
18 |
19 | for i := ln - 1; i > 0; i-- {
20 | if nums[i] == target {
21 | n = i
22 | }
23 | if i > 0 && nums[i] < nums[i-1] {
24 | break
25 | }
26 | }
27 | return n
28 | }
29 |
--------------------------------------------------------------------------------
/problems/0058.length-of-last-word/run_test.go:
--------------------------------------------------------------------------------
1 | package word
2 |
3 | import "testing"
4 |
5 | type tcheck struct {
6 | input string
7 | out int
8 | }
9 |
10 | func TestRun(t *testing.T) {
11 | ss := []tcheck{
12 | // {"Hello world", 5},
13 | // {"", 0},
14 | // {" ", 0},
15 | {" a", 1},
16 | {"a ", 1},
17 | // {"a b ", 1},
18 | // {" ", 0},
19 | }
20 | for _, s := range ss {
21 |
22 | i := lengthOfLastWord(s.input)
23 |
24 | t.Logf("in:%v, out:%v, expect:%v", s.input, i, s.out)
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/problems/0832.flipping-an-image/run.go:
--------------------------------------------------------------------------------
1 | package image
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | A := [][]int{
7 | []int{1, 1, 0},
8 | []int{1, 0, 1},
9 | []int{0, 0, 0},
10 | }
11 | r := flipAndInvertImage(A)
12 | fmt.Println(r)
13 | }
14 |
15 | func flipAndInvertImage(A [][]int) [][]int {
16 | for _, a := range A {
17 | for i := 0; i < len(a)/2; i++ {
18 | a[i], a[len(a)-i-1] = a[len(a)-i-1], a[i]
19 | }
20 | for i := 0; i < len(a); i++ {
21 | a[i] = a[i] ^ 1
22 | }
23 | }
24 | return A
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0226.invert-binary-tree/run.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for a binary tree node.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *TreeNode
12 | * Right *TreeNode
13 | * }
14 | */
15 | func invertTree(root *structure.TreeNode) *structure.TreeNode {
16 | if root == nil {
17 | return nil
18 | }
19 | root.Left, root.Right = root.Right, root.Left
20 | invertTree(root.Left)
21 | invertTree(root.Right)
22 | return root
23 | }
24 |
--------------------------------------------------------------------------------
/problems/0164.maximum-gap/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0164.maximum-gap
3 |
4 | ```
5 | 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
6 |
7 | 如果数组元素个数小于 2,则返回 0。
8 |
9 | 示例 1:
10 |
11 | 输入: [3,6,9,1]
12 | 输出: 3
13 | 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
14 | 示例 2:
15 |
16 | 输入: [10]
17 | 输出: 0
18 | 解释: 数组元素个数小于 2,因此返回 0。
19 | 说明:
20 |
21 | 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
22 | 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题
23 |
24 | 来源:力扣(LeetCode)
25 | 链接:https://leetcode-cn.com/problems/maximum-gap
26 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
27 |
28 | ```
--------------------------------------------------------------------------------
/problems/0019.remove-nth-node-from-end-of-list/run_test.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 |
10 | n := 2
11 |
12 | l := &ListNode{
13 | 1,
14 | &ListNode{
15 | 2,
16 | &ListNode{
17 | 3,
18 | &ListNode{
19 | 4,
20 | &ListNode{
21 | 5,
22 | &ListNode{},
23 | },
24 | },
25 | },
26 | },
27 | }
28 | s := removeNthFromEnd(l, n)
29 |
30 | for s.Next != nil {
31 | fmt.Println(s.Val)
32 | s = s.Next
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/problems/0090.subsets-ii/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0090.subsets-ii
3 |
4 | ```text
5 | 90. 子集 II
6 |
7 | 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
8 |
9 | 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
10 |
11 |
12 |
13 | 示例 1:
14 |
15 | 输入:nums = [1,2,2]
16 | 输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
17 | 示例 2:
18 |
19 | 输入:nums = [0]
20 | 输出:[[],[0]]
21 |
22 |
23 | 提示:
24 |
25 | 1 <= nums.length <= 10
26 | -10 <= nums[i] <= 10
27 |
28 | 来源:力扣(LeetCode)
29 | 链接:https://leetcode-cn.com/problems/subsets-ii
30 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
31 | ```
--------------------------------------------------------------------------------
/problems/0148.sort-list/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0148.sort-list](https://leetcode.com/problems/sort-list/)
3 |
4 | ```English
5 | Sort a linked list in O(n log n) time using constant space complexity.
6 |
7 | Example 1:
8 |
9 | Input: 4->2->1->3
10 | Output: 1->2->3->4
11 | Example 2:
12 |
13 | Input: -1->5->3->4->0
14 | Output: -1->0->3->4->5
15 | ```
16 |
17 | ```Chinese
18 | 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
19 |
20 | 示例 1:
21 |
22 | 输入: 4->2->1->3
23 | 输出: 1->2->3->4
24 | 示例 2:
25 |
26 | 输入: -1->5->3->4->0
27 | 输出: -1->0->3->4->5
28 | ```
--------------------------------------------------------------------------------
/problems/0142.linked-list-cycle-ii/run.go:
--------------------------------------------------------------------------------
1 | package ii
2 |
3 | import "github.com/itcuihao/leetcode-go/structure"
4 |
5 | func Run() {
6 |
7 | }
8 |
9 | func detectCycle(head *structure.ListNode) *structure.ListNode {
10 | f, s := head, head
11 | isC := false
12 | for f != nil && f.Next != nil {
13 | s = s.Next
14 | f = f.Next.Next
15 | if s == f {
16 | isC = true
17 | break
18 | }
19 | }
20 | if !isC {
21 | return nil
22 | }
23 | s = head
24 | for s != f {
25 | f = f.Next
26 | s = s.Next
27 | }
28 | return f
29 | }
30 |
--------------------------------------------------------------------------------
/problems/0226.invert-binary-tree/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0226.invert-binary-tree
3 |
4 | ```English
5 | Invert a binary tree.
6 |
7 | Example:
8 |
9 | Input:
10 |
11 | 4
12 | / \
13 | 2 7
14 | / \ / \
15 | 1 3 6 9
16 | Output:
17 |
18 | 4
19 | / \
20 | 7 2
21 | / \ / \
22 | 9 6 3 1
23 | Trivia:
24 | This problem was inspired by this original tweet by Max Howell:
25 |
26 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
27 | ```
--------------------------------------------------------------------------------
/problems/0017.letter-combinations-of-a-phone-number/README.md:
--------------------------------------------------------------------------------
1 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
2 |
3 |
4 | A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
5 |
6 |
7 |
8 |
9 |
10 | Example:
11 |
12 | ```
13 | Input: "23"
14 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
15 | ```
16 |
17 |
--------------------------------------------------------------------------------
/problems/0131.palindrome-partitioning/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0131.palindrome-partitioning
3 |
4 | ```text
5 | 131. 分割回文串
6 |
7 |
8 | 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
9 |
10 | 回文串 是正着读和反着读都一样的字符串。
11 |
12 |
13 |
14 | 示例 1:
15 |
16 | 输入:s = "aab"
17 | 输出:[["a","a","b"],["aa","b"]]
18 | 示例 2:
19 |
20 | 输入:s = "a"
21 | 输出:[["a"]]
22 |
23 |
24 | 提示:
25 |
26 | 1 <= s.length <= 16
27 | s 仅由小写英文字母组成
28 |
29 | 来源:力扣(LeetCode)
30 | 链接:https://leetcode-cn.com/problems/palindrome-partitioning
31 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
32 | ```
--------------------------------------------------------------------------------
/problems/0001.two-sum/run_test.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import (
4 | "testing"
5 | "time"
6 | )
7 |
8 | func TestTwoSum(t *testing.T) {
9 | nums := []int{2, 7, 11, 15}
10 | s1 := time.Now()
11 | t.Log(twoSum(nums, 9))
12 | t.Logf("用时:%d", time.Now().Sub(s1).Nanoseconds())
13 |
14 | s2 := time.Now()
15 | t.Log(twoSum2(nums, 13))
16 | t.Logf("用时:%d", time.Now().Sub(s2).Nanoseconds())
17 | }
18 | func TestTwoSum2(t *testing.T) {
19 | // nums := []int{2, 7, 11, 15}
20 | nums := []int{7, 2, 11, 15}
21 | s := findnum(nums, 13)
22 | t.Log(s)
23 | }
24 |
--------------------------------------------------------------------------------
/problems/0033.search-in-rotated-sorted-array/run_test.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 | ts := []struct {
9 | target int
10 | nums []int
11 | out int
12 | }{
13 | {0, []int{4, 5, 6, 7, 0, 1, 2}, 4},
14 | {3, []int{4, 5, 6, 7, 0, 1, 2}, -1},
15 | {2, []int{0, 1, 2}, 2},
16 | {7, []int{4, 5, 6, 7, 0}, 3},
17 | }
18 |
19 | for _, v := range ts {
20 | if v.out == search(v.nums, v.target) {
21 | t.Log("success")
22 | } else {
23 | t.Log("fail")
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/problems/0006.zigzag-conversion/README.md:
--------------------------------------------------------------------------------
1 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
2 |
3 | ```
4 | P A H N
5 | A P L S I I G
6 | Y I R
7 | ```
8 |
9 | And then read line by line: "PAHNAPLSIIGYIR"
10 | Write the code that will take a string and make this conversion given a number of rows:
11 |
12 | ```
13 | string convert(string text, int nRows);
14 | ```
15 |
16 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
--------------------------------------------------------------------------------
/problems/0058.length-of-last-word/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0050.length-of-last-word
3 |
4 | ```English
5 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
6 |
7 | If the last word does not exist, return 0.
8 |
9 | Note: A word is defined as a character sequence consists of non-space characters only.
10 |
11 | Example:
12 |
13 | Input: "Hello World"
14 | Output: 5
15 | ```
16 |
17 | 分析:
18 | 共有多少种情况呢?
19 |
20 | ```
21 | ""
22 | " "
23 | " a"
24 | "a "
25 | "a b "
26 | " "
27 | ```
--------------------------------------------------------------------------------
/problems/0100.same-tree/run_test.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | tree1 := &structure.TreeNode{
10 | Val: 1,
11 | Left: &structure.TreeNode{
12 | Val: 2,
13 | },
14 |
15 | Right: &structure.TreeNode{
16 | Val: 3,
17 | },
18 | }
19 |
20 | tree2 := &structure.TreeNode{
21 | Val: 1,
22 | Left: &structure.TreeNode{
23 | Val: 2,
24 | },
25 |
26 | Right: &structure.TreeNode{
27 | Val: 3,
28 | },
29 | }
30 | isSameTree(tree1, tree2)
31 | }
32 |
--------------------------------------------------------------------------------
/problems/0069.sqrt/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0069.sqrt
3 |
4 | ```English
5 | Implement int sqrt(int x).
6 |
7 | Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
8 |
9 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
10 |
11 | Example 1:
12 |
13 | Input: 4
14 | Output: 2
15 | Example 2:
16 |
17 | Input: 8
18 | Output: 2
19 | Explanation: The square root of 8 is 2.82842..., and since
20 | the decimal part is truncated, 2 is returned.
21 | ```
--------------------------------------------------------------------------------
/problems/0031.next-permutation/run_test.go:
--------------------------------------------------------------------------------
1 | package permutation
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 |
10 | words := [][]int{
11 | {1, 3, 2},
12 | // {1, 2, 3},
13 | // {3, 2, 1},
14 | // {1, 1, 5},
15 | }
16 |
17 | for _, word := range words {
18 | fmt.Println("old:", word)
19 | nextPermutation(word)
20 | fmt.Println("new:", word)
21 | }
22 |
23 | }
24 |
25 | func TestReverse(t *testing.T) {
26 |
27 | words := []int{1, 2, 3}
28 |
29 | reverse(words, 0, 1)
30 |
31 | fmt.Println(words)
32 | }
33 |
--------------------------------------------------------------------------------
/problems/0035.search-insert-position/run.go:
--------------------------------------------------------------------------------
1 | package position
2 |
3 | func searchInsert(nums []int, target int) int {
4 |
5 | // for i := 0; i < len(nums); i++ {
6 | // switch {
7 | // case target < nums[i]:
8 | // return i
9 | // case target > nums[i]:
10 | // if i == len(nums)-1 {
11 | // return i + 1
12 | // }
13 | // default:
14 | // return i
15 | // }
16 | // }
17 | // return 0
18 |
19 | // example:
20 | for i := 0; i < len(nums); i++ {
21 | if target <= nums[i] {
22 | return i
23 | }
24 | }
25 |
26 | return len(nums)
27 | }
28 |
--------------------------------------------------------------------------------
/problems/0338.counting-bits/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0338.counting-bits
3 |
4 | ```text
5 |
6 | 338. 比特位计数
7 |
8 | 给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
9 |
10 | 示例 1:
11 |
12 | 输入: 2
13 | 输出: [0,1,1]
14 | 示例 2:
15 |
16 | 输入: 5
17 | 输出: [0,1,1,2,1,2]
18 | 进阶:
19 |
20 | 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
21 | 要求算法的空间复杂度为O(n)。
22 | 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。
23 |
24 | 来源:力扣(LeetCode)
25 | 链接:https://leetcode-cn.com/problems/counting-bits
26 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
27 | ```
--------------------------------------------------------------------------------
/problems/0542.01-matrix/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0542.01-matrix
3 |
4 | - 难度中等
5 |
6 | ```
7 | 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
8 |
9 | 两个相邻元素间的距离为 1 。
10 |
11 | 示例 1:
12 | 输入:
13 |
14 | 0 0 0
15 | 0 1 0
16 | 0 0 0
17 | 输出:
18 |
19 | 0 0 0
20 | 0 1 0
21 | 0 0 0
22 | 示例 2:
23 | 输入:
24 |
25 | 0 0 0
26 | 0 1 0
27 | 1 1 1
28 | 输出:
29 |
30 | 0 0 0
31 | 0 1 0
32 | 1 2 1
33 | 注意:
34 |
35 | 给定矩阵的元素个数不超过 10000。
36 | 给定矩阵中至少有一个元素是 0。
37 | 矩阵中的元素只在四个方向上相邻: 上、下、左、右。
38 |
39 | 来源:力扣(LeetCode)
40 | 链接:https://leetcode-cn.com/problems/01-matrix
41 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
42 | ```
--------------------------------------------------------------------------------
/problems/0101.symmetric-tree/run.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | )
6 |
7 | func isSymmetric(root *structure.TreeNode) bool {
8 | if root == nil {
9 | return false
10 | }
11 | return sym(root.Left, root.Right)
12 | }
13 |
14 | func sym(left, right *structure.TreeNode) bool {
15 | if left == nil && right == nil {
16 | return true
17 | }
18 | if left == nil || right == nil {
19 | return false
20 | }
21 | if left.Val != right.Val {
22 | return false
23 | }
24 | return sym(left.Left, right.Right) && sym(left.Right, right.Left)
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0112.path-sum/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0112.path-sum
3 |
4 | ```English
5 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
6 |
7 | Note: A leaf is a node with no children.
8 |
9 | Example:
10 |
11 | Given the below binary tree and sum = 22,
12 |
13 | 5
14 | / \
15 | 4 8
16 | / / \
17 | 11 13 4
18 | / \ \
19 | 7 2 1
20 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
21 | ```
22 |
23 | **思路:**
24 |
25 |
26 |
--------------------------------------------------------------------------------
/problems/0347.top-k-frequent-elements/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0347.top-k-frequent-elements
3 |
4 | ```text
5 | 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
6 |
7 |
8 |
9 | 示例 1:
10 |
11 | 输入: nums = [1,1,1,2,2,3], k = 2
12 | 输出: [1,2]
13 | 示例 2:
14 |
15 | 输入: nums = [1], k = 1
16 | 输出: [1]
17 |
18 |
19 | 提示:
20 |
21 | 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
22 | 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
23 | 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
24 | 你可以按任意顺序返回答案。
25 |
26 | 来源:力扣(LeetCode)
27 | 链接:https://leetcode-cn.com/problems/top-k-frequent-elements
28 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
29 | ```
--------------------------------------------------------------------------------
/problems/0470.implement-rand10-using-rand7/run.go:
--------------------------------------------------------------------------------
1 | package rand7
2 |
3 | import (
4 | "math/rand"
5 | "time"
6 | )
7 |
8 | func rand10() int {
9 | // num := 41
10 | // for num >= 40 {
11 | // num = (rand7()-1)*7 + rand7() - 1
12 | // }
13 | // return num%10 + 1
14 |
15 | a := rand7()
16 | b := rand7()
17 |
18 | for {
19 | if b <= 4 {
20 | return a
21 | } else if a <= 4 {
22 | return b + 3
23 | }
24 | a = rand7()
25 | b = rand7()
26 | }
27 | }
28 |
29 | func rand7() int {
30 | rand.Seed(time.Now().UTC().UnixNano())
31 | return rand.Intn(7)
32 | }
33 |
--------------------------------------------------------------------------------
/problems/0020.valid-parentheses/run.go:
--------------------------------------------------------------------------------
1 | package parentheses
2 |
3 | import "fmt"
4 |
5 | func isValid(s string) bool {
6 | st := make([]rune, 0, len(s))
7 |
8 | check := map[string]bool{
9 | "()": true,
10 | "[]": true,
11 | "{}": true,
12 | }
13 |
14 | for _, i := range s {
15 |
16 | if len(st) == 0 {
17 | st = append(st, i)
18 | continue
19 | }
20 |
21 | t := string(st[len(st)-1]) + string(i)
22 |
23 | if _, ok := check[t]; ok {
24 | st = st[:len(st)-1]
25 | continue
26 | }
27 | st = append(st, i)
28 | }
29 |
30 | return len(st) == 0
31 | }
32 |
--------------------------------------------------------------------------------
/problems/0019.remove-nth-node-from-end-of-list/run.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | /**
4 | * Definition for singly-linked list.
5 | * type ListNode struct {
6 | * Val int
7 | * Next *ListNode
8 | * }
9 | */
10 | type ListNode struct {
11 | Val int
12 | Next *ListNode
13 | }
14 |
15 | func removeNthFromEnd(head *ListNode, n int) *ListNode {
16 | p := &ListNode{}
17 | s := p
18 | e := p
19 | p.Next = head
20 | for i := 0; i <= n; i++ {
21 | s = s.Next
22 | }
23 | for s != nil {
24 | s = s.Next
25 | e = e.Next
26 | }
27 | e.Next = e.Next.Next
28 | return p.Next
29 | }
30 |
--------------------------------------------------------------------------------
/problems/0023.merge-k-sorted-lists/run_test.go:
--------------------------------------------------------------------------------
1 | package lists
2 |
3 | import "testing"
4 |
5 | func TestRun(t *testing.T) {
6 | var ls []*ListNode
7 | ls = append(ls, &ListNode{
8 | Val: 1,
9 | Next: &ListNode{
10 | Val: 4,
11 | Next: &ListNode{
12 | Val: 5,
13 | },
14 | },
15 | })
16 | ls = append(ls, &ListNode{
17 | Val: 1,
18 | Next: &ListNode{
19 | Val: 3,
20 | Next: &ListNode{
21 | Val: 4,
22 | },
23 | },
24 | })
25 | ls = append(ls, &ListNode{
26 | Val: 2,
27 | Next: &ListNode{
28 | Val: 6,
29 | },
30 | })
31 | mergeKLists(ls)
32 | }
33 |
--------------------------------------------------------------------------------
/problems/0083.remove-duplicates-from-sorted-list/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0083.remove-duplicates-from-sorted-list](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)
3 |
4 | ```English
5 | Given a sorted linked list, delete all duplicates such that each element appear only once.
6 |
7 | Example 1:
8 |
9 | Input: 1->1->2
10 | Output: 1->2
11 | Example 2:
12 |
13 | Input: 1->1->2->3->3
14 | Output: 1->2->3
15 | ```
16 |
17 | ```Chinese
18 | 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
19 |
20 | 示例 1:
21 |
22 | 输入: 1->1->2
23 | 输出: 1->2
24 | 示例 2:
25 |
26 | 输入: 1->1->2->3->3
27 | 输出: 1->2->3
28 | ```
--------------------------------------------------------------------------------
/problems/0100.same-tree/run.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for a binary tree node.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *TreeNode
12 | * Right *TreeNode
13 | * }
14 | */
15 | func isSameTree(p *structure.TreeNode, q *structure.TreeNode) bool {
16 | if p == nil && q == nil {
17 | return true
18 | }
19 | if p == nil || q == nil {
20 | return false
21 | }
22 | if p.Val != q.Val {
23 | return false
24 | }
25 | return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
26 | }
27 |
--------------------------------------------------------------------------------
/problems/0077.combinations/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0077.combinations](https://leetcode.com/problems/combinations/)
3 |
4 | ```English
5 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
6 |
7 | Example:
8 |
9 | Input: n = 4, k = 2
10 | Output:
11 | [
12 | [2,4],
13 | [3,4],
14 | [2,3],
15 | [1,2],
16 | [1,3],
17 | [1,4],
18 | ]
19 | ```
20 |
21 | ```Chinese
22 | 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
23 |
24 | 示例:
25 |
26 | 输入: n = 4, k = 2
27 | 输出:
28 | [
29 | [2,4],
30 | [3,4],
31 | [2,3],
32 | [1,2],
33 | [1,3],
34 | [1,4],
35 | ]
36 | ```
--------------------------------------------------------------------------------
/problems/0004.median-of-two-sorted-arrays/run.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
4 | if len(nums1) == 0 && len(nums2) == 0 {
5 | return 0.0
6 | }
7 | ln := len(nums1) + len(nums2)
8 | n := make([]int, 0, ln)
9 | n = append(n, nums1...)
10 | n = append(n, nums2...)
11 |
12 | for i := 0; i < ln; i++ {
13 | for j := i + 1; j < ln; j++ {
14 | if n[i] > n[j] {
15 | n[i], n[j] = n[j], n[i]
16 | }
17 | }
18 | }
19 |
20 | if ln%2 == 0 {
21 | return (float64(n[ln/2-1]) + float64(n[ln/2])) / 2
22 | }
23 |
24 | return float64(n[ln/2])
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0011.container-with-most-water/run.go:
--------------------------------------------------------------------------------
1 | package water
2 |
3 | func maxArea(height []int) int {
4 | lh := len(height)
5 | if lh == 0 {
6 | return 0
7 | }
8 | l, r := 0, lh-1
9 |
10 | max := 0
11 |
12 | minf := func(i, j int) int {
13 | if i < j {
14 | return i
15 | }
16 | return j
17 | }
18 | maxf := func(i, j int) int {
19 | if i > j {
20 | return i
21 | }
22 | return j
23 | }
24 | for l < r {
25 | lh, rh := height[l], height[r]
26 | max = maxf(minf(lh, rh)*(r-l), max)
27 |
28 | if lh < rh {
29 | l++
30 | } else {
31 | r--
32 | }
33 | }
34 | return max
35 | }
36 |
--------------------------------------------------------------------------------
/problems/0141.linked-list-cycle/run.go:
--------------------------------------------------------------------------------
1 | package cycle
2 |
3 | import (
4 | "github.com/itcuihao/leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for singly-linked list.
9 | * type ListNode struct {
10 | * Val int
11 | * Next *ListNode
12 | * }
13 | */
14 | func hasCycle(head *structure.ListNode) bool {
15 | if head == nil || head.Next == nil {
16 | return false
17 | }
18 | slow := head
19 | fast := head
20 | for fast != nil && fast.Next != nil {
21 | slow = slow.Next
22 | fast = fast.Next.Next
23 | if slow == fast {
24 | return true
25 | }
26 | }
27 | return false
28 | }
29 |
--------------------------------------------------------------------------------
/problems/0347.top-k-frequent-elements/run_test.go:
--------------------------------------------------------------------------------
1 | package elements
2 |
3 | import (
4 | "container/heap"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | Run()
10 | }
11 |
12 | func TestPriorityQueue(t *testing.T) {
13 | p := PriorityQueue{}
14 | p.Push(&Item{key: 1, count: 1})
15 | p.Push(&Item{key: 1, count: 3})
16 | p.Push(&Item{key: 2, count: 2})
17 | p.Push(&Item{key: 2, count: 1})
18 | a := p.Pop()
19 | t.Log(a)
20 | heap.Push(&p, &Item{key: 3, count: 1})
21 | heap.Push(&p, &Item{key: 4, count: 5})
22 | heap.Push(&p, &Item{key: 5, count: 2})
23 | i := heap.Pop(&p)
24 | t.Log(i)
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0029.divide-two-integers/run.go:
--------------------------------------------------------------------------------
1 | package integers
2 |
3 | func divide(a int, b int) int {
4 | if b == 0 {
5 | return math.MaxInt32
6 | }
7 |
8 | if a == ^math.MaxInt32 && b == -1 {
9 | return ^a
10 | }
11 | ddf, dif := math.Abs(float64(a)), math.Abs(float64(b))
12 | dd, di := int64(ddf), int64(dif)
13 |
14 | ans := 0
15 | for dd >= di {
16 | tmp := 0
17 | for dd >= di< 0 && b > 0) || (a < 0 && b < 0) {
27 | return ans
28 | }
29 | return -ans
30 | }
31 |
--------------------------------------------------------------------------------
/problems/0042.trapping-rain-water/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0042.trapping-rain-
3 |
4 | ```text
5 | 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
6 |
7 |
8 |
9 | 示例 1:
10 |
11 |
12 |
13 | 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
14 | 输出:6
15 | 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
16 | 示例 2:
17 |
18 | 输入:height = [4,2,0,3,2,5]
19 | 输出:9
20 |
21 |
22 | 提示:
23 |
24 | n == height.length
25 | 0 <= n <= 3 * 104
26 | 0 <= height[i] <= 105
27 |
28 | 来源:力扣(LeetCode)
29 | 链接:https://leetcode-cn.com/problems/trapping-rain-water
30 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
31 | ```
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/problems/0424.longest-repeating-character-replacement/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0424.longest-repeating-character-replacement
3 |
4 | ```text
5 | 给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
6 |
7 | 注意:字符串长度 和 k 不会超过 104。
8 |
9 |
10 |
11 | 示例 1:
12 |
13 | 输入:s = "ABAB", k = 2
14 | 输出:4
15 | 解释:用两个'A'替换为两个'B',反之亦然。
16 | 示例 2:
17 |
18 | 输入:s = "AABABBA", k = 1
19 | 输出:4
20 | 解释:
21 | 将中间的一个'A'替换为'B',字符串变为 "AABBBBA"。
22 | 子串 "BBBB" 有最长重复字母, 答案为 4。
23 |
24 | 来源:力扣(LeetCode)
25 | 链接:https://leetcode-cn.com/problems/longest-repeating-character-replacement
26 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
27 | ```
--------------------------------------------------------------------------------
/problems/0021.merge-two-sorted-lists/README.md:
--------------------------------------------------------------------------------
1 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
2 |
3 | Example:
4 |
5 | ```
6 | Input: 1->2->4, 1->3->4
7 | Output: 1->1->2->3->4->4
8 | ```
9 |
10 | ```text
11 | 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
12 |
13 |
14 |
15 | 示例:
16 |
17 | 输入:1->2->4, 1->3->4
18 | 输出:1->1->2->3->4->4
19 |
20 | 来源:力扣(LeetCode)
21 | 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
22 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
23 | ```
24 |
25 | 链表(link)题目,会与同类型的进行联合考察。
--------------------------------------------------------------------------------
/problems/0035.search-insert-position/run_test.go:
--------------------------------------------------------------------------------
1 | package position
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRun(t *testing.T) {
8 |
9 | ts := []struct {
10 | target int
11 | nums []int
12 | out int
13 | }{
14 | {5, []int{1, 3, 5, 6}, 2},
15 | {2, []int{1, 3, 5, 6}, 1},
16 | {7, []int{1, 3, 5, 6}, 4},
17 | {0, []int{1, 3, 5, 6}, 0},
18 | }
19 |
20 | for _, v := range ts {
21 | i := searchInsert(v.nums, v.target)
22 | if v.out != i {
23 | t.Logf("nums: %v, target: %d, output: %v, index: %d", v.nums, v.target, v.out, i)
24 | } else {
25 | t.Log("success")
26 | }
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/problems/0034.find-first-and-last-position-of-element-in-sorted-array/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0034.find-first-and-last-position-of-element-in-sorted-array
3 |
4 | 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
5 |
6 | 你的算法时间复杂度必须是 O(log n) 级别。
7 |
8 | 如果数组中不存在目标值,返回 [-1, -1]。
9 |
10 | 示例 1:
11 |
12 | ```text
13 | 输入: nums = [5,7,7,8,8,10], target = 8
14 | 输出: [3,4]
15 | ```
16 |
17 | 示例 2:
18 |
19 | ```text
20 | 输入: nums = [5,7,7,8,8,10], target = 6
21 | 输出: [-1,-1]
22 | ```
23 |
24 | >来源:力扣(LeetCode)
25 | 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
26 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
--------------------------------------------------------------------------------
/problems/0053.maximum-subarray/README.md:
--------------------------------------------------------------------------------
1 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
2 |
3 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
4 | the contiguous subarray [4,-1,2,1] has the largest sum = 6.
5 |
6 | ```
7 | 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
8 |
9 | 示例:
10 |
11 | 输入: [-2,1,-3,4,-1,2,1,-5,4]
12 | 输出: 6
13 | 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
14 | 进阶:
15 |
16 | 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
17 |
18 | 来源:力扣(LeetCode)
19 | 链接:https://leetcode-cn.com/problems/maximum-subarray
20 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
21 | ```
--------------------------------------------------------------------------------
/problems/0098.validate-binary-search-tree/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0098.validate-binary-search-tree
3 | ```text
4 |
5 | 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
6 |
7 | 假设一个二叉搜索树具有如下特征:
8 |
9 | 节点的左子树只包含小于当前节点的数。
10 | 节点的右子树只包含大于当前节点的数。
11 | 所有左子树和右子树自身必须也是二叉搜索树。
12 |
13 | 示例 1:
14 |
15 | 输入:
16 | 2
17 | / \
18 | 1 3
19 | 输出: true
20 | 示例 2:
21 |
22 | 输入:
23 | 5
24 | / \
25 | 1 4
26 | / \
27 | 3 6
28 | 输出: false
29 | 解释: 输入为: [5,1,4,null,null,3,6]。
30 | 根节点的值为 5 ,但是其右子节点值为 4 。
31 |
32 | 来源:力扣(LeetCode)
33 | 链接:https://leetcode-cn.com/problems/validate-binary-search-tree
34 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
35 | ```
36 |
--------------------------------------------------------------------------------
/problems/0002.add-two-numbers/README.md:
--------------------------------------------------------------------------------
1 | # 2.Add Two Numbers
2 |
3 | ## 题目
4 |
5 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
6 |
7 | You may assume the two numbers do not contain any leading zero, except the number 0 itself.
8 |
9 | Example
10 |
11 | ```Example
12 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
13 | Output: 7 -> 0 -> 8
14 | Explanation: 342 + 465 = 807.
15 | ```
16 |
17 | ## 思路
18 |
19 | 对应节点相加
20 |
21 | 需要考虑几点:
22 |
23 | - 节点位数不对应
24 | - 节点相加进位,节点数+1
25 | - 为0的节点处理
--------------------------------------------------------------------------------
/problems/0112.path-sum/run.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import (
4 | "leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for a binary tree node.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *TreeNode
12 | * Right *TreeNode
13 | * }
14 | */
15 | func hasPathSum(root *structure.TreeNode, sum int) bool {
16 | return dfs(root, sum)
17 | }
18 |
19 | func dfs(root *structure.TreeNode, sum int) bool {
20 | if root == nil {
21 | return false
22 | }
23 |
24 | if root.Left == nil && root.Right == nil {
25 | return sum == root.Val
26 | }
27 | return dfs(root.Left, sum-root.Val) || dfs(root.Right, sum-root.Val)
28 | }
29 |
--------------------------------------------------------------------------------
/problems/0088.merge-sorted-array/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Merge Sorted Array
3 |
4 | ```English
5 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
6 |
7 | Note:
8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
9 | ```
10 |
11 | ```Chinese
12 | 给定两个排序的整数数组nums1和nums2,将nums2合并为nums1作为一个排序数组。
13 |
14 | 注意:
15 | 你可以假设nums1有足够的空间(大小大于或等于m + n)来保存nums2中的其他元素。 nums1和nums2中初始化的元素数量分别为m和n。
16 |
17 | ```
18 |
19 | **步骤**
20 |
21 | 1. 获取n1,n2
22 | 2. 将n2追加到n1
23 | 3. 将n1排序
--------------------------------------------------------------------------------
/problems/0018.4sum/README.md:
--------------------------------------------------------------------------------
1 | Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
2 |
3 |
4 | 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
5 |
6 | Note:
7 |
8 | The solution set must not contain duplicate quadruplets.
9 |
10 | 答案中不可以包含重复的四元组。
11 |
12 | Example:
13 |
14 | Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
15 |
16 | A solution set is:
17 | [
18 | [-1, 0, 0, 1],
19 | [-2, -1, 1, 2],
20 | [-2, 0, 0, 2]
21 | ]
22 |
--------------------------------------------------------------------------------
/problems/0013.roman-to-integer/run.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | // 到着遍历?
4 | func romanToInt(s string) int {
5 | k := 0
6 | ls := len(s)
7 | if ls == 0 {
8 | return k
9 | }
10 | roman := map[byte]int{
11 | 'I': 1,
12 | 'V': 5,
13 | 'X': 10,
14 | 'L': 50,
15 | 'C': 100,
16 | 'D': 500,
17 | 'M': 1000,
18 | }
19 | getRoman := func(b byte) int {
20 | if v, ok := roman[b]; ok {
21 | return v
22 | }
23 | return 0
24 | }
25 |
26 | tn := 0
27 | for i := ls - 1; i >= 0; i-- {
28 | tmp := getRoman(s[i])
29 |
30 | if tmp < tn {
31 | k -= tmp
32 | } else {
33 | k += tmp
34 | }
35 |
36 | tn = tmp
37 |
38 | }
39 | return k
40 | }
41 |
--------------------------------------------------------------------------------
/problems/0082.remove-duplicates-from-sorted-list2/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0082.remove-duplicates-from-sorted-list2](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)
3 |
4 | ```English
5 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
6 |
7 | Example 1:
8 |
9 | Input: 1->2->3->3->4->4->5
10 | Output: 1->2->5
11 | Example 2:
12 |
13 | Input: 1->1->1->2->3
14 | Output: 2->3
15 | ```
16 |
17 | ```Chinese
18 | 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
19 |
20 | 示例 1:
21 |
22 | 输入: 1->2->3->3->4->4->5
23 | 输出: 1->2->5
24 | 示例 2:
25 |
26 | 输入: 1->1->1->2->3
27 | 输出: 2->3
28 | ```
--------------------------------------------------------------------------------
/problems/0094.binary-tree-inorder-traversal/run_test.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | import "testing"
4 |
5 | var tn = &TreeNode{
6 | Val: 1,
7 | Left: &TreeNode{
8 | Val: 2,
9 | Left: &TreeNode{
10 | Val: 4,
11 | },
12 | Right: &TreeNode{
13 | Val: 5,
14 | },
15 | },
16 | Right: &TreeNode{
17 | Val: 3,
18 | Left: &TreeNode{
19 | Val: 6,
20 | },
21 | Right: &TreeNode{
22 | Val: 7,
23 | },
24 | },
25 | }
26 |
27 | func TestInorderTraversal(t *testing.T) {
28 | t.Log(inorderTraversal(tn))
29 | }
30 | func TestInorderFor(t *testing.T) {
31 | t.Log(inorderFor(tn))
32 | }
33 | func TestInorder1(t *testing.T) {
34 | t.Log(inorder(tn))
35 | }
36 |
--------------------------------------------------------------------------------
/problems/0213.house-robber-ii/run.go:
--------------------------------------------------------------------------------
1 | package ii
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | nums := []int{1, 2, 3, 1}
7 | sum := rob(nums)
8 | fmt.Println(sum)
9 | }
10 |
11 | func rob(nums []int) int {
12 | if len(nums) == 0 {
13 | return 0
14 | }
15 | if len(nums) == 1 {
16 | return nums[0]
17 | }
18 | return max(myRob(nums[0:len(nums)-1]), myRob(nums[1:]))
19 | }
20 |
21 | func myRob(nums []int) int {
22 | pre, cur, tmp := 0, 0, 0
23 | for _, num := range nums {
24 | tmp = cur
25 | cur = max(pre+num, cur)
26 | pre = tmp
27 | }
28 | return cur
29 | }
30 |
31 | func max(a, b int) int {
32 | if a > b {
33 | return a
34 | }
35 | return b
36 | }
37 |
--------------------------------------------------------------------------------
/problems/0038.count-and-say/run.go:
--------------------------------------------------------------------------------
1 | package say
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | "strings"
7 | )
8 |
9 | func Run() {
10 | s := countAndSay(6)
11 | fmt.Println(s)
12 | }
13 |
14 | func countAndSay(n int) string {
15 | if n == 1 {
16 | return "1"
17 | }
18 | s := countAndSay(n - 1)
19 | res, start, length := make([]string, n), 0, len(s)
20 | for i := 1; i < length+1; i++ {
21 | if i == length {
22 | res = append(res, strconv.Itoa(i-start), string(s[start]))
23 | continue
24 | }
25 | if s[i] != s[start] {
26 | res = append(res, strconv.Itoa(i-start), string(s[start]))
27 | start = i
28 | }
29 | }
30 | return strings.Join(res, "")
31 | }
32 |
--------------------------------------------------------------------------------
/problems/0354.russian-doll-envelopes/run.go:
--------------------------------------------------------------------------------
1 | package envelopes
2 |
3 | import "sort"
4 |
5 | func Run() {
6 | r := [][]int{
7 | []int{5, 4},
8 | []int{6, 4},
9 | []int{6, 7},
10 | []int{2, 3},
11 | }
12 | me := maxEnvelopes(r)
13 | println(me)
14 | }
15 | func maxEnvelopes(envelopes [][]int) int {
16 | sort.Slice(envelopes, func(i, j int) bool {
17 | a, b := envelopes[i], envelopes[j]
18 | return a[0] < b[0] || a[0] == b[0] && a[1] > b[1]
19 | })
20 |
21 | f := []int{}
22 | for _, e := range envelopes {
23 | h := e[1]
24 | if i := sort.SearchInts(f, h); i < len(f) {
25 | f[i] = h
26 | } else {
27 | f = append(f, h)
28 | }
29 | }
30 | return len(f)
31 | }
32 |
--------------------------------------------------------------------------------
/problems/0016.3sum-closest/run.go:
--------------------------------------------------------------------------------
1 | package closest
2 |
3 | import (
4 | "math"
5 | "sort"
6 | )
7 |
8 | func threeSumClosest(nums []int, target int) int {
9 | ln := len(nums)
10 | if ln < 3 {
11 | return 0
12 | }
13 |
14 | res := nums[0] + nums[1] + nums[ln-1]
15 | sort.Ints(nums)
16 |
17 | for i := 0; i < ln-2; i++ {
18 | l, r := i+1, ln-1
19 | for l < r {
20 | sum := nums[i] + nums[l] + nums[r]
21 | if sum > target {
22 | r--
23 | } else if sum < target {
24 | l++
25 | } else {
26 | return target
27 | }
28 |
29 | if math.Abs(float64(sum-target)) < math.Abs(float64(res-target)) {
30 | res = sum
31 | }
32 | }
33 | }
34 | return res
35 | }
36 |
--------------------------------------------------------------------------------
/problems/0032.longest-valid-parentheses/run.go:
--------------------------------------------------------------------------------
1 | package parentheses
2 |
3 | func longestValidParentheses(s string) int {
4 | l := len(s)
5 | if l <= 0 {
6 | return 0
7 | }
8 | res := 0
9 | start := -1
10 | q := make([]int, 0)
11 |
12 | for i := 0; i < l; i++ {
13 |
14 | if s[i] == '(' {
15 | q = append(q, i)
16 | } else {
17 | if len(q) == 0 {
18 | start = i
19 | } else {
20 | q = q[:len(q)-1]
21 | if len(q) == 0 {
22 | res = max(res, i-start)
23 | } else {
24 | res = max(res, i-q[len(q)-1])
25 | }
26 | }
27 | }
28 | }
29 | return res
30 | }
31 |
32 | func max(a, b int) int {
33 | if a >= b {
34 | return a
35 | }
36 | return b
37 | }
38 |
--------------------------------------------------------------------------------
/problems/0387.first-unique-character-in-a-string/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0387.first-unique-character-in-a-string](https://leetcode.com/problems/first-unique-character-in-a-string/)
3 |
4 | ```English
5 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
6 |
7 | Examples:
8 |
9 | s = "leetcode"
10 | return 0.
11 |
12 | s = "loveleetcode",
13 | return 2.
14 | Note: You may assume the string contain only lowercase letters.
15 | ```
16 |
17 | ```Chinese
18 | 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
19 |
20 | 案例:
21 |
22 | s = "leetcode"
23 | 返回 0.
24 |
25 | s = "loveleetcode",
26 | 返回 2.
27 |
28 |
29 | 注意事项:您可以假定该字符串只包含小写字母。
30 | ```
--------------------------------------------------------------------------------
/problems/0043.multiply-strings/run.go:
--------------------------------------------------------------------------------
1 | package strings
2 |
3 | import "fmt"
4 |
5 | func multiply(num1 string, num2 string) string {
6 | if num1 == "" || num2 == "" {
7 | return "0"
8 | }
9 | l1 := len(num1)
10 | l2 := len(num2)
11 | digits := make([]int, l1+l2)
12 | for i := l1 - 1; i >= 0; i++ {
13 | for j := l2 - 1; j >= 0; j-- {
14 | product := int((num1[i] - '0') * (num2[j] - '0'))
15 | p1 := i + j
16 | p2 := i + j + 1
17 | sum := product + digits[p2]
18 | digits[p1] += sum / 10
19 | digits[p2] = sum % 10
20 | }
21 | }
22 | s := ""
23 | for _, v := range digits {
24 | if !(v == 0 && len(s) == 0) {
25 | s += fmt.Sprint(v)
26 | }
27 | }
28 | return s
29 | }
30 |
--------------------------------------------------------------------------------
/problems/0083.remove-duplicates-from-sorted-list/run.go:
--------------------------------------------------------------------------------
1 | package list
2 |
3 | import "leetcode-go/structure"
4 |
5 | // list: 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
6 | // out: 1 -> 2 -> 3 -> 4 -> 5
7 | // tmp: 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
8 | // p
9 | // time: o(n) space: o(1)
10 | func deleteDuplicates(head *structure.ListNode) *structure.ListNode {
11 | if head == nil || head.Next == nil {
12 | return head
13 | }
14 | tmp := &structure.ListNode{Val: 0}
15 | tmp.Next = head
16 | p := tmp
17 | for p.Next != nil && p.Next.Next != nil {
18 | if p.Next.Val == p.Next.Next.Val {
19 | p.Next = p.Next.Next
20 | } else {
21 | p = p.Next
22 | }
23 | }
24 | return tmp.Next
25 | }
26 |
--------------------------------------------------------------------------------
/problems/0006.zigzag-conversion/run.go:
--------------------------------------------------------------------------------
1 | package conversion
2 |
3 | import "bytes"
4 |
5 | func convert(s string, numRows int) string {
6 | ls := len(s)
7 | if numRows == 1 || ls < numRows {
8 | return s
9 | }
10 |
11 | buf := bytes.Buffer{}
12 |
13 | l := numRows*2 - 2
14 |
15 | for i := 0; i < ls; i += l {
16 | buf.WriteByte(s[i])
17 | }
18 |
19 | for i := 1; i <= numRows-2; i++ {
20 |
21 | buf.WriteByte(s[i])
22 |
23 | for k := l; k-i < len(s); k += l {
24 | buf.WriteByte(s[k-i])
25 | if k+i < ls {
26 | buf.WriteByte(s[k+i])
27 | }
28 | }
29 | }
30 |
31 | for i := numRows - 1; i < ls; i += l {
32 | buf.WriteByte(s[i])
33 | }
34 |
35 | return buf.String()
36 | }
37 |
--------------------------------------------------------------------------------
/problems/0007.reverse-integer/run.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | import (
4 | "math"
5 | "strconv"
6 | )
7 |
8 | func reverse(x int) int {
9 |
10 | s := strconv.Itoa(x)
11 | i := make([]rune, len(s))
12 | l := len(s)
13 |
14 | if x < 0 {
15 | s = s[1:]
16 | }
17 |
18 | for k, v := range s {
19 | i[l-k-1] = v
20 | }
21 |
22 | for k, v := range i {
23 | if v == 0 {
24 | i = i[k+1:]
25 | } else {
26 | break
27 | }
28 | }
29 |
30 | s = string(i)
31 |
32 | j, err := strconv.Atoi(s)
33 | if err != nil {
34 | return 0
35 | }
36 | if x < 0 {
37 | j = ^j + 1 // 按位取反 +1 得到对应负数
38 | }
39 | if j > math.MaxInt32 || j < math.MinInt32 {
40 | return 0
41 | }
42 | return j
43 | }
44 |
--------------------------------------------------------------------------------
/problems/0094.binary-tree-inorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | # [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)
2 |
3 | ## 题干
4 |
5 | ```English
6 | Given a binary tree, return the inorder traversal of its nodes' values.
7 |
8 | For example:
9 |
10 | Given binary tree [1,null,2,3],
11 | 1
12 | \
13 | 2
14 | /
15 | 3
16 | return [1,3,2].
17 |
18 | Note: Recursive solution is trivial, could you do it iteratively?
19 | ```
20 |
21 | ```Chinese
22 | 给定一个二叉树,返回它的中序 遍历。
23 |
24 | 示例:
25 |
26 | 输入: [1,null,2,3]
27 | 1
28 | \
29 | 2
30 | /
31 | 3
32 |
33 | 输出: [1,3,2]
34 | 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
35 | ```
--------------------------------------------------------------------------------
/problems/0235.lowest-common-ancestor-of-a-binary-search-tree/run_test.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | root := structure.BinarySearchTree
10 | q := &structure.TreeNode{
11 | Val: 5,
12 | }
13 | p := &structure.TreeNode{
14 | Val: 3,
15 | }
16 | ancestor := lowestCommonAncestor(root, q, p)
17 |
18 | t.Log(ancestor)
19 | }
20 | func TestStackOver(t *testing.T) {
21 | root := structure.BinarySearchTree
22 | q := &structure.TreeNode{
23 | Val: 5,
24 | }
25 | p := &structure.TreeNode{
26 | Val: 3,
27 | }
28 | ancestor := lowestCommonAncestorStackOverflow(root, p, q)
29 |
30 | t.Log(ancestor)
31 | }
32 |
--------------------------------------------------------------------------------
/problems/0090.subsets-ii/run.go:
--------------------------------------------------------------------------------
1 | package ii
2 |
3 | import (
4 | "fmt"
5 | "sort"
6 | )
7 |
8 | func Run() {
9 | nums := []int{1, 2, 2}
10 | sub := subsetsWithDup(nums)
11 | fmt.Println(sub)
12 | }
13 |
14 | func subsetsWithDup(nums []int) [][]int {
15 | res := make([][]int, 0)
16 | if len(nums) == 0 {
17 | return res
18 | }
19 | sort.Ints(nums)
20 | l := len(nums)
21 | outer:
22 | for mask := 0; mask < 1<>i&1 > 0 {
26 | if i > 0 && mask>>(i-1)&1 == 0 && v == nums[i-1] {
27 | continue outer
28 | }
29 | t = append(t, v)
30 | }
31 | }
32 | res = append(res, t)
33 | }
34 | return res
35 | }
36 |
--------------------------------------------------------------------------------
/problems/0144.binary-tree-preorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | # [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)
2 |
3 | ## 题干
4 |
5 | ```English
6 | Given a binary tree, return the preorder traversal of its nodes' values.
7 |
8 | For example:
9 |
10 | Given binary tree [1,null,2,3],
11 | 1
12 | \
13 | 2
14 | /
15 | 3
16 | return [1,2,3].
17 |
18 | Note: Recursive solution is trivial, could you do it iteratively?
19 | ```
20 |
21 | ```Chinese
22 | 给定一个二叉树,返回它的 前序 遍历。
23 |
24 | 示例:
25 |
26 | 输入: [1,null,2,3]
27 | 1
28 | \
29 | 2
30 | /
31 | 3
32 |
33 | 输出: [1,2,3]
34 | 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
35 | ```
--------------------------------------------------------------------------------
/problems/0024.swap-nodes-in-pairs/run.go:
--------------------------------------------------------------------------------
1 | package pairs
2 |
3 | /**
4 | * Definition for singly-linked list.
5 | * type ListNode struct {
6 | * Val int
7 | * Next *ListNode
8 | * }
9 | */
10 |
11 | type ListNode struct {
12 | Val int
13 | Next *ListNode
14 | }
15 |
16 | // 时间复杂度:0(n)
17 | // 空间复杂度:0(1)
18 | func swapPairs(head *ListNode) *ListNode {
19 | if head == nil || head.Next == nil {
20 | return head
21 | }
22 | tmp := &ListNode{}
23 | tmp.Next = head
24 | l1 := tmp
25 | l2 := head
26 | for l2 != nil && l2.Next != nil {
27 | cur := l2.Next.Next
28 | l1.Next = l2.Next
29 | l2.Next.Next = l2
30 | l2.Next = cur
31 | l1 = l2
32 | l2 = l2.Next
33 | }
34 | return tmp.Next
35 | }
36 |
--------------------------------------------------------------------------------
/problems/0136.single-number/run.go:
--------------------------------------------------------------------------------
1 | package number
2 |
3 | import (
4 | "sort"
5 | )
6 |
7 | func singleNumber(nums []int) int {
8 |
9 | c := make(map[int]int)
10 | for _, num := range nums {
11 | c[num]++
12 | }
13 | for k, v := range c {
14 | if v == 1 {
15 | return k
16 | }
17 | }
18 | return -1
19 | }
20 | func singleNumber1(nums []int) int {
21 |
22 | sort.Ints(nums)
23 |
24 | for i := 0; i < len(nums); i += 2 {
25 | if i+1 >= len(nums) {
26 | return nums[i]
27 | }
28 | if nums[i] != nums[i+1] {
29 | return nums[i]
30 | }
31 | }
32 | return -1
33 | }
34 | func singleNumber2(nums []int) int {
35 |
36 | r := 0
37 | for _, num := range nums {
38 | r ^= num
39 | }
40 | return r
41 | }
42 |
--------------------------------------------------------------------------------
/problems/0019.remove-nth-node-from-end-of-list/README.md:
--------------------------------------------------------------------------------
1 | # 题干
2 |
3 | Given a linked list, remove the n-th node from the end of list and return its head.
4 |
5 | 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
6 |
7 | ## Example:
8 |
9 | ```
10 | Given linked list: 1->2->3->4->5, and n = 2.
11 |
12 | After removing the second node from the end, the linked list becomes 1->2->3->5.
13 | ```
14 |
15 | ## Note:
16 |
17 | Given n will always be valid.
18 |
19 | 给定的 n 保证是有效的。
20 |
21 | ## Follow up:
22 |
23 | Could you do this in one pass?
24 |
25 | 你能尝试使用一趟扫描实现吗?
26 |
27 | ## 思路
28 |
29 | - 利用快慢指针,设置空链表的下一个节点为list
30 |
31 | - 第一个指针先走n步
32 |
33 | - 第一个指针走到最后,第二个指针跟着走
34 |
35 | - 第二个指针走到的位置就是要删除的位置
36 |
37 | - p.next=p.next.next
38 |
39 |
--------------------------------------------------------------------------------
/problems/0046.permute/run.go:
--------------------------------------------------------------------------------
1 | package permute
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | arr := []int{1, 2, 3}
7 | res := permute(arr)
8 | fmt.Println(res)
9 | }
10 |
11 | func permute(nums []int) [][]int {
12 | l := len(nums)
13 | if l == 0 {
14 | return nil
15 | }
16 | res := make([][]int, 0)
17 | used := make([]bool, l)
18 | path := make([]int, l)
19 | df := func(int) {}
20 | df = func(i int) {
21 | if i == l {
22 | res = append(res, append([]int(nil), path...))
23 | return
24 | }
25 | for k, find := range used {
26 | if find {
27 | continue
28 | }
29 | path[i] = nums[k]
30 | used[k] = true
31 | df(i + 1)
32 | used[k] = false
33 | }
34 | }
35 | df(0)
36 | return res
37 | }
38 |
--------------------------------------------------------------------------------
/problems/0435.non-overlapping-intervals/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0435.non-overlapping-intervals
3 |
4 | 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。
5 |
6 | 注意:
7 |
8 | 可以认为区间的终点总是大于它的起点。
9 | 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。
10 |
11 | 示例 1:
12 |
13 | 输入: [ [1,2], [2,3], [3,4], [1,3] ]
14 |
15 | 输出: 1
16 |
17 | 解释: 移除 [1,3] 后,剩下的区间没有重叠。
18 |
19 | 示例 2:
20 |
21 | 输入: [ [1,2], [1,2], [1,2] ]
22 |
23 | 输出: 2
24 |
25 | 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
26 |
27 | 示例 3:
28 |
29 | 输入: [ [1,2], [2,3] ]
30 |
31 | 输出: 0
32 |
33 | 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。
34 |
35 | ```text
36 | 来源:力扣(LeetCode)
37 | 链接:https://leetcode-cn.com/problems/non-overlapping-intervals
38 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
39 | ```
40 |
41 | 利用贪心方式让结尾最小的符合条件的优先保留,供后面的空间有更多的选择。
--------------------------------------------------------------------------------
/problems/0042.trapping-rain-water/run.go:
--------------------------------------------------------------------------------
1 | package water
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | height := []int{4, 2, 0, 3, 2, 5}
7 | t := trap(height)
8 | fmt.Println(t)
9 | }
10 |
11 | func trap(height []int) int {
12 | t := 0
13 | size := len(height)
14 | for i := 1; i < size-1; i++ {
15 | maxL, maxR := 0, 0
16 | for j := i; j >= 0; j-- {
17 | maxL = max(maxL, height[j])
18 | }
19 | for j := i; j < size; j++ {
20 | maxR = max(maxR, height[j])
21 | }
22 | t += min(maxL, maxR) - height[i]
23 | }
24 | return t
25 | }
26 |
27 | func max(i, j int) int {
28 | if i > j {
29 | return i
30 | }
31 | return j
32 | }
33 |
34 | func min(i, j int) int {
35 | if i > j {
36 | return j
37 | }
38 | return i
39 | }
40 |
--------------------------------------------------------------------------------
/problems/0145.binary-tree-postorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | # [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/submissions/)
2 |
3 | ## 题干
4 |
5 | ```English
6 | Given a binary tree, return the postorder traversal of its nodes' values.
7 |
8 | For example:
9 | Given binary tree [1,null,2,3],
10 |
11 | 1
12 | \
13 | 2
14 | /
15 | 3
16 |
17 |
18 | return [3,2,1].
19 |
20 | Note: Recursive solution is trivial, could you do it iteratively?
21 | ```
22 |
23 | ```
24 | 给定一个二叉树,返回它的 后序 遍历。
25 |
26 | 示例:
27 |
28 | 输入: [1,null,2,3]
29 | 1
30 | \
31 | 2
32 | /
33 | 3
34 |
35 | 输出: [3,2,1]
36 | 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
37 | ```
--------------------------------------------------------------------------------
/problems/0032.longest-valid-parentheses/README.md:
--------------------------------------------------------------------------------
1 | # 32. Longest Valid Parentheses
2 |
3 | ## 题目
4 |
5 | - English
6 |
7 | ```
8 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
9 |
10 | Example 1:
11 |
12 | Input: "(()"
13 | Output: 2
14 | Explanation: The longest valid parentheses substring is "()"
15 | Example 2:
16 |
17 | Input: ")()())"
18 | Output: 4
19 | Explanation: The longest valid parentheses substring is "()()"
20 | ```
21 |
22 | - 中文
23 |
24 | ```
25 | 给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
26 |
27 | 示例 1:
28 |
29 | 输入: "(()"
30 | 输出: 2
31 | 解释: 最长有效括号子串为 "()"
32 | 示例 2:
33 |
34 | 输入: ")()())"
35 | 输出: 4
36 | 解释: 最长有效括号子串为 "()()"
37 | ```
38 |
--------------------------------------------------------------------------------
/problems/0145.binary-tree-postorder-traversal/run_test.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | import "testing"
4 |
5 | var tn = &TreeNode{
6 | Val: 1,
7 | Left: &TreeNode{
8 | Val: 2,
9 | Left: &TreeNode{
10 | Val: 4,
11 | },
12 | Right: &TreeNode{
13 | Val: 5,
14 | },
15 | },
16 | Right: &TreeNode{
17 | Val: 3,
18 | Left: &TreeNode{
19 | Val: 6,
20 | },
21 | Right: &TreeNode{
22 | Val: 7,
23 | Left: &TreeNode{
24 | Val: 8,
25 | },
26 | },
27 | },
28 | }
29 |
30 | func TestPostorderTraversal(t *testing.T) {
31 | t.Log(postorderTraversal(tn))
32 | }
33 | func TestPostorderFor(t *testing.T) {
34 | t.Log(portorderFor(tn))
35 | }
36 |
37 | func TestPostorder(t *testing.T) {
38 | t.Log(postorder(tn))
39 | }
40 |
--------------------------------------------------------------------------------
/problems/0030.substrings-with-concatenation-of-all-words/run_test.go:
--------------------------------------------------------------------------------
1 | package words
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 |
10 | // s := "wordgoodgoodgoodbestword"
11 | // words := []string{"word", "good", "best", "good"}
12 | s := "barfoothefoobarman"
13 | words := []string{"foo", "bar"}
14 | // "wordgoodgoodgoodbestword"
15 | // ["word","good","best","word"]
16 | // s := "wordgoodgoodgoodbestword"
17 | // words := []string{"word", "good", "best", "word"}
18 |
19 | i := findSubstring(s, words)
20 | fmt.Println(i)
21 | }
22 |
23 | func TestArray(t *testing.T) {
24 | var a array
25 | words := []string{"a", "b", "c"}
26 | a.permutation(words, 0, len(words))
27 | fmt.Println(a.eles)
28 | }
29 |
--------------------------------------------------------------------------------
/problems/0888.fair-candy-swap/run.go:
--------------------------------------------------------------------------------
1 | package swap
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | A := []int{1, 2, 5}
7 | B := []int{2, 4}
8 | res := fairCandySwap(A, B)
9 | fmt.Println(res)
10 | }
11 |
12 | func fairCandySwap(A []int, B []int) []int {
13 | aSum := sum(A)
14 | bSum := sum(B)
15 | diff := aSum - bSum
16 |
17 | res := make([]int, 2)
18 | checkB := make(map[int]bool, len(B))
19 | for _, i := range B {
20 | checkB[i] = true
21 | }
22 | for i := 0; i < len(A); i++ {
23 | res[0] = A[i]
24 | res[1] = A[i] - diff/2
25 | if checkB[res[1]] {
26 | return res
27 | }
28 | }
29 | return nil
30 | }
31 |
32 | func sum(arr []int) int {
33 | s := 0
34 | for _, i := range arr {
35 | s += i
36 | }
37 | return s
38 | }
39 |
--------------------------------------------------------------------------------
/problems/0226.invert-binary-tree/run_test.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | tree := &structure.TreeNode{
10 | Val: 5,
11 | Left: &structure.TreeNode{
12 | Val: 4,
13 | Left: &structure.TreeNode{
14 | Val: 11,
15 | Left: &structure.TreeNode{
16 | Val: 7,
17 | },
18 | Right: &structure.TreeNode{
19 | Val: 2,
20 | },
21 | },
22 | },
23 |
24 | Right: &structure.TreeNode{
25 | Val: 8,
26 | Left: &structure.TreeNode{
27 | Val: 13,
28 | },
29 | Right: &structure.TreeNode{
30 | Val: 4,
31 | Right: &structure.TreeNode{
32 | Val: 1,
33 | },
34 | },
35 | },
36 | }
37 | invertTree(tree)
38 | }
39 |
--------------------------------------------------------------------------------
/problems/0236.lowest-common-ancestor-of-a-binary-tree/run.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for TreeNode.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *ListNode
12 | * Right *ListNode
13 | * }
14 | */
15 | func lowestCommonAncestor(root, p, q *structure.TreeNode) *structure.TreeNode {
16 | if root == nil {
17 | return nil
18 | }
19 | if root.Val == p.Val || root.Val == q.Val {
20 | return root
21 | }
22 |
23 | left := lowestCommonAncestor(root.Left, p, q)
24 | right := lowestCommonAncestor(root.Right, p, q)
25 |
26 | switch {
27 | case left == nil:
28 | return right
29 | case right == nil:
30 | return left
31 | }
32 |
33 | return root
34 | }
35 |
--------------------------------------------------------------------------------
/problems/0112.path-sum/run_test.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import (
4 | "leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | func TestRun(t *testing.T) {
9 | tree := &structure.TreeNode{
10 | Val: 5,
11 | Left: &structure.TreeNode{
12 | Val: 4,
13 | Left: &structure.TreeNode{
14 | Val: 11,
15 | Left: &structure.TreeNode{
16 | Val: 7,
17 | },
18 | Right: &structure.TreeNode{
19 | Val: 2,
20 | },
21 | },
22 | },
23 |
24 | Right: &structure.TreeNode{
25 | Val: 8,
26 | Left: &structure.TreeNode{
27 | Val: 13,
28 | },
29 | Right: &structure.TreeNode{
30 | Val: 4,
31 | Right: &structure.TreeNode{
32 | Val: 1,
33 | },
34 | },
35 | },
36 | }
37 | f := hasPathSum(tree, 22)
38 | t.Log(f)
39 | }
40 |
--------------------------------------------------------------------------------
/problems/0164.maximum-gap/run.go:
--------------------------------------------------------------------------------
1 | package gap
2 |
3 | func maximumGap(nums []int) int {
4 | if len(nums) < 2 {
5 | return 0
6 | }
7 | quickSort(nums, 0, len(nums)-1)
8 | res := 0
9 | for i := 0; i < len(nums)-1; i++ {
10 | sub := nums[i+1] - nums[i]
11 | if sub > res {
12 | res = sub
13 | }
14 | }
15 | return res
16 | }
17 |
18 | func partition(a []int, l, h int) int {
19 | pivot := a[h]
20 | i := l - 1
21 | for j := l; j < h; j++ {
22 | if a[j] < pivot {
23 | i++
24 | a[j], a[i] = a[i], a[j]
25 | }
26 | }
27 | a[i+1], a[h] = a[h], a[i+1]
28 | return i + 1
29 | }
30 |
31 | func quickSort(a []int, l, h int) {
32 | if l >= h {
33 | return
34 | }
35 | p := partition(a, l, h)
36 | quickSort(a, l, p-1)
37 | quickSort(a, p+1, h)
38 | }
39 |
--------------------------------------------------------------------------------
/problems/0026.remove-duplicates-from-sorted-array/README.md:
--------------------------------------------------------------------------------
1 | Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
2 |
3 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
4 |
5 | Example:
6 |
7 | ```
8 | Given nums = [1,1,2],
9 |
10 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
11 | It doesn't matter what you leave beyond the new length.
12 | ```
13 |
14 | ```
15 | 给定一个有序数组,删除重复内容,使每个元素只出现一次并返回新的长度。
16 |
17 | 不要为其他数组分配额外空间,您必须通过在O(1)额外内存中就地修改输入数组来实现此目的。
18 |
19 | 例:
20 |
21 | 给定nums = [1,1,2],
22 |
23 | 你的函数应该返回length = 2,num的前两个元素分别是1和2。
24 | 无论你在新的长度以外留下什么都没有关系。
25 | ```
--------------------------------------------------------------------------------
/problems/0424.longest-repeating-character-replacement/run.go:
--------------------------------------------------------------------------------
1 | package replacement
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | s := "AABABBA"
7 | k := 1
8 | c := characterReplacement(s, k)
9 | fmt.Println(c)
10 | }
11 |
12 | func characterReplacement(s string, k int) int {
13 | num := make(map[uint8]int, 26)
14 | ls := len(s)
15 | maxn := 0
16 | left := 0
17 | right := 0
18 | for right < ls {
19 | indexRight := s[right] - 'A'
20 | num[indexRight]++
21 | maxn = max(maxn, num[indexRight])
22 |
23 | if right-left+1-maxn > k {
24 | indexLeft := s[left] - 'A'
25 | num[indexLeft]--
26 | left++
27 | }
28 | right++
29 | }
30 | return right - left
31 | }
32 |
33 | func max(a, b int) int {
34 | if a > b {
35 | return a
36 | }
37 | return b
38 | }
39 |
--------------------------------------------------------------------------------
/problems/0039.combination-sum/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0039.combination-sum
3 |
4 |
5 | ```text
6 | 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
7 |
8 | candidates 中的数字可以无限制重复被选取。
9 |
10 | 说明:
11 |
12 | 所有数字(包括 target)都是正整数。
13 | 解集不能包含重复的组合。
14 | 示例 1:
15 |
16 | 输入:candidates = [2,3,6,7], target = 7,
17 | 所求解集为:
18 | [
19 | [7],
20 | [2,2,3]
21 | ]
22 | 示例 2:
23 |
24 | 输入:candidates = [2,3,5], target = 8,
25 | 所求解集为:
26 | [
27 | [2,2,2,2],
28 | [2,3,3],
29 | [3,5]
30 | ]
31 |
32 |
33 | 提示:
34 |
35 | 1 <= candidates.length <= 30
36 | 1 <= candidates[i] <= 200
37 | candidate 中的每个元素都是独一无二的。
38 | 1 <= target <= 500
39 |
40 | 来源:力扣(LeetCode)
41 | 链接:https://leetcode-cn.com/problems/combination-sum
42 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
43 | ```
--------------------------------------------------------------------------------
/problems/0354.russian-doll-envelopes/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0354.russian-doll-envelopes
3 |
4 | ```text
5 | 354. 俄罗斯套娃信封问题
6 |
7 | 给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。
8 |
9 | 当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
10 |
11 | 请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
12 |
13 | 注意:不允许旋转信封。
14 |
15 |
16 | 示例 1:
17 |
18 | 输入:envelopes = [[5,4],[6,4],[6,7],[2,3]]
19 | 输出:3
20 | 解释:最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
21 | 示例 2:
22 |
23 | 输入:envelopes = [[1,1],[1,1],[1,1]]
24 | 输出:1
25 |
26 |
27 | 提示:
28 |
29 | 1 <= envelopes.length <= 5000
30 | envelopes[i].length == 2
31 | 1 <= wi, hi <= 104
32 |
33 | 来源:力扣(LeetCode)
34 | 链接:https://leetcode-cn.com/problems/russian-doll-envelopes
35 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
36 |
37 | ```
--------------------------------------------------------------------------------
/problems/0100.same-tree/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0100.same-tree
3 |
4 | ```English
5 | Given two binary trees, write a function to check if they are the same or not.
6 |
7 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
8 |
9 | Example 1:
10 |
11 | Input: 1 1
12 | / \ / \
13 | 2 3 2 3
14 |
15 | [1,2,3], [1,2,3]
16 |
17 | Output: true
18 | Example 2:
19 |
20 | Input: 1 1
21 | / \
22 | 2 2
23 |
24 | [1,2], [1,null,2]
25 |
26 | Output: false
27 | Example 3:
28 |
29 | Input: 1 1
30 | / \ / \
31 | 2 1 1 2
32 |
33 | [1,2,1], [1,1,2]
34 |
35 | Output: false
36 | ```
--------------------------------------------------------------------------------
/problems/0455.assign-cookies/run.go:
--------------------------------------------------------------------------------
1 | package cookies
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | g := []int{1, 2, 3}
7 | s := []int{1, 1}
8 | res := findContentChildren(g, s)
9 | fmt.Println(res)
10 | }
11 |
12 | func findContentChildren(g []int, s []int) int {
13 | children := bubbleSort(g)
14 | cookies := bubbleSort(s)
15 | child, cookie := 0, 0
16 | for child < len(children) && cookie < len(cookies) {
17 | if children[child] <= cookies[cookie] {
18 | child++
19 | }
20 | cookie++
21 | }
22 | return child
23 | }
24 |
25 | func bubbleSort(arr []int) []int {
26 | l := len(arr)
27 | for i := 0; i < l; i++ {
28 | for j := 0; j < l-1-i; j++ {
29 | if arr[j] > arr[j+1] {
30 | arr[j], arr[j+1] = arr[j+1], arr[j]
31 | }
32 | }
33 | }
34 | return arr
35 | }
36 |
--------------------------------------------------------------------------------
/problems/0213.house-robber-ii/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0213.house-robber-ii
3 |
4 |
5 | ```text
6 | 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
7 |
8 | 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。
9 |
10 |
11 |
12 | 示例 1:
13 |
14 | 输入:nums = [2,3,2]
15 | 输出:3
16 | 解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
17 | 示例 2:
18 |
19 | 输入:nums = [1,2,3,1]
20 | 输出:4
21 | 解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
22 | 偷窃到的最高金额 = 1 + 3 = 4 。
23 | 示例 3:
24 |
25 | 输入:nums = [0]
26 | 输出:0
27 |
28 |
29 | 提示:
30 |
31 | 1 <= nums.length <= 100
32 | 0 <= nums[i] <= 1000
33 |
34 | 来源:力扣(LeetCode)
35 | 链接:https://leetcode-cn.com/problems/house-robber-ii
36 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
37 | ```
38 |
39 | 动态规划
--------------------------------------------------------------------------------
/problems/0128.longest-consecutive-sequence/run.go:
--------------------------------------------------------------------------------
1 | package sequence
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | //nums := []int{100, 1, 200, 2, 3}
7 | nums := []int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}
8 | l := longestConsecutive(nums)
9 | fmt.Println(l)
10 | }
11 |
12 | func longestConsecutive(nums []int) int {
13 | length := 0
14 | if len(nums) == 0 {
15 | return length
16 | }
17 | numsMap := make(map[int]bool, len(nums))
18 | for _, num := range nums {
19 | numsMap[num] = true
20 | }
21 | for num := range numsMap {
22 | if numsMap[num-1] {
23 | continue
24 | }
25 | curLength := 1
26 | curNum := num
27 | for numsMap[curNum+1] {
28 | curLength++
29 | curNum++
30 | }
31 | if length < curLength {
32 | length = curLength
33 | }
34 | }
35 | return length
36 | }
37 |
--------------------------------------------------------------------------------
/problems/0136.single-number/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0136.single-number
3 |
4 | ```English
5 | Given a non-empty array of integers, every element appears twice except for one. Find that single one.
6 |
7 | Note:
8 |
9 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
10 |
11 | Example 1:
12 |
13 | Input: [2,2,1]
14 | Output: 1
15 | Example 2:
16 |
17 | Input: [4,1,2,1,2]
18 | Output: 4
19 | ```
20 |
21 | ```中文
22 | 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
23 |
24 | 说明:
25 |
26 | 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
27 |
28 | 示例 1:
29 |
30 | 输入: [2,2,1]
31 | 输出: 1
32 | 示例 2:
33 |
34 | 输入: [4,1,2,1,2]
35 | 输出: 4
36 | ```
37 |
38 | **三种方法:**
39 |
40 | 1. 利用map,返回value为1的key;
41 | 2. 既然都是数字,排序后,前一个元素与后一个元素不等,则是只出现一次的数字;
42 | 3. 利用异或,最后的元素就是只出现一次的元素。
--------------------------------------------------------------------------------
/problems/0050.pow/run.go:
--------------------------------------------------------------------------------
1 | package pow
2 |
3 | import (
4 | "math"
5 | )
6 |
7 | // 递归
8 | func MyPow(x float64, n int) float64 {
9 |
10 | if n > 0 {
11 | return pow(x, n)
12 | }
13 |
14 | return 1.0 / pow(x, n)
15 | }
16 |
17 | func pow(x float64, n int) float64 {
18 | if n == 0 {
19 | return 1
20 | }
21 | y := pow(x, n/2)
22 | if n%2 == 0 {
23 | return y * y
24 | }
25 | return y * y * x
26 | }
27 |
28 | // 第二种方法,非递归
29 | func MyPow2(x float64, n int) float64 {
30 | if n == 0 {
31 | return 1
32 | }
33 | res := float64(1)
34 |
35 | // 取绝对值
36 | absf := math.Abs(float64(n))
37 | abs := int64(absf)
38 |
39 | for abs > 0 {
40 |
41 | if abs%2 != 0 {
42 | res *= x
43 | }
44 | x *= x
45 |
46 | abs /= 2
47 | }
48 |
49 | if n < 0 {
50 | return 1.0 / res
51 | }
52 | return res
53 | }
54 |
--------------------------------------------------------------------------------
/problems/0064.minimum-path-sum/run.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | grid := [][]int{{1, 3, 1}, {1, 50, 1}, {40, 2, 1}}
7 | m := minPathSum(grid)
8 | fmt.Println(m)
9 | }
10 |
11 | func minPathSum(grid [][]int) int {
12 | if len(grid) == 0 {
13 | return 0
14 | }
15 | r := len(grid)
16 | c := len(grid[0])
17 | min := func(m, n int) int {
18 | if m > n {
19 | return n
20 | }
21 | return m
22 | }
23 | for i := 0; i < r; i++ {
24 | for j := 0; j < c; j++ {
25 | if i == j && i == 0 {
26 | continue
27 | }
28 | if i == 0 {
29 | grid[i][j] += grid[i][j-1]
30 | continue
31 | }
32 | if j == 0 {
33 | grid[i][j] += grid[i-1][j]
34 | continue
35 | }
36 | grid[i][j] += min(grid[i][j-1], grid[i-1][j])
37 | }
38 | }
39 | return grid[r-1][c-1]
40 | }
41 |
--------------------------------------------------------------------------------
/problems/0303.range-sum-query-immutable/run.go:
--------------------------------------------------------------------------------
1 | package immutable
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | nums := []int{-2, 0, 3, -5, 2, -1}
7 | c := Constructor(nums)
8 | fmt.Println(c.nums)
9 | sub := c.SumRange(0, 2)
10 | fmt.Println(sub)
11 | sub = c.SumRange(2, 5)
12 | fmt.Println(sub)
13 | sub = c.SumRange(0, 5)
14 | fmt.Println(sub)
15 | }
16 |
17 | type NumArray struct {
18 | nums []int
19 | }
20 |
21 | func Constructor(nums []int) NumArray {
22 | return NumArray{nums: nums}
23 | }
24 |
25 | func (this *NumArray) SumRange(i int, j int) int {
26 | sum := 0
27 | for ; i <= j; i++ {
28 | sum += this.nums[i]
29 | }
30 | return sum
31 | }
32 |
33 | /**
34 | * Your NumArray object will be instantiated and called as such:
35 | * obj := Constructor(nums);
36 | * param_1 := obj.SumRange(i,j);
37 | */
38 |
--------------------------------------------------------------------------------
/problems/0039.combination-sum/run.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | candidates := []int{2, 3, 6, 7}
7 | target := 7
8 | sums := combinationSum(candidates, target)
9 | fmt.Println(sums)
10 | }
11 |
12 | func combinationSum(candidates []int, target int) [][]int {
13 | res := make([][]int, 0)
14 | comb := make([]int, 0)
15 | dfs := func(target, index int) {}
16 | dfs = func(target, index int) {
17 | if index == len(candidates) {
18 | return
19 | }
20 | if target == 0 {
21 | res = append(res, append([]int(nil), comb...))
22 | return
23 | }
24 | dfs(target, index+1)
25 | if target-candidates[index] >= 0 {
26 | comb = append(comb, candidates[index])
27 | dfs(target-candidates[index], index)
28 | comb = comb[:len(comb)-1]
29 | }
30 | }
31 | dfs(target, 0)
32 | return res
33 | }
34 |
--------------------------------------------------------------------------------
/problems/0025.reverse-nodes-in-k-group/run_test.go:
--------------------------------------------------------------------------------
1 | package pairs
2 |
3 | import (
4 | "github.com/itcuihao/leetcode-go/structure"
5 | "testing"
6 | )
7 |
8 | var ls = &structure.ListNode{
9 | Val: 1,
10 | Next: &structure.ListNode{
11 | Val: 2,
12 | Next: &structure.ListNode{
13 | Val: 3,
14 | Next: &structure.ListNode{
15 | Val: 4,
16 | Next: &structure.ListNode{
17 | Val: 5,
18 | },
19 | },
20 | },
21 | },
22 | }
23 |
24 | func TestRun(t *testing.T) {
25 | l := reverseKGroup(ls, 2)
26 | l.Print()
27 | }
28 |
29 | func TestRun2(t *testing.T) {
30 | l := reverseKGroup2(ls, 2)
31 | l.Print()
32 | }
33 |
34 | func TestReverse(t *testing.T) {
35 | node := ls
36 | k := 3
37 | for i := 0; i < k; i++ {
38 | if node != nil {
39 | node = node.Next
40 | }
41 | }
42 | l := reverse(ls, node)
43 | l.Print()
44 | }
45 |
--------------------------------------------------------------------------------
/problems/0031.next-permutation/run.go:
--------------------------------------------------------------------------------
1 | package permutation
2 |
3 | func nextPermutation(nums []int) {
4 | if nums == nil || len(nums) == 0 {
5 | return
6 | }
7 |
8 | ln := len(nums)
9 | firstSmall := -1
10 | for i := ln - 2; i >= 0; i-- {
11 | if nums[i] < nums[i+1] {
12 | firstSmall = i
13 | break
14 | }
15 | }
16 |
17 | if firstSmall == -1 {
18 | reverse(nums, 0, ln-1)
19 | return
20 | }
21 |
22 | firstLarge := -1
23 | for i := ln - 1; i > firstSmall; i-- {
24 | if nums[i] > nums[firstSmall] {
25 | firstLarge = i
26 | break
27 | }
28 | }
29 |
30 | nums[firstSmall], nums[firstLarge] = nums[firstLarge], nums[firstSmall]
31 | reverse(nums, firstSmall+1, ln-1)
32 | return
33 | }
34 |
35 | func reverse(nums []int, l, r int) {
36 | for ; l < r; l, r = l+1, r-1 {
37 | nums[l], nums[r] = nums[r], nums[l]
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/problems/0304.range-sum-query-2d-immutable/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0304.range-sum-query-2d-immutable
3 |
4 | 
5 |
6 | ```text
7 | 304. 二维区域和检索 - 矩阵不可变
8 |
9 | 给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2) 。
10 |
11 |
12 | 上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。
13 |
14 |
15 |
16 | 示例:
17 |
18 | 给定 matrix = [
19 | [3, 0, 1, 4, 2],
20 | [5, 6, 3, 2, 1],
21 | [1, 2, 0, 1, 5],
22 | [4, 1, 0, 1, 7],
23 | [1, 0, 3, 0, 5]
24 | ]
25 |
26 | sumRegion(2, 1, 4, 3) -> 8
27 | sumRegion(1, 1, 2, 2) -> 11
28 | sumRegion(1, 2, 2, 4) -> 12
29 |
30 |
31 | 提示:
32 |
33 | 你可以假设矩阵不可变。
34 | 会多次调用 sumRegion 方法。
35 | 你可以假设 row1 ≤ row2 且 col1 ≤ col2 。
36 |
37 | 来源:力扣(LeetCode)
38 | 链接:https://leetcode-cn.com/problems/range-sum-query-2d-immutable
39 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
40 | ```
--------------------------------------------------------------------------------
/problems/0002.add-two-numbers/run_test.go:
--------------------------------------------------------------------------------
1 | package numbers
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | // go test -v -test.run TestLn
9 | func TestLn(t *testing.T) {
10 | s := []int{0}
11 | ln := makeListNode(s)
12 | if ln == nil {
13 | t.Error("nil")
14 | }
15 |
16 | fmt.Println("ln:")
17 |
18 | printLN(ln)
19 | }
20 |
21 | func TestRun(t *testing.T) {
22 | s1 := []int{2, 4, 5}
23 | s2 := []int{5, 6, 4}
24 |
25 | // s1 := []int{2, 4, 3}
26 | // s2 := []int{5, 6, 4}
27 |
28 | // s1 := []int{1, 8}
29 | // s2 := []int{0}
30 |
31 | // s1 := []int{5}
32 | // s2 := []int{5}
33 |
34 | // s1 := []int{9}
35 | // s2 := []int{9}
36 |
37 | l1 := makeListNode(s1)
38 | l2 := makeListNode(s2)
39 |
40 | ln := addTwoNumbers(l1, l2)
41 | if ln == nil {
42 | t.Error("nil")
43 | }
44 |
45 | fmt.Println("ln:")
46 |
47 | printLN(ln)
48 | }
49 |
--------------------------------------------------------------------------------
/problems/0092.reverse-linked-list-2/run.go:
--------------------------------------------------------------------------------
1 | package reverse
2 |
3 | import "github.com/itcuihao/leetcode-go/structure"
4 |
5 | func Run() {
6 |
7 | }
8 |
9 | /**
10 | * Definition for singly-linked list.
11 | * type ListNode struct {
12 | * Val int
13 | * Next *ListNode
14 | * }
15 | */
16 | func reverseBetween(head *structure.ListNode, m int, n int) *structure.ListNode {
17 | if head == nil || m >= n {
18 | return head
19 | }
20 | newHead := &structure.ListNode{Val: 0, Next: head}
21 | pre := newHead
22 | for count := 0; pre.Next != nil && count < m-1; count++ {
23 | pre = pre.Next
24 | }
25 | if pre.Next == nil {
26 | return head
27 | }
28 | cur := pre.Next
29 | for i := 0; i < n-m; i++ {
30 | tmp := pre.Next
31 | pre.Next = cur.Next
32 | cur.Next = cur.Next.Next
33 | pre.Next.Next = tmp
34 | }
35 | return newHead.Next
36 | }
37 |
--------------------------------------------------------------------------------
/problems/0455.assign-cookies/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0455.assign-cookies
3 |
4 | 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
5 |
6 | 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
7 |
8 |
9 | 示例 1:
10 |
11 | 输入: g = [1,2,3], s = [1,1]
12 | 输出: 1
13 | 解释:
14 | 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
15 | 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
16 | 所以你应该输出1。
17 | 示例 2:
18 |
19 | 输入: g = [1,2], s = [1,2,3]
20 | 输出: 2
21 | 解释:
22 | 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
23 | 你拥有的饼干数量和尺寸都足以让所有孩子满足。
24 | 所以你应该输出2.
25 |
26 |
27 | 提示:
28 |
29 | 1 <= g.length <= 3 * 104
30 | 0 <= s.length <= 3 * 104
31 | 1 <= g[i], s[j] <= 231 - 1
32 |
33 | ```text
34 | 来源:力扣(LeetCode)
35 | 链接:https://leetcode-cn.com/problems/assign-cookies
36 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
37 | ```
38 |
39 | 贪心算法,即每次操作都是局部最优的,从而达到全局最优。
--------------------------------------------------------------------------------
/problems/0169.majority-element/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0169.majority-element
3 |
4 | ```English
5 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
6 |
7 | You may assume that the array is non-empty and the majority element always exist in the array.
8 |
9 | Example 1:
10 |
11 | Input: [3,2,3]
12 | Output: 3
13 | Example 2:
14 |
15 | Input: [2,2,1,1,1,2,2]
16 | Output: 2
17 | ```
18 |
19 | ```Chinese
20 | 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
21 |
22 | 你可以假设数组是非空的,并且给定的数组总是存在众数。
23 |
24 | 示例 1:
25 |
26 | 输入: [3,2,3]
27 | 输出: 3
28 | 示例 2:
29 |
30 | 输入: [2,2,1,1,1,2,2]
31 | 输出: 2
32 | ```
33 |
34 | **分析**
35 |
36 | 1. 利用map,循环时重复的key,将value++ ,再次循环map,将value>len(n)/2的key返回。
37 | 2. 既然众数是超过数组一半的数,那就将数组排序,返回中间值,该值就是众数。
38 |
39 | **总结**
40 |
41 | 遇到数组的题目可以考虑排序后有序数组可不可以有效的解决问题
42 |
43 | 例如:136题也是类似
--------------------------------------------------------------------------------
/problems/0101.symmetric-tree/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0101.symmetric-tree](https://leetcode.com/problems/symmetric-tree/)
3 |
4 | ```English
5 | ****Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
6 |
7 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
8 |
9 | 1
10 | / \
11 | 2 2
12 | / \ / \
13 | 3 4 4 3
14 | But the following [1,2,2,null,3,null,3] is not:
15 | 1
16 | / \
17 | 2 2
18 | \ \
19 | 3 3
20 | Note:
21 | Bonus points if you could solve it both recursively and iteratively.
22 | ```
23 |
24 | ```Chinese
25 | 给定一个二叉树,检查它是否是镜像对称的。
26 |
27 | 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
28 |
29 | 1
30 | / \
31 | 2 2
32 | / \ / \
33 | 3 4 4 3
34 | 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
35 |
36 | 1
37 | / \
38 | 2 2
39 | \ \
40 | 3 3
41 | 说明:
42 |
43 | 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
44 | ```
--------------------------------------------------------------------------------
/problems/0617.merge-two-binary-trees/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0617.merge-two-binary-trees
3 |
4 | ```text
5 | 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
6 |
7 | 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
8 |
9 | 示例 1:
10 |
11 | 输入:
12 | Tree 1 Tree 2
13 | 1 2
14 | / \ / \
15 | 3 2 1 3
16 | / \ \
17 | 5 4 7
18 | 输出:
19 | 合并后的树:
20 | 3
21 | / \
22 | 4 5
23 | / \ \
24 | 5 4 7
25 | 注意: 合并必须从两个树的根节点开始。
26 |
27 | 来源:力扣(LeetCode)
28 | 链接:https://leetcode-cn.com/problems/merge-two-binary-trees
29 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
30 | ```
--------------------------------------------------------------------------------
/problems/0832.flipping-an-image/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0832.flipping-an-image
3 |
4 | ```text
5 |
6 | 给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
7 |
8 | 水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
9 |
10 | 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
11 |
12 |
13 |
14 | 示例 1:
15 |
16 | 输入:[[1,1,0],[1,0,1],[0,0,0]]
17 | 输出:[[1,0,0],[0,1,0],[1,1,1]]
18 | 解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
19 | 然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
20 | 示例 2:
21 |
22 | 输入:[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
23 | 输出:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
24 | 解释:首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
25 | 然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
26 |
27 |
28 | 提示:
29 |
30 | 1 <= A.length = A[0].length <= 20
31 | 0 <= A[i][j] <= 1
32 |
33 | 来源:力扣(LeetCode)
34 | 链接:https://leetcode-cn.com/problems/flipping-an-image
35 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
36 | ```
37 |
--------------------------------------------------------------------------------
/problems/0035.search-insert-position/README.md:
--------------------------------------------------------------------------------
1 | # 35. Search Insert Position
2 |
3 | ## 题目
4 |
5 | - English
6 |
7 | ```
8 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
9 |
10 | You may assume no duplicates in the array.
11 |
12 | Example 1:
13 |
14 | Input: [1,3,5,6], 5
15 | Output: 2
16 | Example 2:
17 |
18 | Input: [1,3,5,6], 2
19 | Output: 1
20 | Example 3:
21 |
22 | Input: [1,3,5,6], 7
23 | Output: 4
24 | Example 4:
25 |
26 | Input: [1,3,5,6], 0
27 | Output: 0
28 | ```
29 |
30 | - 中文
31 |
32 | ```
33 | 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
34 |
35 | 你可以假设数组中无重复元素。
36 |
37 | 示例 1:
38 |
39 | 输入: [1,3,5,6], 5
40 | 输出: 2
41 | 示例 2:
42 |
43 | 输入: [1,3,5,6], 2
44 | 输出: 1
45 | 示例 3:
46 |
47 | 输入: [1,3,5,6], 7
48 | 输出: 4
49 | 示例 4:
50 |
51 | 输入: [1,3,5,6], 0
52 | 输出: 0
53 | ```
54 |
--------------------------------------------------------------------------------
/problems/0020.valid-parentheses/README.md:
--------------------------------------------------------------------------------
1 | # 题干
2 |
3 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
4 | 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
5 |
6 | An input string is valid if:
7 | 有效字符串需满足:
8 |
9 | ```
10 | Open brackets must be closed by the same type of brackets.
11 | 左括号必须用相同类型的右括号闭合。
12 |
13 | Open brackets must be closed in the correct order.
14 | 左括号必须以正确的顺序闭合。
15 | ```
16 |
17 | Note that an empty string is also considered valid.
18 | 注意空字符串可被认为是有效字符串。
19 |
20 | Example 1:
21 |
22 | ```
23 | Input: "()"
24 | Output: true
25 | ```
26 |
27 | Example 2:
28 |
29 | ```
30 | Input: "()[]{}"
31 | Output: true
32 | ```
33 |
34 | Example 3:
35 |
36 | ```
37 | Input: "(]"
38 | Output: false
39 | ```
40 |
41 | Example 4:
42 |
43 | ```
44 | Input: "([)]"
45 | Output: false
46 | ```
47 |
48 | Example 5:
49 |
50 | ```
51 | Input: "{[]}"
52 | Output: true
53 | ```
--------------------------------------------------------------------------------
/problems/0215.kth-largest-element-in-an-array/run.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | func findKthLargest(nums []int, k int) int {
4 | if len(nums) < k {
5 | return -1
6 | }
7 |
8 | start := 0
9 | end := len(nums) - 1
10 |
11 | for start <= end {
12 | i := partition(nums, start, end)
13 |
14 | switch {
15 | case i+1 < k:
16 | start = i + 1
17 | case i+1 > k:
18 | end = i - 1
19 | default:
20 | return nums[i]
21 | }
22 | }
23 | return -1
24 | }
25 |
26 | // 3, 2, 3, 1, 2, 4, 5, 5, 6
27 | // K:4
28 | func partition(nums []int, start, end int) int {
29 | povit := nums[start]
30 | s := start + 1
31 | e := end
32 | for s <= e {
33 | if nums[s] < povit && nums[e] > povit {
34 | nums[s], nums[e] = nums[e], nums[s]
35 | s++
36 | e--
37 | }
38 | if nums[s] >= povit {
39 | s++
40 | }
41 | if nums[e] <= povit {
42 | e--
43 | }
44 | }
45 | nums[start], nums[e] = nums[e], nums[start]
46 | return e
47 | }
48 |
--------------------------------------------------------------------------------
/problems/0082.remove-duplicates-from-sorted-list2/run.go:
--------------------------------------------------------------------------------
1 | package list2
2 |
3 | import (
4 | "github.com/itcuihao/leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for singly-linked list.
9 | * type ListNode struct {
10 | * Val int
11 | * Next *ListNode
12 | * }
13 | */
14 | // list: 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
15 | // out: 1 -> 2 -> 5
16 | // tmp: 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
17 | // p
18 | // time: o(n) space: o(1)
19 | func deleteDuplicates(head *structure.ListNode) *structure.ListNode {
20 | if head == nil || head.Next == nil {
21 | return head
22 | }
23 | tmp := &structure.ListNode{Val: 0}
24 | tmp.Next = head
25 | p := tmp
26 | for p.Next != nil && p.Next.Next != nil {
27 | if p.Next.Val == p.Next.Next.Val {
28 | same := p.Next.Val
29 | for p.Next != nil && p.Next.Val == same {
30 | p.Next = p.Next.Next
31 | }
32 | } else {
33 | p = p.Next
34 | }
35 | }
36 | return tmp.Next
37 | }
38 |
--------------------------------------------------------------------------------
/problems/0131.palindrome-partitioning/run.go:
--------------------------------------------------------------------------------
1 | package partitioning
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | s := "aab"
7 | p := partition(s)
8 | fmt.Println(p)
9 | }
10 |
11 | func partition(s string) [][]string {
12 | n := len(s)
13 | f := make([][]bool, n)
14 | for i := range f {
15 | f[i] = make([]bool, n)
16 | for j := range f[i] {
17 | f[i][j] = true
18 | }
19 | }
20 | for i := n - 1; i >= 0; i-- {
21 | for j := i + 1; j < n; j++ {
22 | f[i][j] = s[i] == s[j] && f[i+1][j-1]
23 | }
24 | }
25 | ans := make([][]string, 0)
26 | splists := make([]string, 0)
27 | dfs := func(int) {}
28 | dfs = func(i int) {
29 | if i == n {
30 | ans = append(ans, append([]string{}, splists...))
31 | return
32 | }
33 | for j := i; j < n; j++ {
34 | if f[i][j] {
35 | splists = append(splists, s[i:j+1])
36 | dfs(j + 1)
37 | splists = splists[:len(splists)-1]
38 | }
39 | }
40 | }
41 | dfs(0)
42 | return ans
43 | }
44 |
--------------------------------------------------------------------------------
/problems/0888.fair-candy-swap/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0888.fair-candy-swap
3 |
4 | ```text
5 | 爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。
6 |
7 | 因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)
8 |
9 | 返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。
10 |
11 | 如果有多个答案,你可以返回其中任何一个。保证答案存在。
12 |
13 |
14 |
15 | 示例 1:
16 |
17 | 输入:A = [1,1], B = [2,2]
18 | 输出:[1,2]
19 | 示例 2:
20 |
21 | 输入:A = [1,2], B = [2,3]
22 | 输出:[1,2]
23 | 示例 3:
24 |
25 | 输入:A = [2], B = [1,3]
26 | 输出:[2,3]
27 | 示例 4:
28 |
29 | 输入:A = [1,2,5], B = [2,4]
30 | 输出:[5,4]
31 |
32 |
33 | 提示:
34 |
35 | 1 <= A.length <= 10000
36 | 1 <= B.length <= 10000
37 | 1 <= A[i] <= 100000
38 | 1 <= B[i] <= 100000
39 | 保证爱丽丝与鲍勃的糖果总量不同。
40 | 答案肯定存在。
41 |
42 | 来源:力扣(LeetCode)
43 | 链接:https://leetcode-cn.com/problems/fair-candy-swap
44 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
45 | ```
46 |
47 | 根据题意,两边和相等,设A需要交换的为x,B需要交换的为y,则有
48 |
49 | >sumA-x+y=sumB-y+x
50 |
51 |
--------------------------------------------------------------------------------
/problems/0010.regular-expression-matching/run.go:
--------------------------------------------------------------------------------
1 | package matching
2 |
3 | func isMatch(s string, p string) bool {
4 | dp := make([][]bool, len(p)+1)
5 | for i := range dp {
6 | dp[i] = make([]bool, len(s)+1)
7 | }
8 |
9 | dp[0][0] = true
10 |
11 | for i := 2; i < len(dp); i += 2 {
12 | if p[i-1] == '*' {
13 | dp[i][0] = true
14 | } else {
15 | break
16 | }
17 | }
18 |
19 | for i := 1; i < len(dp); i++ {
20 | if i < len(p) && p[i] == '*' {
21 | continue
22 | }
23 |
24 | for j := 1; j < len(dp[0]); j++ {
25 |
26 | if p[i-1] == '*' {
27 | if p[i-2] == '.' {
28 | dp[i][j] = dp[i-2][j-1] || dp[i][j-1] || dp[i-2][j]
29 | } else {
30 | dp[i][j] = (dp[i-2][j]) || (p[i-2] == s[j-1] && (dp[i-2][j-1] || dp[i][j-1]))
31 | }
32 | } else if p[i-1] == '.' {
33 | dp[i][j] = dp[i-1][j-1]
34 | } else {
35 | dp[i][j] = dp[i-1][j-1] && p[i-1] == s[j-1]
36 | }
37 | }
38 | }
39 |
40 | return dp[len(p)][len(s)]
41 | }
42 |
--------------------------------------------------------------------------------
/problems/0542.01-matrix/run.go:
--------------------------------------------------------------------------------
1 | package matrix
2 |
3 | func updateMatrix(matrix [][]int) [][]int {
4 | if len(matrix) == 0 {
5 | return nil
6 | }
7 | maxRow, maxCel := len(matrix), len(matrix[0])
8 | zero := make([][]int, 0)
9 | for i := 0; i < maxRow; i++ {
10 | for j := 0; j < maxCel; j++ {
11 | if matrix[i][j] == 0 {
12 | zero = append(zero, []int{i, j})
13 | } else {
14 | matrix[i][j] = -1
15 | }
16 | }
17 | }
18 |
19 | around := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
20 |
21 | for len(zero) > 0 {
22 | item := zero[0]
23 | x := item[0]
24 | y := item[1]
25 |
26 | zero = zero[1:]
27 |
28 | for _, a := range around {
29 | ax, ay := x+a[0], y+a[1]
30 |
31 | if ax < 0 || ax >= maxRow || ay < 0 || ay >= maxCel {
32 | continue
33 | }
34 |
35 | if matrix[ax][ay] == -1 {
36 | matrix[ax][ay] = matrix[x][y] + 1
37 | zero = append(zero, []int{ax, ay})
38 | }
39 |
40 | }
41 | }
42 | return matrix
43 | }
44 |
--------------------------------------------------------------------------------
/problems/0023.merge-k-sorted-lists/run.go:
--------------------------------------------------------------------------------
1 | package lists
2 |
3 | /**
4 | * Definition for singly-linked list.
5 | * type ListNode struct {
6 | * Val int
7 | * Next *ListNode
8 | * }
9 | */
10 |
11 | type ListNode struct {
12 | Val int
13 | Next *ListNode
14 | }
15 |
16 | // 分治法
17 | func mergeKLists(lists []*ListNode) *ListNode {
18 | if lists == nil || len(lists) == 0 {
19 | return nil
20 | }
21 | return sort(lists, 0, len(lists)-1)
22 | }
23 |
24 | func sort(lists []*ListNode, lo, hi int) *ListNode {
25 | if lo >= hi {
26 | return lists[lo]
27 | }
28 | mid := (hi-lo)/2 + lo
29 | l1 := sort(lists, lo, mid)
30 | l2 := sort(lists, mid+1, hi)
31 | return merge(l1, l2)
32 | }
33 |
34 | func merge(l1, l2 *ListNode) *ListNode {
35 | if l1 == nil {
36 | return l2
37 | }
38 | if l2 == nil {
39 | return l1
40 | }
41 | if l1.Val < l2.Val {
42 | l1.Next = merge(l1.Next, l2)
43 | return l1
44 | }
45 | l2.Next = merge(l1, l2.Next)
46 | return l2
47 | }
48 |
--------------------------------------------------------------------------------
/problems/0480.sliding-window-median/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0480.sliding-window-median
3 |
4 | ```text
5 | 中位数是有序序列最中间的那个数。如果序列的长度是偶数,则没有最中间的数;此时中位数是最中间的两个数的平均数。
6 |
7 | 例如:
8 |
9 | [2,3,4],中位数是 3
10 | [2,3],中位数是 (2 + 3) / 2 = 2.5
11 | 给你一个数组 nums,有一个长度为 k 的窗口从最左端滑动到最右端。窗口中有 k 个数,每次窗口向右移动 1 位。你的任务是找出每次窗口移动后得到的新窗口中元素的中位数,并输出由它们组成的数组。
12 |
13 |
14 |
15 | 示例:
16 |
17 | 给出 nums = [1,3,-1,-3,5,3,6,7],以及 k = 3。
18 |
19 | 窗口位置 中位数
20 | --------------- -----
21 | [1 3 -1] -3 5 3 6 7 1
22 | 1 [3 -1 -3] 5 3 6 7 -1
23 | 1 3 [-1 -3 5] 3 6 7 -1
24 | 1 3 -1 [-3 5 3] 6 7 3
25 | 1 3 -1 -3 [5 3 6] 7 5
26 | 1 3 -1 -3 5 [3 6 7] 6
27 | 因此,返回该滑动窗口的中位数数组 [1,-1,-1,3,5,6]。
28 |
29 |
30 |
31 | 提示:
32 |
33 | 你可以假设 k 始终有效,即:k 始终小于输入的非空数组的元素个数。
34 | 与真实值误差在 10 ^ -5 以内的答案将被视作正确答案。
35 |
36 | 来源:力扣(LeetCode)
37 | 链接:https://leetcode-cn.com/problems/sliding-window-median
38 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
39 | ```
40 |
--------------------------------------------------------------------------------
/problems/0018.4sum/run.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import (
4 | "sort"
5 | )
6 |
7 | func fourSum(nums []int, target int) [][]int {
8 | var data [][]int
9 | ln := len(nums)
10 | if ln < 4 {
11 | return data
12 | }
13 |
14 | sort.Ints(nums)
15 |
16 | for i := 0; i < ln-3; i++ {
17 | if i > 0 && nums[i-1] == nums[i] {
18 | continue
19 | }
20 | for j := i + 1; j < ln-2; j++ {
21 | if j > i+1 && nums[j-1] == nums[j] {
22 | continue
23 | }
24 | s, e := j+1, ln-1
25 | for s < e {
26 | sum := nums[i] + nums[j] + nums[s] + nums[e]
27 |
28 | if sum == target {
29 | d := []int{nums[i], nums[j], nums[s], nums[e]}
30 |
31 | data = append(data, d)
32 | for s < e && nums[s] == nums[s+1] {
33 | s++
34 | }
35 | for s < e && nums[e-1] == nums[e] {
36 | e--
37 | }
38 | s++
39 | e--
40 | } else if sum < target {
41 | s++
42 | } else {
43 | e--
44 | }
45 | }
46 | }
47 |
48 | }
49 |
50 | return data
51 | }
52 |
--------------------------------------------------------------------------------
/problems/0034.find-first-and-last-position-of-element-in-sorted-array/run.go:
--------------------------------------------------------------------------------
1 | package array
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | nums := []int{5, 7, 7, 8, 8, 10}
7 | target := 8
8 | r := searchRange(nums, target)
9 | fmt.Println(r)
10 |
11 | nums = []int{1, 3}
12 | target = 1
13 | r = searchRange(nums, target)
14 | fmt.Println(r)
15 |
16 | nums = []int{1}
17 | target = 1
18 | r = searchRange(nums, target)
19 | fmt.Println(r)
20 |
21 | nums = []int{1, 1, 1}
22 | target = 1
23 | r = searchRange(nums, target)
24 | fmt.Println(r)
25 | }
26 |
27 | func searchRange(nums []int, target int) []int {
28 | l := len(nums)
29 | r := []int{-1, -1}
30 | if l == 0 {
31 | return r
32 | }
33 |
34 | for i := 0; i < l; i++ {
35 | if nums[i] == target {
36 | r[0] = i
37 | break
38 | }
39 | }
40 | for i := l - 1; i > r[0]; i-- {
41 | if nums[i] == target {
42 | r[1] = i
43 | return r
44 | }
45 | }
46 | if r[0] > r[1] {
47 | r[1] = r[0]
48 | }
49 | return r
50 | }
51 |
--------------------------------------------------------------------------------
/problems/0160.intersection-of-two-linked-lists/run.go:
--------------------------------------------------------------------------------
1 | package lists
2 |
3 | import "leetcode-go/structure"
4 |
5 | /**
6 | * Definition for singly-linked list.
7 | * type ListNode struct {
8 | * Val int
9 | * Next *ListNode
10 | * }
11 | */
12 | func getIntersectionNode(headA, headB *structure.ListNode) *structure.ListNode {
13 | if headA == nil || headB == nil {
14 | return nil
15 | }
16 | a, b := headA, headB
17 | la, lb := 0, 0
18 | for a != nil {
19 | a = a.Next
20 | la++
21 | }
22 | for b != nil {
23 | b = b.Next
24 | lb++
25 | }
26 |
27 | if la > lb {
28 | abs := la - lb
29 | for ; abs > 0; abs-- {
30 | headA = headA.Next
31 | }
32 | } else {
33 | abs := lb - la
34 | for ; abs > 0; abs-- {
35 | headB = headB.Next
36 | }
37 | }
38 | for headA != nil && headB != nil {
39 | // if headA.Val == headB.Val { // 如果是求相交的第一个节点,则对比值
40 | if headA == headB {
41 | return headA
42 | }
43 | headA = headA.Next
44 | headB = headB.Next
45 | }
46 | return nil
47 | }
48 |
--------------------------------------------------------------------------------
/problems/0098.validate-binary-search-tree/run.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "fmt"
5 | "github.com/itcuihao/leetcode-go/structure"
6 | )
7 |
8 | func Run() {
9 | root := structure.BinaryTree98
10 | b := isValidBST(root)
11 | fmt.Println(b)
12 | }
13 |
14 | /**
15 | * Definition for a binary tree node.
16 | * type TreeNode struct {
17 | * Val int
18 | * Left *TreeNode
19 | * Right *TreeNode
20 | * }
21 | */
22 | func isValidBST(root *structure.TreeNode) bool {
23 | res := traverse(root)
24 | if len(res) <= 1 {
25 | return true
26 | }
27 | tmp := res[0]
28 | for i := 1; i < len(res); i++ {
29 | if res[i] <= tmp {
30 | return false
31 | }
32 | tmp = res[i]
33 | }
34 | return true
35 | }
36 |
37 | // 中序遍历获取有序数组
38 | func traverse(root *structure.TreeNode) []int {
39 | res := make([]int, 0)
40 | if root == nil {
41 | return res
42 | }
43 | res = append(res, traverse(root.Left)...)
44 | res = append(res, root.Val)
45 | res = append(res, traverse(root.Right)...)
46 | return res
47 | }
48 |
--------------------------------------------------------------------------------
/problems/0001.two-sum/README.md:
--------------------------------------------------------------------------------
1 | # Two Sum
2 |
3 | ```English
4 | Given an array of integers, return indices of the two numbers such that they add up to a specific target.
5 |
6 | You may assume that each input would have exactly one solution, and you may not use the same element twice.
7 |
8 | Example:
9 |
10 | Given nums = [2, 7, 11, 15], target = 9,
11 |
12 | Because nums[0] + nums[1] = 2 + 7 = 9,
13 | return [0, 1].
14 | ```
15 |
16 | ```Chinese
17 | 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
18 |
19 | 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
20 |
21 | 示例:
22 |
23 | 给定 nums = [2, 7, 11, 15], target = 9
24 |
25 | 因为 nums[0] + nums[1] = 2 + 7 = 9
26 | 所以返回 [0, 1]
27 | ```
28 |
29 | ---
30 |
31 | 20190411 update
32 |
33 | 今天看剑指Offer,第41题与此题类似。
34 |
35 | *题干*
36 |
37 | ```Chinese
38 | 输入一个递增排序的数组与一个数字s,在数组中查找两个数,使得他们的和,
39 | 正好是s,如果有多对和为s则输出任意一对。
40 | ```
41 |
42 | `步骤`
43 |
44 | 1. 数组排序 (要求输出下标,排序会破会原有结构)
45 | 2. 两个指针,指向头尾位置
46 | 3. 相加小于s,则头向后移动
47 | 4. 相加等于s,则返回
48 | 5. 相加大于s,则尾部向前移
49 | 6. 直到头>尾
50 |
51 | __注意这两个题的区别__
--------------------------------------------------------------------------------
/problems/0097.interleaving-string/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0097.interleaving-string](https://leetcode.com/problems/interleaving-string/)
3 |
4 | ```English
5 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
6 |
7 | Example 1:
8 |
9 | Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
10 | Output: true
11 | Example 2:
12 |
13 | Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
14 | Output: false
15 | ```
16 |
17 | ```Chinese
18 | 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
19 |
20 | 示例 1:
21 |
22 | 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
23 | 输出: true
24 | 示例 2:
25 |
26 | 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
27 | 输出: false
28 | ```
29 |
30 | 利用DP
31 |
32 | ```
33 | 考虑用动态规划做。
34 |
35 | s1, s2只有两个字符串,因此可以展平为一个二维地图,判断是否能从左上角走到右下角。
36 |
37 | 当s1到达第i个元素,s2到达第j个元素:
38 |
39 | 地图上往右一步就是s2[j-1]匹配s3[i+j-1]。
40 |
41 | 地图上往下一步就是s1[i-1]匹配s3[i+j-1]。
42 |
43 | 示例:s1="aa",s2="ab",s3="aaba"。标1的为可行。最终返回右下角。
44 |
45 | 0 a b
46 |
47 | 0 1 1 0
48 |
49 | a 1 1 1
50 |
51 | a 1 0 1
52 | ```
--------------------------------------------------------------------------------
/problems/0127.word-ladder/README.md:
--------------------------------------------------------------------------------
1 | Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
2 |
3 | 1. Only one letter can be changed at a time.
4 | 1. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
5 | For example,
6 |
7 | ```
8 | Given:
9 | beginWord = "hit"
10 | endWord = "cog"
11 | wordList = ["hot","dot","dog","lot","log","cog"]
12 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
13 | return its length 5.
14 | ```
15 |
16 | #####Note:
17 | Return 0 if there is no such transformation sequence.
18 | All words have the same length.
19 | All words contain only lowercase alphabetic characters.
20 | You may assume no duplicates in the word list.
21 | You may assume beginWord and endWord are non-empty and are not the same.
22 | #####UPDATE (2017/1/20):
23 | The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
--------------------------------------------------------------------------------
/problems/0033.search-in-rotated-sorted-array/README.md:
--------------------------------------------------------------------------------
1 | # 33. Search in Rotated Sorted Array
2 |
3 | ## 题目
4 |
5 | ```English
6 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
7 |
8 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
9 |
10 | You are given a target value to search. If found in the array return its index, otherwise return -1.
11 |
12 | You may assume no duplicate exists in the array.
13 |
14 | Your algorithm's runtime complexity must be in the order of O(log n).
15 |
16 | Example 1:
17 |
18 | Input: nums = [4,5,6,7,0,1,2], target = 0
19 | Output: 4
20 | Example 2:
21 |
22 | Input: nums = [4,5,6,7,0,1,2], target = 3
23 | Output: -1
24 | ```
25 |
26 | ```中文
27 | 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
28 |
29 | ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
30 |
31 | 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
32 |
33 | 你可以假设数组中不存在重复的元素。
34 |
35 | 你的算法时间复杂度必须是 O(log n) 级别。
36 |
37 | 示例 1:
38 |
39 | 输入: nums = [4,5,6,7,0,1,2], target = 0
40 | 输出: 4
41 | 示例 2:
42 |
43 | 输入: nums = [4,5,6,7,0,1,2], target = 3
44 | 输出: -1
45 | ```
--------------------------------------------------------------------------------
/problems/0001.two-sum/run.go:
--------------------------------------------------------------------------------
1 | package sum
2 |
3 | import "sort"
4 |
5 | // 61ms
6 | func twoSum(nums []int, target int) []int {
7 | if len(nums) < 2 {
8 | return nil
9 | }
10 |
11 | for k, v := range nums {
12 | for i := k + 1; i < len(nums); i++ {
13 | if v+nums[i] == target {
14 | return []int{k, i}
15 | }
16 | }
17 | }
18 | return nil
19 | }
20 |
21 | func twoSum2(nums []int, target int) []int {
22 | if len(nums) < 2 {
23 | return nil
24 | }
25 |
26 | m := make(map[int]int, len(nums))
27 | for k, v := range nums {
28 | if i, ok := m[v]; ok {
29 | return []int{i, k}
30 | }
31 | m[target-v] = k
32 | }
33 | return nil
34 | }
35 |
36 | func findnum(nums []int, target int) []int {
37 | if len(nums) < 2 {
38 | return nil
39 | }
40 | sort.Ints(nums)
41 | start := 0
42 | end := len(nums) - 1
43 |
44 | for start < end {
45 | cur := nums[start] + nums[end]
46 | switch {
47 | case target > cur:
48 | start++
49 | case target < cur:
50 | end--
51 | default:
52 | return []int{nums[start], nums[end]}
53 | }
54 | }
55 | return nil
56 | }
57 |
--------------------------------------------------------------------------------
/problems/0003.longest-substring-without-repeating-characters/run.go:
--------------------------------------------------------------------------------
1 | package characters
2 |
3 | // The above solution requires at most 2n steps. In fact, it could be optimized to require only n steps. Instead of using a set to tell if a character exists or not, we could define a mapping of the characters to its index. Then we can skip the characters immediately when we found a repeated character.
4 |
5 | // The reason is that if s[j]s[j] have a duplicate in the range [i, j)[i,j) with index j'j
6 | // ′
7 | // , we don't need to increase ii little by little. We can skip all the elements in the range [i, j'][i,j
8 | // ′
9 | // ] and let ii to be j' + 1j
10 | // ′
11 | // +1 directly.
12 | func lengthOfLongestSubstring(s string) int {
13 | if len(s) == 0 {
14 | return 0
15 | }
16 | m, max, i := make(map[rune]int, len(s)), 0, 0
17 | for k, v := range s {
18 | if j, ok := m[v]; ok {
19 | i = mmax(j, i)
20 | }
21 | max = mmax(max, k-i+1)
22 | m[v] = k + 1
23 | }
24 | return max
25 | }
26 |
27 | func mmax(ml, m int) int {
28 | if ml > m {
29 | return ml
30 | }
31 | return m
32 | }
33 |
--------------------------------------------------------------------------------
/problems/0303.range-sum-query-immutable/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0303.range-sum-query-immutable
3 |
4 | ```text
5 |
6 | 303. 区域和检索 - 数组不可变
7 |
8 | 给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
9 |
10 | 实现 NumArray 类:
11 |
12 | NumArray(int[] nums) 使用数组 nums 初始化对象
13 | int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点(也就是 sum(nums[i], nums[i + 1], ... , nums[j]))
14 |
15 |
16 | 示例:
17 |
18 | 输入:
19 | ["NumArray", "sumRange", "sumRange", "sumRange"]
20 | [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
21 | 输出:
22 | [null, 1, -1, -3]
23 |
24 | 解释:
25 | NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
26 | numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
27 | numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
28 | numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
29 |
30 |
31 | 提示:
32 |
33 | 0 <= nums.length <= 104
34 | -105 <= nums[i] <= 105
35 | 0 <= i <= j < nums.length
36 | 最多调用 104 次 sumRange 方法
37 |
38 | 来源:力扣(LeetCode)
39 | 链接:https://leetcode-cn.com/problems/range-sum-query-immutable
40 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
41 | ```
--------------------------------------------------------------------------------
/problems/0043.multiply-strings/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0043.multiply-strings](https://leetcode.com/problems/multiply-strings/)
3 |
4 | ```English
5 | Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
6 |
7 | Example 1:
8 |
9 | Input: num1 = "2", num2 = "3"
10 | Output: "6"
11 | Example 2:
12 |
13 | Input: num1 = "123", num2 = "456"
14 | Output: "56088"
15 | Note:
16 |
17 | The length of both num1 and num2 is < 110.
18 | Both num1 and num2 contain only digits 0-9.
19 | Both num1 and num2 do not contain any leading zero, except the number 0 itself.
20 | You must not use any built-in BigInteger library or convert the inputs to integer directly.
21 | ```
22 |
23 | ```Chinese
24 | 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
25 |
26 | 示例 1:
27 |
28 | 输入: num1 = "2", num2 = "3"
29 | 输出: "6"
30 | 示例 2:
31 |
32 | 输入: num1 = "123", num2 = "456"
33 | 输出: "56088"
34 | 说明:
35 |
36 | num1 和 num2 的长度小于110。
37 | num1 和 num2 只包含数字 0-9。
38 | num1 和 num2 均不以零开头,除非是数字 0 本身。
39 | 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
40 | ```
--------------------------------------------------------------------------------
/problems/0304.range-sum-query-2d-immutable/run.go:
--------------------------------------------------------------------------------
1 | package immutable
2 |
3 | import "fmt"
4 |
5 | func Run() {
6 | matrix := [][]int{
7 | []int{3, 0, 1, 4, 2},
8 | []int{5, 6, 3, 2, 1},
9 | []int{1, 2, 0, 1, 5},
10 | []int{4, 1, 0, 1, 7},
11 | []int{1, 0, 3, 0, 5},
12 | }
13 | c := Constructor(matrix)
14 | sum := c.SumRegion(2, 1, 4, 3)
15 | fmt.Println(sum)
16 | }
17 |
18 | type NumMatrix struct {
19 | sums [][]int
20 | }
21 |
22 | func Constructor(matrix [][]int) NumMatrix {
23 | sums := make([][]int, len(matrix))
24 | for i, row := range matrix {
25 | sums[i] = make([]int, len(row)+1)
26 | for i2, v := range row {
27 | sums[i][i2+1] = sums[i][i2] + v
28 | }
29 | }
30 | return NumMatrix{sums: sums}
31 | }
32 |
33 | func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
34 | sum := 0
35 | for i := row1; i <= row2; i++ {
36 | sum += this.sums[i][col2+1] - this.sums[i][col1]
37 | }
38 | return sum
39 | }
40 |
41 | /**
42 | * Your NumMatrix object will be instantiated and called as such:
43 | * obj := Constructor(matrix);
44 | * param_1 := obj.SumRegion(row1,col1,row2,col2);
45 | */
46 |
--------------------------------------------------------------------------------
/problems/0053.maximum-subarray/run.go:
--------------------------------------------------------------------------------
1 | package subarray
2 |
3 | import "fmt"
4 |
5 | // 思路遍历整个数组,连续相加,索引前相加小于索引位置,则从索引位置开始相加
6 | func maxSubArray(s []int) int {
7 | l := len(s)
8 | if l == 0 {
9 | return 0
10 | }
11 |
12 | if l == 1 {
13 | return s[0]
14 | }
15 |
16 | maxSoFar, maxEndingHere := s[0], s[0]
17 |
18 | for i := 1; i < l; i++ {
19 | if maxEndingHere+s[i] > s[i] {
20 | maxEndingHere += s[i]
21 | fmt.Println("a:", maxEndingHere)
22 | } else {
23 | maxEndingHere = s[i]
24 | fmt.Println("b:", maxEndingHere)
25 | }
26 |
27 | if maxSoFar < maxEndingHere {
28 | maxSoFar = maxEndingHere
29 | }
30 | fmt.Println("c:", maxSoFar)
31 | }
32 | return maxSoFar
33 | }
34 |
35 | func maxSubArrayDp(nums []int) int {
36 | if len(nums) == 0 {
37 | return 0
38 | }
39 | if len(nums) == 1 {
40 | return nums[0]
41 | }
42 | dp, res := make([]int, len(nums)), nums[0]
43 | dp[0] = nums[0]
44 | for i := 1; i < len(nums); i++ {
45 | if dp[i-1] > 0 {
46 | dp[i] = nums[i] + dp[i-1]
47 | } else {
48 | dp[i] = nums[i]
49 | }
50 | if res < dp[i] {
51 | res = dp[i]
52 | }
53 | }
54 | return res
55 | }
56 |
--------------------------------------------------------------------------------
/problems/0028.implement-strstr/README.md:
--------------------------------------------------------------------------------
1 | # 28.Implement strStr()
2 |
3 | - English
4 |
5 | ```
6 | Implement strStr().
7 |
8 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
9 |
10 | Example 1:
11 |
12 | Input: haystack = "hello", needle = "ll"
13 | Output: 2
14 |
15 | Example 2:
16 |
17 | Input: haystack = "aaaaa", needle = "bba"
18 | Output: -1
19 |
20 | Clarification:
21 |
22 | What should we return when needle is an empty string? This is a great question to ask during an interview.
23 |
24 | For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
25 | ```
26 |
27 | - 中文
28 |
29 | ```
30 | 实现 strStr() 函数。
31 |
32 | 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
33 |
34 | 示例 1:
35 |
36 | 输入: haystack = "hello", needle = "ll"
37 | 输出: 2
38 | 示例 2:
39 |
40 | 输入: haystack = "aaaaa", needle = "bba"
41 | 输出: -1
42 | 说明:
43 |
44 | 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
45 |
46 | 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
47 | ```
48 |
--------------------------------------------------------------------------------
/problems/0235.lowest-common-ancestor-of-a-binary-search-tree/run.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "leetcode-go/structure"
5 | )
6 |
7 | /**
8 | * Definition for TreeNode.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *ListNode
12 | * Right *ListNode
13 | * }
14 | */
15 | func lowestCommonAncestor(root, p, q *structure.TreeNode) *structure.TreeNode {
16 | if root == nil || p == nil || q == nil {
17 | return nil
18 | }
19 |
20 | switch {
21 | case q.Val < root.Val && p.Val < root.Val:
22 | return lowestCommonAncestor(root.Left, q, p)
23 | case q.Val > root.Val && p.Val > root.Val:
24 | return lowestCommonAncestor(root.Right, q, p)
25 | }
26 |
27 | return root
28 | }
29 |
30 | func lowestCommonAncestorStackOverflow(root, p, q *structure.TreeNode) *structure.TreeNode {
31 | if root == nil || p == nil || q == nil {
32 | return root
33 | }
34 |
35 | switch {
36 | case q.Val < root.Val && p.Val < root.Val:
37 | root = root.Left
38 | case q.Val > root.Val && p.Val > root.Val:
39 | root = root.Right
40 | // default: // 递归退出条件
41 | // return root
42 | }
43 |
44 | return lowestCommonAncestorStackOverflow(root, q, p)
45 | }
46 |
--------------------------------------------------------------------------------
/problems/0240.search-a-2D-matrix2/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0240.search-a-2D-matrix2
3 |
4 | ```English
5 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
6 |
7 | Integers in each row are sorted in ascending from left to right.
8 | Integers in each column are sorted in ascending from top to bottom.
9 | Example:
10 |
11 | Consider the following matrix:
12 |
13 | [
14 | [1, 4, 7, 11, 15],
15 | [2, 5, 8, 12, 19],
16 | [3, 6, 9, 16, 22],
17 | [10, 13, 14, 17, 24],
18 | [18, 21, 23, 26, 30]
19 | ]
20 | Given target = 5, return true.
21 |
22 | Given target = 20, return false
23 | ```
24 |
25 | ```Chinese
26 | 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
27 |
28 | 每行的元素从左到右升序排列。
29 | 每列的元素从上到下升序排列。
30 | 示例:
31 |
32 | 现有矩阵 matrix 如下:
33 |
34 | [
35 | [1, 4, 7, 11, 15],
36 | [2, 5, 8, 12, 19],
37 | [3, 6, 9, 16, 22],
38 | [10, 13, 14, 17, 24],
39 | [18, 21, 23, 26, 30]
40 | ]
41 | 给定 target = 5,返回 true。
42 |
43 | 给定 target = 20,返回 false。
44 | ```
45 |
46 | **步骤**
47 |
48 | 1. 从每一行的最大数值开始对比;
49 | 2. 如果target > row max,则对比下一行;
50 | 3. 如果target < row max,则对比下一列;
51 | 4. 找到相等元素返回true,否则返回false;
--------------------------------------------------------------------------------
/problems/0038.count-and-say/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0038.count-and-say
3 |
4 | ```text
5 | 给定一个正整数 n ,输出外观数列的第 n 项。
6 |
7 | 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
8 |
9 | 你可以将其视作是由递归公式定义的数字字符串序列:
10 |
11 | countAndSay(1) = "1"
12 | countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
13 | 前五项如下:
14 |
15 | 1. 1
16 | 2. 11
17 | 3. 21
18 | 4. 1211
19 | 5. 111221
20 | 第一项是数字 1
21 | 描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"
22 | 描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"
23 | 描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"
24 | 描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"
25 | 要 描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
26 |
27 | 例如,数字字符串 "3322251" 的描述如下图:
28 |
29 |
30 |
31 |
32 | 示例 1:
33 |
34 | 输入:n = 1
35 | 输出:"1"
36 | 解释:这是一个基本样例。
37 | 示例 2:
38 |
39 | 输入:n = 4
40 | 输出:"1211"
41 | 解释:
42 | countAndSay(1) = "1"
43 | countAndSay(2) = 读 "1" = 一 个 1 = "11"
44 | countAndSay(3) = 读 "11" = 二 个 1 = "21"
45 | countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"
46 |
47 |
48 | 提示:
49 |
50 | 1 <= n <= 30
51 |
52 | 来源:力扣(LeetCode)
53 | 链接:https://leetcode-cn.com/problems/count-and-say
54 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
55 | ```
--------------------------------------------------------------------------------
/problems/0025.reverse-nodes-in-k-group/README.md:
--------------------------------------------------------------------------------
1 | # 25.Reverse Nodes in k-Group
2 |
3 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
4 |
5 | k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
6 |
7 | Example:
8 |
9 | ```
10 | Given this linked list: 1->2->3->4->5
11 |
12 | For k = 2, you should return: 2->1->4->3->5
13 |
14 | For k = 3, you should return: 3->2->1->4->5
15 | ```
16 |
17 | Note:
18 |
19 | - Only constant extra memory is allowed.
20 | - You may not alter the values in the list's nodes, only nodes itself may be changed.
21 |
22 |
23 | ```
24 | 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
25 |
26 | k 是一个正整数,它的值小于或等于链表的长度。
27 |
28 | 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
29 |
30 |
31 |
32 | 示例:
33 |
34 | 给你这个链表:1->2->3->4->5
35 |
36 | 当 k = 2 时,应当返回: 2->1->4->3->5
37 |
38 | 当 k = 3 时,应当返回: 3->2->1->4->5
39 |
40 |
41 |
42 | 说明:
43 |
44 | 你的算法只能使用常数的额外空间。
45 | 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
46 |
47 | 来源:力扣(LeetCode)
48 | 链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
49 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
50 | ```
--------------------------------------------------------------------------------
/problems/0144.binary-tree-preorder-traversal/run.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | /**
4 | * Definition for a binary tree node.
5 | * type TreeNode struct {
6 | * Val int
7 | * Left *TreeNode
8 | * Right *TreeNode
9 | * }
10 | */
11 | type TreeNode struct {
12 | Val int
13 | Left *TreeNode
14 | Right *TreeNode
15 | }
16 |
17 | // 递归
18 | func preorderTraversal(root *TreeNode) []int {
19 | l := make([]int, 0, 3)
20 | if root == nil {
21 | return l
22 | }
23 |
24 | l = append(l, root.Val)
25 | l = append(l, preorderTraversal(root.Left)...)
26 | l = append(l, preorderTraversal(root.Right)...)
27 |
28 | return l
29 | }
30 |
31 | // 遍历
32 | func preorderFor(root *TreeNode) []int {
33 | var (
34 | l []int
35 | tempStack []*TreeNode
36 | )
37 |
38 | for root != nil || len(tempStack) > 0 {
39 | l = append(l, root.Val)
40 |
41 | if root.Left != nil {
42 | if root.Right != nil {
43 | tempStack = append(tempStack, root.Right)
44 | }
45 | root = root.Left
46 | } else if root.Right != nil {
47 | root = root.Right
48 | } else {
49 |
50 | if len(tempStack) == 0 {
51 | break
52 | }
53 |
54 | root = tempStack[len(tempStack)-1]
55 | tempStack = tempStack[:len(tempStack)-1]
56 | }
57 | }
58 |
59 | return l
60 | }
61 |
--------------------------------------------------------------------------------
/problems/0021.merge-two-sorted-lists/run.go:
--------------------------------------------------------------------------------
1 | package lists
2 |
3 | import "fmt"
4 |
5 | type ListNode struct {
6 | Val int
7 | Next *ListNode
8 | }
9 |
10 | func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
11 | if l1 == nil {
12 | return l2
13 | }
14 | if l2 == nil {
15 | return l1
16 | }
17 | var head, node *ListNode
18 |
19 | if l1.Val > l2.Val {
20 | head, node = l2, l2
21 | l2 = l2.Next
22 | } else {
23 | head, node = l1, l1
24 | l1 = l1.Next
25 | }
26 | for l1 != nil && l2 != nil {
27 | if l1.Val < l2.Val {
28 | node.Next = l1
29 | l1 = l1.Next
30 | } else {
31 | node.Next = l2
32 | l2 = l2.Next
33 | }
34 | node = node.Next
35 | }
36 | if l1 != nil {
37 | node.Next = l1
38 | }
39 | if l2 != nil {
40 | node.Next = l2
41 | }
42 | return head
43 | }
44 |
45 | // PrintList print listnode
46 | func printList(l *ListNode) {
47 | for l != nil {
48 | fmt.Println("Val:", l.Val)
49 | l = l.Next
50 | }
51 | }
52 |
53 | // 递归的方式
54 | func mergeTwoLists2(l1 *ListNode, l2 *ListNode) *ListNode {
55 | if l1 == nil {
56 | return l2
57 | }
58 | if l2 == nil {
59 | return l1
60 | }
61 | if l1.Val < l2.Val {
62 | l1.Next = mergeTwoLists2(l1.Next, l2)
63 | return l1
64 | }
65 | l2.Next = mergeTwoLists2(l1, l2.Next)
66 | return l2
67 | }
68 |
--------------------------------------------------------------------------------
/problems/0470.implement-rand10-using-rand7/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0470.implement-rand10-using-rand7](https://leetcode.com/problems/implement-rand10-using-rand7/)
3 |
4 | ```English
5 | Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.
6 |
7 | Do NOT use system's Math.random().
8 |
9 |
10 |
11 | Example 1:
12 |
13 | Input: 1
14 | Output: [7]
15 | Example 2:
16 |
17 | Input: 2
18 | Output: [8,4]
19 | Example 3:
20 |
21 | Input: 3
22 | Output: [8,1,10]
23 |
24 |
25 | Note:
26 |
27 | rand7 is predefined.
28 | Each testcase has one argument: n, the number of times that rand10 is called.
29 |
30 |
31 | Follow up:
32 |
33 | What is the expected value for the number of calls to rand7() function?
34 | Could you minimize the number of calls to rand7()?
35 | ```
36 |
37 | ```Chinese
38 | 已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
39 |
40 | 不要使用系统的 Math.random() 方法。
41 |
42 |
43 |
44 | 示例 1:
45 |
46 | 输入: 1
47 | 输出: [7]
48 | 示例 2:
49 |
50 | 输入: 2
51 | 输出: [8,4]
52 | 示例 3:
53 |
54 | 输入: 3
55 | 输出: [8,1,10]
56 |
57 |
58 | 提示:
59 |
60 | rand7 已定义。
61 | 传入参数: n 表示 rand10 的调用次数。
62 |
63 |
64 | 进阶:
65 |
66 | rand7()调用次数的 期望值 是多少 ?
67 | 你能否尽量少调用 rand7() ?
68 | ```
--------------------------------------------------------------------------------
/problems/0347.top-k-frequent-elements/run.go:
--------------------------------------------------------------------------------
1 | package elements
2 |
3 | import (
4 | "container/heap"
5 | "fmt"
6 | )
7 |
8 | func Run() {
9 | nums := []int{1, 1, 1, 2, 2, 3}
10 | k := 2
11 | result := topKFrequent(nums, k)
12 | fmt.Println(result)
13 | }
14 |
15 | func topKFrequent(nums []int, k int) []int {
16 | m := make(map[int]int, len(nums))
17 | for _, n := range nums {
18 | m[n]++
19 | }
20 | pq := PriorityQueue{}
21 | for k, v := range m {
22 | heap.Push(&pq, &Item{key: k, count: v})
23 | }
24 | result := make([]int, 0, k)
25 | for len(result) < k {
26 | item := heap.Pop(&pq).(*Item)
27 | result = append(result, item.key)
28 | }
29 | return result
30 | }
31 |
32 | type Item struct {
33 | key int
34 | count int
35 | }
36 |
37 | // 优先队列
38 | type PriorityQueue []*Item
39 |
40 | func (p PriorityQueue) Len() int {
41 | return len(p)
42 | }
43 |
44 | func (p PriorityQueue) Less(i, j int) bool {
45 | return p[i].count > p[j].count
46 | }
47 |
48 | func (p PriorityQueue) Swap(i, j int) {
49 | p[i], p[j] = p[j], p[i]
50 | }
51 |
52 | func (p *PriorityQueue) Push(x interface{}) {
53 | item := x.(*Item)
54 | *p = append(*p, item)
55 | }
56 |
57 | func (p *PriorityQueue) Pop() interface{} {
58 | n := len(*p)
59 | item := (*p)[n-1]
60 | *p = (*p)[:n-1]
61 | return item
62 | }
63 |
--------------------------------------------------------------------------------
/problems/0030.substrings-with-concatenation-of-all-words/README.md:
--------------------------------------------------------------------------------
1 | # 30. Substring with Concatenation of All Words
2 |
3 | - English
4 |
5 | ```
6 | You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
7 |
8 | Example 1:
9 |
10 | Input:
11 | s = "barfoothefoobarman",
12 | words = ["foo","bar"]
13 | Output: [0,9]
14 | Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
15 | The output order does not matter, returning [9,0] is fine too.
16 | Example 2:
17 |
18 | Input:
19 | s = "wordgoodstudentgoodword",
20 | words = ["word","student"]
21 | Output: []
22 | ```
23 |
24 | - 中文
25 |
26 | ```
27 | 给定一个字符串 s 和一些长度相同的单词 words。在 s 中找出可以恰好串联 words 中所有单词的子串的起始位置。
28 |
29 | 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
30 |
31 | 示例 1:
32 |
33 | 输入:
34 | s = "barfoothefoobarman",
35 | words = ["foo","bar"]
36 | 输出: [0,9]
37 | 解释: 从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。
38 | 输出的顺序不重要, [9,0] 也是有效答案。
39 | 示例 2:
40 |
41 | 输入:
42 | s = "wordgoodstudentgoodword",
43 | words = ["word","student"]
44 | 输出: []
45 | ```
46 |
47 | 思路:
48 |
49 | ```
50 | 先将words全排列,然后再从s中找寻是否含有words中的元素,寻找字串,如果存在,则记录起始位置
51 | ```
--------------------------------------------------------------------------------
/problems/0003.longest-substring-without-repeating-characters/README.md:
--------------------------------------------------------------------------------
1 | # 题目
2 | Given a string, find the length of the longest substring without repeating characters.
3 |
4 | Examples:
5 |
6 | ```
7 | Given "abcabcbb", the answer is "abc", which the length is 3.
8 |
9 | Given "bbbbb", the answer is "b", with the length of 1.
10 |
11 | Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
12 | ```
13 |
14 | ```text
15 | 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
16 |
17 |
18 |
19 | 示例 1:
20 |
21 | 输入: s = "abcabcbb"
22 | 输出: 3
23 | 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
24 | 示例 2:
25 |
26 | 输入: s = "bbbbb"
27 | 输出: 1
28 | 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
29 | 示例 3:
30 |
31 | 输入: s = "pwwkew"
32 | 输出: 3
33 | 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
34 | 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
35 | 示例 4:
36 |
37 | 输入: s = ""
38 | 输出: 0
39 |
40 |
41 | 提示:
42 |
43 | 0 <= s.length <= 5 * 104
44 | s 由英文字母、数字、符号和空格组成
45 |
46 | 来源:力扣(LeetCode)
47 | 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
48 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
49 | ```
50 |
51 | # 分析
52 |
53 | ```
54 | 最长的不重复子字符串,只要有一个重复的字符,便要重新计算。
55 |
56 | 用 map[rune]int 记录遍历过的字符与数目,
57 | 当读取到重复的字符,记录不改变 max
58 |
59 | ```
--------------------------------------------------------------------------------
/problems/0017.letter-combinations-of-a-phone-number/run.go:
--------------------------------------------------------------------------------
1 | package closest
2 |
3 | import "fmt"
4 |
5 | // bfs
6 | func letterCombinations(digits string) []string {
7 | var jp = []string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
8 | ld := len(digits)
9 | // 初始化
10 | r := []string{}
11 | if ld == 0 {
12 | return r
13 | }
14 | r = []string{""}
15 | for i := 0; i < ld; i++ {
16 | var tmp []string
17 | // 获取jp对应的下标
18 | index := digits[i] - '0'
19 | for _, k := range r {
20 | for _, j := range jp[index] {
21 | tmp = append(tmp, k+string(j))
22 | }
23 | }
24 | // 重新给r赋值
25 | r = tmp
26 | }
27 | return r
28 | }
29 |
30 | // dfs
31 | func letterCombinationsDFS(digits string) []string {
32 | var jp = []string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
33 | cur := make([]rune, len(digits))
34 | ans = dfs(digits, jp, 0, cur)
35 | return ans
36 | }
37 |
38 | var (
39 | ans []string
40 | )
41 |
42 | func dfs(digits string, jp []string, l int, cur []rune) []string {
43 |
44 | if l == len(digits) {
45 | if l > 0 {
46 | ans = append(ans, string(cur))
47 | }
48 | return ans
49 | }
50 | s := jp[digits[l]-'0']
51 | for _, v := range s {
52 | cur[l] = v
53 | fmt.Println("cur:", string(cur))
54 | ans = dfs(digits, jp, l+1, cur)
55 | }
56 | return ans
57 | }
58 |
--------------------------------------------------------------------------------
/problems/0031.next-permutation/README.md:
--------------------------------------------------------------------------------
1 | # 31. Next Permutation
2 |
3 | ## 题目
4 |
5 | - English
6 |
7 | ```
8 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
9 |
10 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
11 |
12 | The replacement must be in-place and use only constant extra memory.
13 |
14 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
15 |
16 | 1,2,3 → 1,3,2
17 | 3,2,1 → 1,2,3
18 | 1,1,5 → 1,5,1
19 | ```
20 |
21 | - 中文
22 |
23 | ```
24 | 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
25 |
26 | 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
27 |
28 | 必须原地修改,只允许使用额外常数空间。
29 |
30 | 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
31 | 1,2,3 → 1,3,2
32 | 3,2,1 → 1,2,3
33 | 1,1,5 → 1,5,1
34 | ```
35 |
36 |
37 | ## 分析
38 |
39 | ```
40 | 这道题让我们求下一个排列顺序,有题目中给的例子可以看出来,如果给定数组是降序,则说明是全排列的最后一种情况,则下一个排列就是最初始情况,可以参见之前的博客 Permutations 全排列。我们再来看下面一个例子,有如下的一个数组
41 |
42 | 1 2 7 4 3 1
43 |
44 | 下一个排列为:
45 |
46 | 1 3 1 2 4 7
47 |
48 | 那么是如何得到的呢,我们通过观察原数组可以发现,如果从末尾往前看,数字逐渐变大,到了2时才减小的,然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可,步骤如下:
49 |
50 | 1 2 7 4 3 1
51 |
52 | 1 2 7 4 3 1
53 |
54 | 1 3 7 4 2 1
55 |
56 | 1 3 1 2 4 7
57 |
58 | ```
--------------------------------------------------------------------------------
/problems/0215.kth-largest-element-in-an-array/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0215.kth-largest-element-in-an-array
3 |
4 | ```English
5 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
6 |
7 | Example 1:
8 |
9 | Input: [3,2,1,5,6,4] and k = 2
10 | Output: 5
11 | Example 2:
12 |
13 | Input: [3,2,3,1,2,4,5,5,6] and k = 4
14 | Output: 4
15 | Note:
16 | You may assume k is always valid, 1 ≤ k ≤ array's length.
17 | ```
18 |
19 | ```Chinese
20 | 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
21 |
22 | 示例 1:
23 |
24 | 输入: [3,2,1,5,6,4] 和 k = 2
25 | 输出: 5
26 | 示例 2:
27 |
28 | 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
29 | 输出: 4
30 | 说明:
31 |
32 | 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
33 | ```
34 |
35 | ---
36 |
37 | 不同的 partition
38 |
39 | ```
40 | func partion(a []int, l int, r int)int{
41 | i, j := l, r
42 | v := a[r]
43 |
44 | for {
45 | for i < r && a[i] <= v {
46 | i++
47 | }
48 | for j >= l && a[j] >= v {
49 | j--
50 | }
51 |
52 | if i > j {
53 | break
54 | }
55 | a[i], a[j] = a[j], a[i]
56 | i++
57 | j++
58 | }
59 |
60 | a[i], a[r] = a[r], a[i]
61 | return i
62 |
63 | }
64 | ```
--------------------------------------------------------------------------------
/problems/0097.interleaving-string/run.go:
--------------------------------------------------------------------------------
1 | package string
2 |
3 | import "fmt"
4 |
5 | func isInterleave(s1 string, s2 string, s3 string) bool {
6 | l1, l2, l3 := len(s1), len(s2), len(s3)
7 | if l1+l2 != l3 {
8 | return false
9 | }
10 |
11 | // 二维初始化
12 | dp := make([][]bool, l2+1)
13 | for k := range dp {
14 | dp[k] = make([]bool, l1+1)
15 | }
16 | // 第一种方式
17 | // dp[0][0] = true
18 | // ldp := len(dp)
19 | // for i := 1; i < ldp; i++ {
20 | // dp[i][0] = dp[i-1][0] && s2[i-1] == s3[i-1]
21 | // }
22 | // ldpi := len(dp[0])
23 | // for i := 1; i < ldpi; i++ {
24 | // dp[0][i] = dp[0][i-1] && s1[i-1] == s3[i-1]
25 | // }
26 |
27 | // for i := 1; i < len(dp); i++ {
28 | // for j := 1; j < ldpi; j++ {
29 | // dp[i][j] = (dp[i-1][j] && s2[i-1] == s3[i+j-1]) ||
30 | // (dp[i][j-1] && s1[j-1] == s3[i+j-1])
31 | // }
32 | // }
33 |
34 | // 第二种方式
35 |
36 | for i := 0; i < l2+1; i++ {
37 | for j := 0; j < l1+1; j++ {
38 | switch {
39 | case i == 0 && j == 0:
40 | dp[i][j] = true
41 | case i == 0:
42 | dp[0][j] = dp[0][j-1] && s1[j-1] == s3[i+j-1]
43 | case j == 0:
44 | fmt.Println("i:", i)
45 | dp[i][0] = dp[i-1][0] && s2[i-1] == s3[i+j-1]
46 | default:
47 | dp[i][j] = (dp[i-1][j] && s2[i-1] == s3[i+j-1]) || (dp[i][j-1] && s1[j-1] == s3[i+j-1])
48 | }
49 | }
50 | }
51 | fmt.Println(dp)
52 | return dp[l2][l1]
53 | }
54 |
--------------------------------------------------------------------------------
/problems/0025.reverse-nodes-in-k-group/run.go:
--------------------------------------------------------------------------------
1 | package pairs
2 |
3 | import (
4 | "github.com/itcuihao/leetcode-go/structure"
5 | )
6 |
7 | //import "leetcode-go/structure"
8 |
9 | /**
10 | * Definition for singly-linked list.
11 | * type ListNode struct {
12 | * Val int
13 | * Next *ListNode
14 | * }
15 | */
16 |
17 | // 时间复杂度:0(n)
18 | // 空间复杂度:0(1)
19 | func reverseKGroup(head *structure.ListNode, k int) *structure.ListNode {
20 | if head == nil || head.Next == nil {
21 | return head
22 | }
23 |
24 | count := 0
25 | cur := head
26 |
27 | for cur != nil && count != k {
28 | cur = cur.Next
29 | count++
30 | }
31 |
32 | if count == k {
33 | cur = reverseKGroup(cur, k)
34 | for count > 0 {
35 | count--
36 | tmp := head.Next
37 | head.Next = cur
38 | cur = head
39 | head = tmp
40 | }
41 | head = cur
42 | }
43 | return head
44 | }
45 |
46 | func reverseKGroup2(head *structure.ListNode, k int) *structure.ListNode {
47 | node := head
48 | for i := 0; i < k; i++ {
49 | if node == nil {
50 | return head
51 | }
52 | node = node.Next
53 | }
54 | newHead := reverse(head, node)
55 | head.Next = reverseKGroup2(node, k)
56 | return newHead
57 | }
58 |
59 | func reverse(first *structure.ListNode, last *structure.ListNode) *structure.ListNode {
60 | prev := last
61 | for first != last {
62 | tmp := first.Next
63 | first.Next = prev
64 | prev = first
65 | first = tmp
66 | }
67 | return prev
68 | }
69 |
--------------------------------------------------------------------------------
/problems/0155.min-stack/run.go:
--------------------------------------------------------------------------------
1 | package stack
2 |
3 | type MinStack struct {
4 | Data []int
5 | MinIndex int
6 | }
7 |
8 | /** initialize your data structure here. */
9 | func Constructor() MinStack {
10 | return MinStack{
11 | Data: make([]int, 0),
12 | }
13 | }
14 |
15 | func (this *MinStack) Push(x int) {
16 | length := len(this.Data)
17 | if length > 0 && length >= this.MinIndex && this.Data[this.MinIndex] > x {
18 | this.MinIndex = length
19 | }
20 | this.Data = append(this.Data, x)
21 | }
22 |
23 | func (this *MinStack) Pop() {
24 | length := len(this.Data)
25 | if length == 0 {
26 | return
27 | }
28 | this.Data = this.Data[:length-1]
29 | if length-1 == this.MinIndex {
30 | this.MinIndex = 0
31 | for i := 0; i < len(this.Data); i++ {
32 | if this.Data[this.MinIndex] > this.Data[i] {
33 | this.MinIndex = i
34 | }
35 | }
36 | }
37 |
38 | }
39 |
40 | func (this *MinStack) Top() int {
41 | length := len(this.Data)
42 | if length == 0 || length < this.MinIndex {
43 | return 0
44 | }
45 | return this.Data[length-1]
46 | }
47 |
48 | func (this *MinStack) GetMin() int {
49 | if len(this.Data) == 0 || len(this.Data) < this.MinIndex {
50 | return 0
51 | }
52 | return this.Data[this.MinIndex]
53 | }
54 |
55 | /**
56 | * Your MinStack object will be instantiated and called as such:
57 | * obj := Constructor();
58 | * obj.Push(x);
59 | * obj.Pop();
60 | * param_3 := obj.Top();
61 | * param_4 := obj.GetMin();
62 | */
63 |
--------------------------------------------------------------------------------
/problems/0012.integer-to-roman/README.md:
--------------------------------------------------------------------------------
1 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
2 |
3 | Symbol Value
4 | I 1
5 | V 5
6 | X 10
7 | L 50
8 | C 100
9 | D 500
10 | M 1000
11 | For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
12 |
13 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
14 |
15 | I can be placed before V (5) and X (10) to make 4 and 9.
16 | X can be placed before L (50) and C (100) to make 40 and 90.
17 | C can be placed before D (500) and M (1000) to make 400 and 900.
18 | Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
19 |
20 | Example 1:
21 |
22 | Input: 3
23 | Output: "III"
24 | Example 2:
25 |
26 | Input: 4
27 | Output: "IV"
28 | Example 3:
29 |
30 | Input: 9
31 | Output: "IX"
32 | Example 4:
33 |
34 | Input: 58
35 | Output: "LVIII"
36 | Explanation: C = 100, L = 50, XXX = 30 and III = 3.
37 | Example 5:
38 |
39 | Input: 1994
40 | Output: "MCMXCIV"
41 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
--------------------------------------------------------------------------------
/problems/0392.is-subsequence/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0392.is-subsequence](https://leetcode.com/problems/is-subsequence/)
3 |
4 | ```English
5 | Given a string s and a string t, check if s is subsequence of t.
6 |
7 | You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
8 |
9 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).
10 |
11 | Example 1:
12 | s = "abc", t = "ahbgdc"
13 |
14 | Return true.
15 |
16 | Example 2:
17 | s = "axc", t = "ahbgdc"
18 |
19 | Return false.
20 |
21 | Follow up:
22 | If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
23 |
24 | Credits:
25 | Special thanks to @pbrother for adding this problem and creating all test cases.
26 | ```
27 |
28 | ```Chinese
29 | 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
30 |
31 | 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
32 |
33 | 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
34 |
35 | 示例 1:
36 | s = "abc", t = "ahbgdc"
37 |
38 | 返回 true.
39 |
40 | 示例 2:
41 | s = "axc", t = "ahbgdc"
42 |
43 | 返回 false.
44 |
45 | 后续挑战 :
46 |
47 | 如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
48 | ```
--------------------------------------------------------------------------------
/problems/0094.binary-tree-inorder-traversal/run.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | /**
4 | * Definition for a binary tree node.
5 | * type TreeNode struct {
6 | * Val int
7 | * Left *TreeNode
8 | * Right *TreeNode
9 | * }
10 | */
11 |
12 | // TreeNode tree
13 | type TreeNode struct {
14 | Val int
15 | Left *TreeNode
16 | Right *TreeNode
17 | }
18 |
19 | func inorderTraversal(root *TreeNode) []int {
20 | var l []int
21 | if root == nil {
22 | return l
23 | }
24 |
25 | l = append(l, inorderTraversal(root.Left)...)
26 | l = append(l, root.Val)
27 | l = append(l, inorderTraversal(root.Right)...)
28 |
29 | return l
30 | }
31 |
32 | func inorderFor(root *TreeNode) []int {
33 | var (
34 | l []int
35 | tempStack []*TreeNode
36 | )
37 |
38 | for root != nil || len(tempStack) > 0 {
39 | if root != nil {
40 | tempStack = append(tempStack, root)
41 | root = root.Left
42 | } else if len(tempStack) > 0 {
43 | root = tempStack[len(tempStack)-1]
44 | tempStack = tempStack[:len(tempStack)-1]
45 | l = append(l, root.Val)
46 | root = root.Right
47 | }
48 | }
49 | return l
50 | }
51 |
52 | func inorder(root *TreeNode) []int {
53 | var res []int
54 | if root == nil {
55 | return res
56 | }
57 | var stack []*TreeNode
58 |
59 | cur := root
60 | for cur != nil || len(stack) > 0 {
61 | for cur != nil {
62 | stack = append(stack, cur)
63 | cur = cur.Left
64 | }
65 | cur = stack[len(stack)-1]
66 | stack = stack[:len(stack)-1]
67 | res = append(res, cur.Val)
68 | cur = cur.Right
69 | }
70 | return res
71 | }
72 |
--------------------------------------------------------------------------------
/problems/0236.lowest-common-ancestor-of-a-binary-tree/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0236.lowest-common-ancestor-of-a-binary-tree
3 |
4 | 
5 |
6 | ```English
7 | Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
8 |
9 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
10 |
11 | Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
12 |
13 |
14 |
15 |
16 | Example 1:
17 |
18 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
19 | Output: 3
20 | Explanation: The LCA of nodes 5 and 1 is 3.
21 | Example 2:
22 |
23 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
24 | Output: 5
25 | Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
26 | ```
27 |
28 | ```Chinese
29 | 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
30 |
31 | 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
32 |
33 | 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
34 |
35 |
36 |
37 |
38 |
39 | 示例 1:
40 |
41 | 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
42 | 输出: 3
43 | 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
44 | 示例 2:
45 |
46 | 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
47 | 输出: 5
48 | 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
49 |
50 |
51 | 说明:
52 |
53 | 所有节点的值都是唯一的。
54 | p、q 为不同节点且均存在于给定的二叉树中。
55 | ```
--------------------------------------------------------------------------------
/problems/0010.regular-expression-matching/README.md:
--------------------------------------------------------------------------------
1 | Implement regular expression matching with support for '.' and '*'.
2 |
3 | ```
4 | '.' Matches any single character.
5 | '*' Matches zero or more of the preceding element.
6 |
7 | The matching should cover the entire input string (not partial).
8 |
9 | The function prototype should be:
10 | bool isMatch(const char *s, const char *p)
11 |
12 | Some examples:
13 | isMatch("aa","a") → false
14 | isMatch("aa","aa") → true
15 | isMatch("aaa","aa") → false
16 | isMatch("aa", "a*") → true
17 | isMatch("aa", ".*") → true
18 | isMatch("ab", ".*") → true
19 | isMatch("aab", "c*a*b") → true
20 | ```
21 |
22 | > 动态规划(英语:Dynamic programming,简称DP)是一种在数学、管理科学、计算机科学、经济学和生物信息学中使用的,通过把原问题分解为相对简单的子问题的方式求解复杂问题的方法。
23 | 动态规划常常适用于有重叠子问题[1]和最优子结构性质的问题,动态规划方法所耗时间往往远少于朴素解法。
24 | 动态规划背后的基本思想非常简单。大致上,若要解一个给定问题,我们需要解其不同部分(即子问题),再合并子问题的解以得出原问题的解。
25 | 通常许多子问题非常相似,为此动态规划法试图仅仅解决每个子问题一次,从而减少计算量:一旦某个给定子问题的解已经算出,则将其记忆化存储,以便下次需要同一个子问题解之时直接查表。这种做法在重复子问题的数目关于输入的规模呈指数增长时特别有用。
26 |
27 |
28 | ```
29 | 最优子结构性质。如果问题的最优解所包含的子问题的解也是最优的,我们就称该问题具有最优子结构性质(即满足最优化原理)。最优子结构性质为动态规划算法解决问题提供了重要线索。
30 | 无后效性。即子问题的解一旦确定,就不再改变,不受在这之后、包含它的更大的问题的求解决策影响。
31 | 子问题重叠性质。子问题重叠性质是指在用递归算法自顶向下对问题进行求解时,每次产生的子问题并不总是新问题,有些子问题会被重复计算多次。动态规划算法正是利用了这种子问题的重叠性质,对每一个子问题只计算一次,然后将其计算结果保存在一个表格中,当再次需要计算已经计算过的子问题时,只是在表格中简单地查看一下结果,从而获得较高的效率。
32 | ```
33 |
34 | [知乎-什么是动态规划](https://www.zhihu.com/question/23995189/answer/35429905?utm_medium=social&utm_source=weibo)
35 |
36 | [DP](https://zh.wikipedia.org/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92)
37 |
38 | [动态规划:从新手到专家](http://www.hawstein.com/posts/dp-novice-to-advanced.html)
--------------------------------------------------------------------------------
/problems/0013.roman-to-integer/README.md:
--------------------------------------------------------------------------------
1 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
2 |
3 | ```table
4 | Symbol Value
5 | I 1
6 | V 5
7 | X 10
8 | L 50
9 | C 100
10 | D 500
11 | M 1000
12 | ```
13 |
14 | For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
15 |
16 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
17 |
18 | I can be placed before V (5) and X (10) to make 4 and 9.
19 | X can be placed before L (50) and C (100) to make 40 and 90.
20 | C can be placed before D (500) and M (1000) to make 400 and 900.
21 | Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
22 |
23 | Example 1:
24 |
25 | Input: "III"
26 | Output: 3
27 | Example 2:
28 |
29 | Input: "IV"
30 | Output: 4
31 | Example 3:
32 |
33 | Input: "IX"
34 | Output: 9
35 | Example 4:
36 |
37 | Input: "LVIII"
38 | Output: 58
39 | Explanation: C = 100, L = 50, XXX = 30 and III = 3.
40 | Example 5:
41 |
42 | Input: "MCMXCIV"
43 | Output: 1994
44 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
45 |
46 | - 倒序遍历,当遇到左边元素比右边小的时候就减掉
--------------------------------------------------------------------------------
/problems/0027.remove-element/README.md:
--------------------------------------------------------------------------------
1 | # 27.Remove Element
2 |
3 | Given an array nums and a value val, remove all instances of that value in-place and return the new length.
4 |
5 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
6 |
7 | The order of elements can be changed. It doesn't matter what you leave beyond the new length.
8 |
9 | Example 1:
10 |
11 | ```
12 | Given nums = [3,2,2,3], val = 3,
13 |
14 | Your function should return length = 2, with the first two elements of nums being 2.
15 |
16 | It doesn't matter what you leave beyond the returned length.
17 | ```
18 |
19 | Example 2:
20 |
21 | ```
22 | Given nums = [0,1,2,2,3,0,4,2], val = 2,
23 |
24 | Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
25 |
26 | Note that the order of those five elements can be arbitrary.
27 |
28 | It doesn't matter what values are set beyond the returned length.
29 | ```
30 |
31 | Clarification:
32 |
33 | Confused why the returned value is an integer but your answer is an array?
34 |
35 | Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
36 |
37 | Internally you can think of this:
38 |
39 | ```
40 | // nums is passed in by reference. (i.e., without making a copy)
41 | int len = removeElement(nums, val);
42 |
43 | // any modification to nums in your function would be known by the caller.
44 | // using the length returned by your function, it prints the first len elements.
45 | for (int i = 0; i < len; i++) {
46 | print(nums[i]);
47 | }
48 | ```
49 |
--------------------------------------------------------------------------------
/problems/0141.linked-list-cycle/README.md:
--------------------------------------------------------------------------------
1 |
2 | # [0141.linked-list-cycle](https://leetcode.com/problems/linked-list-cycle/)
3 |
4 | 
5 |
6 | ```English
7 | Given a linked list, determine if it has a cycle in it.
8 |
9 | To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
10 |
11 |
12 |
13 | Example 1:
14 |
15 | Input: head = [3,2,0,-4], pos = 1
16 | Output: true
17 | Explanation: There is a cycle in the linked list, where tail connects to the second node.
18 |
19 |
20 | Example 2:
21 |
22 | Input: head = [1,2], pos = 0
23 | Output: true
24 | Explanation: There is a cycle in the linked list, where tail connects to the first node.
25 |
26 |
27 | Example 3:
28 |
29 | Input: head = [1], pos = -1
30 | Output: false
31 | Explanation: There is no cycle in the linked list.
32 |
33 |
34 |
35 |
36 | Follow up:
37 |
38 | Can you solve it using O(1) (i.e. constant) memory?
39 | ```
40 |
41 | ```Chinese
42 | 给定一个链表,判断链表中是否有环。
43 |
44 | 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
45 |
46 |
47 |
48 | 示例 1:
49 |
50 | 输入:head = [3,2,0,-4], pos = 1
51 | 输出:true
52 | 解释:链表中有一个环,其尾部连接到第二个节点。
53 |
54 |
55 | 示例 2:
56 |
57 | 输入:head = [1,2], pos = 0
58 | 输出:true
59 | 解释:链表中有一个环,其尾部连接到第一个节点。
60 |
61 |
62 | 示例 3:
63 |
64 | 输入:head = [1], pos = -1
65 | 输出:false
66 | 解释:链表中没有环。
67 |
68 |
69 |
70 |
71 | 进阶:
72 |
73 | 你能用 O(1)(即,常量)内存解决此问题吗?
74 | ```
75 |
76 | ```text
77 | 思路:
78 | 给两个指针,一个指针是另外一个指针的下一个。快指针一次走两步,慢指针走一步。
79 | 如果存在环,那么快指针会赶上慢指针。
80 | ```
--------------------------------------------------------------------------------
/problems/0146.lru-cache/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0146.lru-cache
3 |
4 | ```English
5 | Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
6 |
7 | get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
8 | put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
9 |
10 | Follow up:
11 | Could you do both operations in O(1) time complexity?
12 |
13 | Example:
14 |
15 | LRUCache cache = new LRUCache( 2 /* capacity */ );
16 |
17 | cache.put(1, 1);
18 | cache.put(2, 2);
19 | cache.get(1); // returns 1
20 | cache.put(3, 3); // evicts key 2
21 | cache.get(2); // returns -1 (not found)
22 | cache.put(4, 4); // evicts key 1
23 | cache.get(1); // returns -1 (not found)
24 | cache.get(3); // returns 3
25 | cache.get(4); // returns 4
26 | ```
27 |
28 | ```中文
29 | 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
30 |
31 | 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
32 | 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
33 |
34 | 进阶:
35 |
36 | 你是否可以在 O(1) 时间复杂度内完成这两种操作?
37 |
38 | 示例:
39 |
40 | LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
41 |
42 | cache.put(1, 1);
43 | cache.put(2, 2);
44 | cache.get(1); // 返回 1
45 | cache.put(3, 3); // 该操作会使得密钥 2 作废
46 | cache.get(2); // 返回 -1 (未找到)
47 | cache.put(4, 4); // 该操作会使得密钥 1 作废
48 | cache.get(1); // 返回 -1 (未找到)
49 | cache.get(3); // 返回 3
50 | cache.get(4); // 返回 4
51 | ```
--------------------------------------------------------------------------------
/problems/0008.string-to-integer/run.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | import (
4 | "math"
5 | "strings"
6 | )
7 |
8 | func myAtoi(str string) int {
9 | str = strings.TrimSpace(str)
10 |
11 | ls := len(str)
12 | if ls == 0 {
13 | return 0
14 | }
15 |
16 | myi, m, plus, less := 0, 1, false, false
17 | if str[0] == '-' {
18 | str = str[1:]
19 | less = true
20 | } else if str[0] == '+' {
21 | str = str[1:]
22 | plus = true
23 | }
24 |
25 | if plus || less {
26 | ls--
27 | }
28 |
29 | for k, v := range str {
30 | if v < 48 || v > 57 {
31 | str = str[:k]
32 | ls = k
33 | break
34 | }
35 | }
36 | for i := ls - 1; i >= 0; i-- {
37 | myi += int(str[i]-48) * m
38 | if isOver(myi) {
39 | if less {
40 | return math.MinInt32
41 | }
42 | return math.MaxInt32
43 | }
44 | m *= 10
45 | }
46 |
47 | if less {
48 | myi = ^myi + 1
49 | }
50 | return myi
51 | }
52 |
53 | func isOver(i int) bool {
54 | if i > math.MaxInt32 {
55 | return true
56 | } else if i < math.MinInt32 {
57 | return true
58 | }
59 | return false
60 | }
61 |
62 | func atoi(s string) int {
63 | s = strings.TrimSpace(s)
64 | if s == "" || s == "0" {
65 | return 0
66 | }
67 | firsts := s[0]
68 | sign := 1
69 | start := 0
70 | res := 0
71 | if firsts == '+' {
72 | sign = 1
73 | start++
74 | } else if firsts == '-' {
75 | sign = -1
76 | start++
77 | }
78 |
79 | for i := start; i < len(s); i++ {
80 | if s[i] < '0' || s[i] > '9' {
81 | return res * sign
82 | }
83 | p := int(s[i] - '0')
84 | res = res*10 + p
85 | if sign == 1 && res > math.MaxInt32 {
86 | return math.MaxInt32
87 | }
88 | if sign == -1 && res > math.MaxInt32 {
89 | return math.MinInt32
90 | }
91 | }
92 | return res * sign
93 | }
94 |
--------------------------------------------------------------------------------
/problems/0235.lowest-common-ancestor-of-a-binary-search-tree/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0235.lowest-common-ancestor-of-a-binary-search-tree
3 |
4 | 
5 | ```English
6 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
7 |
8 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
9 |
10 | Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
11 |
12 |
13 |
14 |
15 | Example 1:
16 |
17 | Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
18 | Output: 6
19 | Explanation: The LCA of nodes 2 and 8 is 6.
20 | Example 2:
21 |
22 | Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
23 | Output: 2
24 | Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
25 |
26 |
27 | Note:
28 |
29 | All of the nodes' values will be unique.
30 | p and q are different and both values will exist in the BST.
31 | ```
32 |
33 | ```
34 | 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
35 |
36 | 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
37 |
38 | 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
39 |
40 |
41 |
42 |
43 |
44 | 示例 1:
45 |
46 | 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
47 | 输出: 6
48 | 解释: 节点 2 和节点 8 的最近公共祖先是 6。
49 | 示例 2:
50 |
51 | 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
52 | 输出: 2
53 | 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
54 |
55 |
56 | 说明:
57 |
58 | 所有节点的值都是唯一的。
59 | p、q 为不同节点且均存在于给定的二叉搜索树中。
60 | ```
--------------------------------------------------------------------------------
/problems/0145.binary-tree-postorder-traversal/run.go:
--------------------------------------------------------------------------------
1 | package traversal
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | /**
8 | * Definition for a binary tree node.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *TreeNode
12 | * Right *TreeNode
13 | * }
14 | */
15 |
16 | // TreeNode tree
17 | type TreeNode struct {
18 | Val int
19 | Left *TreeNode
20 | Right *TreeNode
21 | }
22 |
23 | func postorderTraversal(root *TreeNode) []int {
24 | l := []int{}
25 | if root == nil {
26 | return l
27 | }
28 |
29 | l = append(l, postorderTraversal(root.Left)...)
30 | l = append(l, postorderTraversal(root.Right)...)
31 | l = append(l, root.Val)
32 | fmt.Println(l)
33 | return l
34 | }
35 |
36 | func portorderFor(root *TreeNode) []int {
37 | l := []int{}
38 | tempStack := []*TreeNode{}
39 |
40 | for root != nil || len(tempStack) > 0 {
41 | if root != nil {
42 | tempStack = append(tempStack, root)
43 | l = append(l, root.Val)
44 | root = root.Right
45 | } else {
46 | root = tempStack[len(tempStack)-1]
47 | tempStack = tempStack[:len(tempStack)-1]
48 | root = root.Left
49 | }
50 | }
51 | lt := len(l)
52 | for i := 0; i < lt/2; i++ {
53 | l[i], l[lt-i-1] = l[lt-i-1], l[i]
54 | }
55 | return l
56 | }
57 |
58 | func postorder(root *TreeNode) []int {
59 | var a []int
60 | stk := make([]*TreeNode, 0)
61 | var prev *TreeNode
62 | for root != nil || len(stk) > 0 {
63 | for root != nil {
64 | stk = append(stk, root)
65 | root = root.Left
66 | }
67 | root = stk[len(stk)-1]
68 | stk = stk[:len(stk)-1]
69 | if root.Right == nil || root.Right == prev {
70 | a = append(a, root.Val)
71 | prev = root
72 | root = nil
73 | } else {
74 | stk = append(stk, root)
75 | root = root.Right
76 | }
77 | }
78 | return a
79 | }
80 |
--------------------------------------------------------------------------------
/problems/0029.divide-two-integers/README.md:
--------------------------------------------------------------------------------
1 | # 29. Divide Two Integers
2 |
3 | ## 题干
4 |
5 | - English
6 |
7 | ```
8 | Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
9 |
10 | Return the quotient after dividing dividend by divisor.
11 |
12 | The integer division should truncate toward zero.
13 |
14 | Example 1:
15 |
16 | Input: dividend = 10, divisor = 3
17 | Output: 3
18 | Example 2:
19 |
20 | Input: dividend = 7, divisor = -3
21 | Output: -2
22 | Note:
23 |
24 | Both dividend and divisor will be 32-bit signed integers.
25 | The divisor will never be 0.
26 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
27 | ```
28 |
29 | - 中文
30 |
31 | ```
32 | 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
33 |
34 | 返回被除数 dividend 除以除数 divisor 得到的商。
35 |
36 | 示例 1:
37 |
38 | 输入: dividend = 10, divisor = 3
39 | 输出: 3
40 | 示例 2:
41 |
42 | 输入: dividend = 7, divisor = -3
43 | 输出: -2
44 | 说明:
45 |
46 | 被除数和除数均为 32 位有符号整数。
47 | 除数不为 0。
48 | 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
49 | ```
50 |
51 | ## 题目分析
52 |
53 | ```
54 | 1. 被除数/除数=商 (忽略余数)=> 被除数=除数*商。
55 |
56 | 2. 商(任意整数)可以表示为:a_0*2^0+a_1*2^1+...a_i*2^i+...+a_n*2^n.
57 |
58 | 3. 在Java中左移操作<<相当于对一个数乘以2,右移操作相当于除以2.
59 |
60 | 4.我们让除数左移直到大于被除数前的的一个数,例如计算28/3,我们进行三次左移操作,使3*2*2*2=3*8=24<28(注意四次左移操作得到3*2^4=48>28).记录下2*2*2=2^3=8.
61 |
62 | 5.我们让28减去24得到4,然后像第四步一样计算4/3,则3*2^0=3<4.记录下2^0=1.
63 |
64 | 6.由于4-3=1小于除数3,停止计算,并将每轮得到的值相加,在本例中8+1=9,记得到商(即28/3=9)。
65 |
66 | 至此,程序的主题思想已经介绍完了,接下来要注意数据左移和求整数绝对值的边界问题。
67 |
68 | 7. 将输入的Int(32位)型数字转换为long(64位)型。
69 |
70 | 8. 考虑MIN_VALUE/-1的特殊情况。
71 | ```
72 |
--------------------------------------------------------------------------------
/problems/0015.3sum/run.go:
--------------------------------------------------------------------------------
1 | package threesum
2 |
3 | import (
4 | "fmt"
5 | "sort"
6 | )
7 |
8 | // 穷举无法通过时间限制
9 | func threeSum1(nums []int) [][]int {
10 | var data [][]int
11 | if len(nums) < 3 {
12 | return data
13 | }
14 | b := true
15 | for _, v := range nums {
16 | if v != 0 {
17 | b = false
18 | }
19 | }
20 | if b {
21 | data = append(data, []int{0, 0, 0})
22 | return data
23 | }
24 | cm := make(map[string]bool)
25 | for i := 0; i < len(nums); i++ {
26 | for j := i + 1; j < len(nums); j++ {
27 | for k := j + 1; k < len(nums); k++ {
28 | if nums[i]+nums[j]+nums[k] == 0 {
29 | if _, ok := cm[min(nums[i], nums[j], nums[k])]; ok {
30 | continue
31 | }
32 |
33 | cm[min(nums[i], nums[j], nums[k])] = true
34 | data = append(data, []int{nums[i], nums[j], nums[k]})
35 | }
36 | }
37 | }
38 | }
39 | return data
40 | }
41 |
42 | func min(i, j, k int) string {
43 | var t int
44 | if i > j {
45 | t, i = i, j
46 | j = t
47 | }
48 | if i > k {
49 | t, i = i, k
50 | k = t
51 | }
52 | if j > k {
53 | t, j = j, k
54 | k = t
55 | }
56 | return fmt.Sprintf("%d%d%d", i, j, k)
57 | }
58 |
59 | func threeSum(nums []int) [][]int {
60 | var data [][]int
61 | ln := len(nums)
62 | if ln < 3 {
63 | return data
64 | }
65 | target := 0
66 | sort.Ints(nums)
67 | for i := 0; i < ln-2; i++ {
68 | if i > 0 && nums[i] == nums[i-1] {
69 | continue
70 | }
71 | l, r := i+1, ln-1
72 |
73 | for l < r {
74 | sum := nums[i] + nums[l] + nums[r]
75 | if sum < target {
76 | l++
77 | } else if sum > target {
78 | r--
79 | } else {
80 |
81 | tmp := []int{nums[i], nums[l], nums[r]}
82 | data = append(data, tmp)
83 |
84 | l++
85 | r--
86 | for l < r && nums[l] == nums[l-1] {
87 | l++
88 | }
89 | for l < r && nums[r] == nums[r+1] {
90 | r--
91 | }
92 | }
93 | }
94 |
95 | }
96 | return data
97 | }
98 |
--------------------------------------------------------------------------------
/problems/0002.add-two-numbers/run.go:
--------------------------------------------------------------------------------
1 | package numbers
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | /**
8 | * Definition for singly-linked list.
9 | * type ListNode struct {
10 | * Val int
11 | * Next *ListNode
12 | * }
13 | */
14 |
15 | // ListNode 存储
16 | type ListNode struct {
17 | Val int
18 | Next *ListNode
19 | }
20 |
21 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
22 | r := new(ListNode)
23 | temp, old := r, 0
24 |
25 | for {
26 |
27 | l1 = nonil(l1)
28 | l2 = nonil(l2)
29 |
30 | n := l1.Val + l2.Val + old
31 | if n > 9 {
32 | n -= 10
33 | old = 1
34 | } else {
35 | old = 0
36 | }
37 |
38 | temp.Val = n
39 |
40 | // 准备下一个
41 | l1 = next(l1)
42 | l2 = next(l2)
43 |
44 | if l1 == nil && l2 == nil {
45 | break
46 | }
47 |
48 | // 下一节点
49 | temp.Next = new(ListNode)
50 | temp = temp.Next
51 | }
52 |
53 | if old == 1 {
54 | temp.Next = &ListNode{Val: old}
55 | }
56 |
57 | return r
58 | }
59 |
60 | // 下一个节点
61 | func next(ln *ListNode) *ListNode {
62 | if ln != nil {
63 | return ln.Next
64 | }
65 | return nil
66 | }
67 |
68 | // 节点不能为nil
69 | func nonil(ln *ListNode) *ListNode {
70 | if ln != nil {
71 | return ln
72 | }
73 | return &ListNode{Val: 0}
74 | }
75 |
76 | // 生成ListNode
77 | func makeListNode(s []int) *ListNode {
78 | if len(s) == 0 {
79 | return nil
80 | }
81 |
82 | ln := new(ListNode)
83 | ln.Val = s[0]
84 |
85 | temp := ln
86 | for i := 1; i < len(s); i++ {
87 | temp.Next = &ListNode{Val: s[i]}
88 | temp = temp.Next
89 | }
90 |
91 | return ln
92 | }
93 |
94 | // 打印ListNode
95 | func printLN(ln *ListNode) {
96 | if ln == nil {
97 | return
98 | }
99 | i := 1
100 | for {
101 | fmt.Printf("%d:%d\n", i, ln.Val)
102 | fmt.Printf("%d:%+v\n", i, ln.Next)
103 | if ln.Next != nil {
104 | ln = ln.Next
105 | i++
106 | } else {
107 | break
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/problems/0155.min-stack/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 0155.min-stack
3 |
4 | ```
5 | 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
6 |
7 | push(x) —— 将元素 x 推入栈中。
8 | pop() —— 删除栈顶的元素。
9 | top() —— 获取栈顶元素。
10 | getMin() —— 检索栈中的最小元素。
11 |
12 |
13 | 示例:
14 |
15 | 输入:
16 | ["MinStack","push","push","push","getMin","pop","top","getMin"]
17 | [[],[-2],[0],[-3],[],[],[],[]]
18 |
19 | 输出:
20 | [null,null,null,null,-3,null,0,-2]
21 |
22 | 解释:
23 | MinStack minStack = new MinStack();
24 | minStack.push(-2);
25 | minStack.push(0);
26 | minStack.push(-3);
27 | minStack.getMin(); --> 返回 -3.
28 | minStack.pop();
29 | minStack.top(); --> 返回 0.
30 | minStack.getMin(); --> 返回 -2.
31 |
32 |
33 | 提示:
34 |
35 | pop、top 和 getMin 操作总是在 非空栈 上调用。
36 |
37 | 来源:力扣(LeetCode)
38 | 链接:https://leetcode-cn.com/problems/min-stack
39 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
40 | ```
41 |
42 | ```text
43 | type MinStack struct {
44 | Data []int
45 | MinIndex int
46 | }
47 | 该实现的执行结果
48 |
49 | 执行用时 :
50 | 20 ms
51 | , 在所有 Go 提交中击败了
52 | 78.89%
53 | 的用户
54 | 内存消耗 :
55 | 7.5 MB
56 | , 在所有 Go 提交中击败了
57 | 75.00%
58 | 的用户
59 | ```
60 |
61 | 执行8ms的例子,利用一个数组存取对应的最小值,空间换时间,消除循环。
62 | ```text
63 | type MinStack struct {
64 | data []int
65 | minData []int
66 | size int
67 | }
68 |
69 |
70 | /** initialize your data structure here. */
71 | func Constructor() MinStack {
72 | return MinStack{
73 | data: make([]int, 0),
74 | minData: make([]int, 0),
75 | size: 0,
76 | }
77 | }
78 |
79 |
80 | func (this *MinStack) Push(x int) {
81 | if this.size == 0 {
82 | this.minData = append(this.minData, x)
83 | } else if this.minData[this.size-1] > x {
84 | this.minData = append(this.minData, x)
85 | } else {
86 | this.minData = append(this.minData, this.minData[this.size-1])
87 | }
88 | this.data = append(this.data, x)
89 | this.size++
90 | }
91 |
92 |
93 | func (this *MinStack) Pop() {
94 | this.data = this.data[:this.size-1]
95 | this.minData = this.minData[:this.size-1]
96 | this.size--
97 | }
98 |
99 |
100 | func (this *MinStack) Top() int {
101 | return this.data[this.size-1]
102 | }
103 |
104 |
105 | func (this *MinStack) GetMin() int {
106 | return this.minData[this.size-1]
107 | }
108 |
109 | ```
--------------------------------------------------------------------------------
/problems/0005.longest-palindromic-substring/run_test.go:
--------------------------------------------------------------------------------
1 | package substring
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestIsPalindrome(t *testing.T) {
8 | s := "abab"
9 | // s := "ababa"
10 | t.Log(isPalindrome(s))
11 | }
12 | func TestLongestPalindrome(t *testing.T) {
13 | // s := "abab"
14 | // s := "ababac"
15 | // s := "babad"
16 | // s := "cbbd"
17 | // s := "abcda"
18 | s := "civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"
19 | t.Log(longestPalindrome(s))
20 | }
21 |
22 | func TestHandleString(t *testing.T) {
23 | s := "ab"
24 | t.Log(handleString(s))
25 | }
26 |
27 | func TestManacher(t *testing.T) {
28 | // s := "abaabaa"
29 | s := "civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"
30 | t.Log(manacher(s))
31 | }
32 |
--------------------------------------------------------------------------------
/create/run.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "io/ioutil"
7 | "log"
8 | "os"
9 | "strings"
10 | )
11 |
12 | func main() {
13 | var (
14 | dir string
15 | topic string
16 | num int
17 | )
18 |
19 | flag.StringVar(&dir, "f", "../problems", "生成的目录")
20 | flag.IntVar(&num, "n", 0, "题号")
21 | flag.StringVar(&topic, "t", "code", "题目")
22 |
23 | flag.Parse()
24 | path := getPath(dir, topic, num)
25 |
26 | Create(path)
27 | }
28 |
29 | func getPath(f, t string, n int) string {
30 | return fmt.Sprintf("%s/%s.%s", f, qnum(n), t)
31 | }
32 |
33 | func qnum(n int) string {
34 | return fmt.Sprintf("%04d", n)
35 | }
36 |
37 | var (
38 | err error
39 | )
40 |
41 | func Create(path string) {
42 |
43 | if of, oerr := os.Stat(path); oerr == nil && of.IsDir() {
44 | log.Printf("%s is dir", path)
45 | return
46 | } else if os.IsExist(oerr) {
47 | log.Printf("%s is exist", path)
48 | return
49 | }
50 |
51 | log.Printf("path is %s", path)
52 | ps := strings.Split(path, "/")
53 | if len(ps) != 3 {
54 | return
55 | }
56 |
57 | rp := ps[2]
58 | pnames := strings.Split(rp, ".")[len(strings.Split(rp, "."))-1]
59 | pname := strings.Split(pnames, "-")[len(strings.Split(rp, "-"))-1]
60 |
61 | funcn := "Run"
62 |
63 | err = os.MkdirAll(path, os.ModePerm)
64 | if err != nil {
65 | log.Fatal(err)
66 | }
67 | fname := fmt.Sprintf("%s/run.go", path)
68 |
69 | _, err = os.Create(fname)
70 | if err != nil {
71 | fmt.Println(err)
72 | log.Fatal(err)
73 | }
74 |
75 | rf, err := os.OpenFile(
76 | fname,
77 | os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
78 | 0666)
79 | if err != nil {
80 | log.Fatal(err)
81 | }
82 | defer rf.Close()
83 |
84 | byteF := []byte(fmt.Sprintf(runs, pname, funcn))
85 | _, err = rf.Write(byteF)
86 | if err != nil {
87 | log.Fatal(err)
88 | }
89 |
90 | tname := fmt.Sprintf("%s/run_test.go", path)
91 | err = ioutil.WriteFile(tname, []byte(fmt.Sprintf(runt, pname, funcn, funcn)), os.ModePerm)
92 | if err != nil {
93 | fmt.Println(err)
94 | }
95 |
96 | rname := fmt.Sprintf("%s/README.md", path)
97 |
98 | err = ioutil.WriteFile(rname, []byte(fmt.Sprintf(readme, rp)), os.ModePerm)
99 | if err != nil {
100 | fmt.Println(err)
101 | }
102 | }
103 |
104 | var runs = `
105 | package %s
106 |
107 | func %s() {
108 |
109 | }
110 | `
111 | var runt = `
112 | package %s
113 |
114 | import "testing"
115 |
116 | func Test%s(t *testing.T) {
117 | %s()
118 | }
119 | `
120 |
121 | var readme = `
122 | # %s
123 |
124 | `
125 |
--------------------------------------------------------------------------------
/structure/init.go:
--------------------------------------------------------------------------------
1 | package structure
2 |
3 | var BinarySearchTree = &TreeNode{
4 | Val: 6,
5 | Left: &TreeNode{
6 | Val: 2,
7 | Left: &TreeNode{
8 | Val: 0,
9 | },
10 | Right: &TreeNode{
11 | Val: 4,
12 | Left: &TreeNode{
13 | Val: 3,
14 | },
15 | Right: &TreeNode{
16 | Val: 5,
17 | },
18 | },
19 | },
20 | Right: &TreeNode{
21 | Val: 8,
22 | Left: &TreeNode{
23 | Val: 7,
24 | },
25 | Right: &TreeNode{
26 | Val: 9,
27 | },
28 | },
29 | }
30 |
31 | var BinaryTree = &TreeNode{
32 | Val: 3,
33 | Left: &TreeNode{
34 | Val: 5,
35 | Left: &TreeNode{
36 | Val: 6,
37 | },
38 | Right: &TreeNode{
39 | Val: 2,
40 | Left: &TreeNode{
41 | Val: 7,
42 | },
43 | Right: &TreeNode{
44 | Val: 4,
45 | },
46 | },
47 | },
48 | Right: &TreeNode{
49 | Val: 1,
50 | Left: &TreeNode{
51 | Val: 0,
52 | },
53 | Right: &TreeNode{
54 | Val: 8,
55 | },
56 | },
57 | }
58 |
59 | var BinaryTree101 = &TreeNode{
60 | Val: 1,
61 | Left: &TreeNode{
62 | Val: 2,
63 | Left: &TreeNode{
64 | Val: 3,
65 | },
66 | },
67 | Right: &TreeNode{
68 | Val: 2,
69 | Right: &TreeNode{
70 | Val: 3,
71 | },
72 | },
73 | }
74 |
75 | var ListNodeA = &ListNode{
76 | Val: 0,
77 | Next: &ListNode{
78 | Val: 9,
79 | Next: &ListNode{
80 | Val: 1,
81 | Next: &ListNode{
82 | Val: 2,
83 | Next: &ListNode{
84 | Val: 4,
85 | },
86 | },
87 | },
88 | },
89 | }
90 |
91 | var ListNodeB = &ListNode{
92 | Val: 3,
93 | Next: &ListNode{
94 | Val: 2,
95 | Next: &ListNode{
96 | Val: 4,
97 | },
98 | },
99 | }
100 |
101 | var ListNode82 = &ListNode{
102 | Val: 1,
103 | Next: &ListNode{
104 | Val: 2,
105 | Next: &ListNode{
106 | Val: 3,
107 | Next: &ListNode{
108 | Val: 3,
109 | Next: &ListNode{
110 | Val: 4,
111 | Next: &ListNode{
112 | Val: 4,
113 | Next: &ListNode{
114 | Val: 5,
115 | },
116 | },
117 | },
118 | },
119 | },
120 | },
121 | }
122 |
123 | var ListNodeCycle = &ListNode{
124 | Val: 3,
125 | Next: &ListNode{
126 | Val: 2,
127 | Next: &ListNode{
128 | Val: 0,
129 | Next: &ListNode{
130 | Val: 4,
131 | Next: &ListNode{
132 | Val: 2,
133 | },
134 | },
135 | },
136 | },
137 | }
138 |
139 | var BinaryTree98 = &TreeNode{
140 | Val: 2,
141 | Left: &TreeNode{
142 | Val: 1,
143 | },
144 | Right: &TreeNode{
145 | Val: 3,
146 | },
147 | //Right: &TreeNode{
148 | // Val: 7,
149 | // Left: &TreeNode{
150 | // Val: 6,
151 | // },
152 | // Right: &TreeNode{
153 | // Val: 8,
154 | // },
155 | //},
156 | }
157 |
--------------------------------------------------------------------------------