├── 0001-two-sum ├── main.go ├── main_test.go └── readme.md ├── 0002-add-two-numbers ├── main.go ├── main_test.go └── readme.md ├── 0003-longest-substring-without-repeating-characters ├── main.go ├── main_test.go └── readme.md ├── 0005-longest-palindromic-substring ├── main.go ├── main_test.go └── readme.md ├── 0009-palindrome-number ├── main.go ├── main_test.go └── readme.md ├── 0018-4sum └── main.go ├── 0022-generate-parentheses └── main.go ├── 0031-next-permutation └── main.go ├── 0035-search-insert-position ├── main.go └── main_test.go ├── 0038-count-and-say ├── main.go └── main_test.go ├── 0039-combination-sum └── main.go ├── 0041-first-missing-positive ├── main.go ├── main_test.go └── readme.md ├── 0042-trapping-rain-water ├── main.go ├── main_test.go └── readme.md ├── 0045-jump-game-ii └── main.go ├── 0046-permutations └── main.go ├── 0047-permutations-ii └── main.go ├── 0051-n-queens └── main.go ├── 0052-n-queens-ii └── main.go ├── 0053-maximum-subarray ├── main.go ├── main_test.go └── readme.md ├── 0055-jump-game └── main.go ├── 0058-length-of-last-word └── main.go ├── 0064-minimum-path-sum └── main.go ├── 0066-plus-one └── main.go ├── 0073-set-matrix-zeroes └── main.go ├── 0077-combinations └── main.go ├── 0078-subsets └── main.go ├── 0082-remove-duplicates-from-sorted-list-ii └── main.go ├── 0083-remove-duplicates-from-sorted-list └── main.go ├── 0090-subsets-ii ├── eq.go └── main.go ├── 0098-validate-binary-search-tree ├── main.go ├── main_test.go └── readme.md ├── 0101-symmetric-tree └── main.go ├── 0102-binary-tree-level-order-traversal ├── main.go ├── main_test.go └── readme.md ├── 0103-binary-tree-zigzag-level-order-traversal └── main.go ├── 0107-binary-tree-level-order-traversal-ii └── main.go ├── 0110-balanced-binary-tree └── main.go ├── 0111-minimum-depth-of-binary-tree └── main.go ├── 0112-path-sum └── main.go ├── 0113-path-sum-ii └── main.go ├── 0118-pascals-triangle └── main.go ├── 0119-pascals-triangle-ii └── main.go ├── 0125-valid-palindrome ├── main.go ├── main_test.go └── readme.md ├── 0128-longest-consecutive-sequence ├── main.go ├── main_test.go └── readme.md ├── 0129-sum-root-to-leaf-numbers └── main.go ├── 0137-single-number-ii └── main.go ├── 0139-word-break ├── main.go └── main_time_exceed.go ├── 0140-word-break-ii ├── main.go └── readme.md ├── 0141-linked-list-cycle └── main.cc ├── 0142-linked-list-cycle-ii └── main.cc ├── 0152-maximum-product-subarray ├── main.go ├── main_test.go └── readme.md ├── 0155-min-stack ├── main.go ├── main_test.go └── readme.md ├── 0162-find-peak-element ├── main.go ├── main_test.go └── readme.md ├── 0167-two-sum-ii-input-array-is-sorted └── main.go ├── 0179-largest-number ├── main.go ├── main_test.go └── readme.md ├── 0191-number-of-1-bits └── main.c ├── 0202-happy-number └── main.go ├── 0203-remove-linked-list-elements └── main.go ├── 0204-count-primes └── main.go ├── 0205-isomorphic-strings └── main.go ├── 0216-combination-sum-iii └── main.go ├── 0219-contains-duplicate-ii └── main.go ├── 0231-power-of-two └── main.go ├── 0232-implement-queue-using-stacks └── main.go ├── 0235-lowest-common-ancestor-of-a-binary-search-tree └── main.cc ├── 0237-delete-node-in-a-linked-list └── main.go ├── 0257-binary-tree-paths └── main.go ├── 0260-single-number-iii └── main.go ├── 0263-ugly-number └── main.go ├── 0283-move-zeroes └── main.go ├── 0292-nim-game └── main.go ├── 0338-counting-bits └── main.go ├── 0342-power-of-four └── main.go ├── 0345-reverse-vowels-of-a-string └── main.go ├── 0349-intersection-of-two-arrays └── main.go ├── 0350-intersection-of-two-arrays-ii └── main.go ├── 0383-ransom-note └── main.go ├── 0384-shuffle-an-array └── main.go ├── 0389-find-the-difference └── main.go ├── 0404-sum-of-left-leaves └── main.go ├── 0412-fizz-buzz └── main.go ├── 0415-add-strings └── main.go ├── 0434-number-of-segments-in-a-string └── main.go ├── 0459-repeated-substring-pattern └── main.go ├── 0461-hamming-distance └── main.go ├── 0476-number-complement └── main.go ├── 0486-max-consecutive-ones └── main.go ├── 0496-next-greater-element-i └── main.go ├── 0500-keyboard-row └── main.go ├── 0503-next-greater-element-ii └── main.go ├── 0504-base-7 └── main.go ├── 0515-find-largest-value-in-each-tree-row └── main.go ├── 0540-single-element-in-a-sorted-array └── main.go ├── 0551-student-attendance-record-i └── main.go ├── 0556-next-greater-element-iii └── main.go ├── 0560-subarray-sum-equals-k └── main.go ├── 0575-distribute-candies └── main.go ├── 0594-longest-harmonious-subsequence └── main.go ├── 0599-minimum-index-sum-of-two-lists └── main.go ├── 0606-construct-string-from-binary-tree └── main.go ├── 0617-merge-two-binary-trees └── main.go ├── 0653-two-sum-iv-input-is-a-bst └── main.go ├── 0657-judge-route-circle └── main.go ├── 0665-non-decreasing-array └── main.go ├── 0674-longest-continuous-increasing-subsequence └── main.go ├── 0686-repeated-string-match └── main.go ├── 0693-binary-number-with-alternating-bits └── main.go ├── 0700-search-in-a-binary-search-tree └── main.go ├── 0704-binary-search └── main.go ├── 0717-1-bit-and-2-bit-characters └── main.go ├── 0724-find-pivot-index └── main.go ├── 0728-self-dividing-numbers └── main.go ├── 0744-find-smallest-letter-greater-than-target └── main.go ├── 0747-largest-number-at-least-twice-of-others └── main.go ├── 0762-prime-number-of-set-bits-in-binary-representation └── main.go ├── 0771-jewels-and-stones └── main.go ├── 0778-swim-in-rising-water ├── main.go └── readme.md ├── 0783-minimum-distance-between-bst-nodes └── main.go ├── 0784-letter-case-permutation └── main.go ├── 0785-is-graph-bipartite └── main.go ├── 0788-rotated-digits └── main.go ├── 0791-custom-sort-string └── main.go ├── 0796-rotate-string └── main.go ├── 0797-all-paths-from-source-to-target └── main.go ├── 0811-subdomain-visit-count └── main.go ├── 0819-most-common-word └── main.go ├── 0821-shortest-distance-to-a-character └── main.go ├── 0829-consecutive-numbers-sum ├── main.go ├── main_test.go └── readme.md ├── 0830-positions-of-large-groups └── main.go ├── 0832-flipping-an-image ├── main.go ├── main_test.go └── readme.md ├── 0836-rectangle-overlap └── main.go ├── 0841-keys-and-rooms └── main.go ├── 0844-backspace-string-compare └── main.go ├── 0845-longest-mountain-in-array └── main.go ├── 0849-maximize-distance-to-closest-person └── main.go ├── 0852-peak-index-in-a-mountain-array └── main.go ├── 0856-score-of-parentheses ├── main.go ├── main_test.go └── readme.md ├── 0859-buddy-strings └── main.go ├── 0860-lemonade-change └── main.go ├── 0865-smallest-subtree-with-all-the-deepest-nodes └── main.go ├── 0867-transpose-matrix └── main.go ├── 0868-binary-gap └── main.go ├── 0872-leaf-similar-trees ├── main.go ├── main_test.go └── readme.md ├── 0873-length-of-longest-fibonacci-subsequence ├── main.go ├── main_test.go └── readme.md ├── 0875-koko-eating-bananas ├── main.go ├── main_test.go └── readme.md ├── 0876-middle-of-the-linked-list └── main.go ├── 0877-stone-game ├── main.go └── main_test.go ├── 0878-nth-magical-number └── main.go ├── 0880-decoded-string-at-index └── main.go ├── 0881-boats-to-save-people └── main.go ├── 0883-projection-area-of-3d-shapes └── main.go ├── 0884-uncommon-words-from-two-sentences └── main.go ├── 0885-spiral-matrix-iii └── main.go ├── 0886-possible-bipartition └── main.go ├── 0887-super-egg-drop └── main.go ├── 0888-fair-candy-swap └── main.go ├── 0890-find-and-replace-pattern ├── main.go └── readme.md ├── 0891-sum-of-subsequence-widths ├── main.go └── readme.md ├── 0892-surface-area-of-3d-shapes └── main.go ├── 0893-groups-of-special-equivalent-strings └── main.go ├── 0894-all-possible-full-binary-trees └── main.go ├── 0895-maximum-frequency-stack └── main.go ├── 0896-monotonic-array └── main.go ├── 0898-bitwise-ors-of-subarrays ├── main.go ├── readme.md └── time_exceed.go ├── 0899-orderly-queue └── main.go ├── 0900-rle-iterator └── main.go ├── 0901-online-stock-span └── main.go ├── 0904-fruit-into-baskets └── main.go ├── 0905-sort-array-by-parity └── main.go ├── A_N_K ├── main.go ├── main_test.go ├── readme.md └── recursive.go ├── BINARY_SEARCH └── bs.go ├── BITMAP └── readme.md ├── C_N_K └── readme.md ├── DFS_BFS └── readme.md ├── HIGH_PRECISION └── readme.md ├── NEXT_PERMUTATION └── main.go ├── SEGMENT_TREE └── readme.md ├── SORT ├── heapsort.go ├── mergesort.go ├── quicksort.go └── readme.md └── readme.md /0001-two-sum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func twoSum(nums []int, target int) []int { 4 | var numMap = map[int][]int{} 5 | for idx, num := range nums { 6 | numMap[num] = append(numMap[num], idx) 7 | } 8 | 9 | var indexMap = []int{} 10 | 11 | for i := 0; i < len(nums); i++ { 12 | cur := nums[i] 13 | left := target - cur 14 | if cur == left { 15 | if len(numMap[cur]) != 2 { 16 | continue 17 | } 18 | indexMap = numMap[cur] 19 | break 20 | } else if _, ok := numMap[left]; ok { 21 | indexMap = []int{i, numMap[left][0]} 22 | break 23 | } 24 | } 25 | 26 | return indexMap 27 | } 28 | -------------------------------------------------------------------------------- /0001-two-sum/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | // Case test definition 10 | type Case struct { 11 | nums []int 12 | target int 13 | expectedResult []int 14 | } 15 | 16 | func TestTwoSum(t *testing.T) { 17 | var cases = []Case{ 18 | Case{nums: []int{1, 2, 3, 4, 5}, 19 | target: 8, 20 | expectedResult: []int{2, 4}, 21 | }, 22 | Case{nums: []int{1, 2, 3, 4, 5}, 23 | target: 9, 24 | expectedResult: []int{3, 4}, 25 | }, 26 | Case{nums: []int{3, 2, 4}, 27 | target: 6, 28 | expectedResult: []int{1, 2}, 29 | }, 30 | } 31 | 32 | for _, cas := range cases { 33 | result := twoSum(cas.nums, cas.target) 34 | assert.Equal(t, 2, len(result)) 35 | assert.Equal(t, result[0], cas.expectedResult[0]) 36 | assert.Equal(t, result[1], cas.expectedResult[1]) 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /0001-two-sum/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/two-sum/description/ 4 | 5 | # desc 6 | 7 | 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 8 | 9 | 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 10 | 11 | 示例: 12 | 13 | ``` 14 | 给定 nums = [2, 7, 11, 15], target = 9 15 | 16 | 因为 nums[0] + nums[1] = 2 + 7 = 9 17 | 所以返回 [0, 1] 18 | ``` 19 | -------------------------------------------------------------------------------- /0002-add-two-numbers/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // ListNode ... 4 | /** 5 | * Definition for singly-linked list. 6 | * type ListNode struct { 7 | * Val int 8 | * Next *ListNode 9 | * } 10 | */ 11 | type ListNode struct { 12 | Val int 13 | Next *ListNode 14 | } 15 | 16 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 17 | var res = &ListNode{} 18 | cur := res 19 | for { 20 | if l1 != nil { 21 | cur.Val += l1.Val 22 | l1 = l1.Next 23 | } 24 | 25 | if l2 != nil { 26 | cur.Val += l2.Val 27 | l2 = l2.Next 28 | } 29 | 30 | if l1 == nil && l2 == nil { 31 | break 32 | } 33 | 34 | cur.Next = &ListNode{} 35 | cur = cur.Next 36 | } 37 | 38 | // 进位 39 | cur = res 40 | for cur != nil { 41 | if cur.Val >= 10 { 42 | if cur.Next == nil { 43 | cur.Next = &ListNode{} 44 | } 45 | 46 | cur.Val = cur.Val - 10 47 | cur.Next.Val++ 48 | } 49 | 50 | cur = cur.Next 51 | } 52 | 53 | return res 54 | } 55 | -------------------------------------------------------------------------------- /0002-add-two-numbers/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestAddTwoNumbers(t *testing.T) { 10 | l1 := &ListNode{ 11 | Val: 2, 12 | Next: &ListNode{ 13 | Val: 4, 14 | Next: &ListNode{ 15 | Val: 3, 16 | Next: nil, 17 | }, 18 | }, 19 | } 20 | 21 | l2 := &ListNode{ 22 | Val: 5, 23 | Next: &ListNode{ 24 | Val: 6, 25 | Next: &ListNode{ 26 | Val: 4, 27 | Next: nil, 28 | }, 29 | }, 30 | } 31 | 32 | result := addTwoNumbers(l1, l2) 33 | assert.Equal(t, result.Val, 7) 34 | assert.Equal(t, result.Next.Val, 0) 35 | assert.Equal(t, result.Next.Next.Val, 8) 36 | 37 | l1 = &ListNode{ 38 | Val: 0, 39 | Next: nil, 40 | } 41 | 42 | l2 = &ListNode{ 43 | Val: 7, 44 | Next: &ListNode{ 45 | Val: 3, 46 | }, 47 | } 48 | 49 | result = addTwoNumbers(l1, l2) 50 | assert.Equal(t, result.Val, 7) 51 | assert.Equal(t, result.Next.Val, 3) 52 | 53 | } 54 | -------------------------------------------------------------------------------- /0002-add-two-numbers/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/add-two-numbers/description/ 4 | 5 | # desc 6 | 7 | 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 8 | 9 | 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 10 | 11 | 示例: 12 | 13 | ``` 14 | 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 15 | 输出:7 -> 0 -> 8 16 | 原因:342 + 465 = 807 17 | ``` 18 | -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func lengthfLongestSubstring(s string) int { 4 | var charMap = map[byte]bool{} 5 | var maxLen = 0 6 | var currentLen = 0 7 | 8 | for i := 0; i < len(s); i++ { 9 | // 如果 hashmap 中不存在 10 | // 那么说明这个元素可以无条件加入到无重复字母的字符串 11 | if charMap[s[i]] == true { 12 | // hashmap 中存在 13 | // 那要把一直到上一个重复字母(含),之前的全部剔除掉 14 | loopIdx := i - currentLen 15 | for loopIdx < i { 16 | delete(charMap, s[loopIdx]) 17 | currentLen-- 18 | 19 | if s[loopIdx] == s[i] { 20 | break 21 | } 22 | loopIdx++ 23 | } 24 | } 25 | 26 | charMap[s[i]] = true 27 | currentLen++ 28 | if currentLen > maxLen { 29 | maxLen = currentLen 30 | } 31 | } 32 | 33 | return maxLen 34 | } 35 | -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | s string 11 | expectedResult int 12 | } 13 | 14 | func TestLengthfLongestSubstring(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{s: "abcabcbb", expectedResult: 3}, 17 | TestCase{s: "bbbbb", expectedResult: 1}, 18 | TestCase{s: "pwwkew", expectedResult: 3}, 19 | } 20 | 21 | for _, cas := range cases { 22 | result := lengthfLongestSubstring(cas.s) 23 | assert.Equal(t, cas.expectedResult, result, "input: "+cas.s) 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/ 4 | 5 | # desc 6 | 7 | 给定一个字符串,找出不含有重复字符的最长子串的长度。 8 | 9 | 示例: 10 | 11 | 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。 12 | 13 | 给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。 14 | 15 | 给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。 16 | -------------------------------------------------------------------------------- /0005-longest-palindromic-substring/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func longestPalindrome(s string) string { 4 | length := len(s) 5 | var matrix = make([][]bool, length) 6 | for i := 0; i < length; i++ { 7 | matrix[i] = make([]bool, length) 8 | } 9 | 10 | var maxPalindromeLen, maxPalindrome = 0, "" 11 | 12 | // 初始化单字母和双字母是否回文的矩阵 13 | for i := 0; i < length; i++ { 14 | matrix[i][i] = true 15 | if maxPalindromeLen == 0 { 16 | maxPalindromeLen = 1 17 | maxPalindrome = string([]byte{s[i]}) 18 | } 19 | if i > 0 && s[i] == s[i-1] { 20 | matrix[i-1][i] = true 21 | maxPalindromeLen = 2 22 | maxPalindrome = string([]byte{s[i-1], s[i]}) 23 | } 24 | } 25 | 26 | // 在初始结果上,每次只可能增加两个字母 27 | // f(i,j) = f(i+1)(j-1) && s[i] == s[j] 28 | // 初始 i j = 0 29 | // 从矩阵的中轴线向两边扩展 30 | for substrLen := 3; substrLen <= length; substrLen++ { 31 | for i := 0; i < length; i++ { 32 | startIdx := i 33 | endIdx := i + substrLen - 1 34 | if endIdx >= length { 35 | break 36 | } 37 | 38 | if matrix[startIdx+1][endIdx-1] == true { 39 | if s[startIdx] == s[endIdx] { 40 | matrix[startIdx][endIdx] = true 41 | if substrLen > maxPalindromeLen { 42 | maxPalindromeLen = substrLen 43 | maxPalindrome = s[startIdx : endIdx+1] 44 | } 45 | } 46 | } 47 | } 48 | } 49 | 50 | return maxPalindrome 51 | } 52 | -------------------------------------------------------------------------------- /0005-longest-palindromic-substring/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | input string 11 | output string 12 | } 13 | 14 | func TestLongestPalindrome(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{input: "babad", output: "bab"}, 17 | TestCase{input: "cbbd", output: "bb"}, 18 | TestCase{input: "abcba", output: "abcba"}, 19 | TestCase{input: "aaaa", output: "aaaa"}, 20 | } 21 | 22 | for _, cas := range cases { 23 | res := longestPalindrome(cas.input) 24 | assert.Equal(t, cas.output, res, "input: "+cas.input) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /0005-longest-palindromic-substring/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/longest-palindromic-substring/description/ 4 | 5 | # desc 6 | 7 | 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。 8 | 9 | 示例 1: 10 | 11 | ``` 12 | 输入: "babad" 13 | 输出: "bab" 14 | 注意: "aba"也是一个有效答案。 15 | ``` 16 | 17 | 示例 2: 18 | 19 | ``` 20 | 输入: "cbbd" 21 | 输出: "bb" 22 | ``` 23 | -------------------------------------------------------------------------------- /0009-palindrome-number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func isPalindrome(x int) bool { 4 | 5 | if x == 0 { 6 | return true 7 | } 8 | 9 | if x < 0 || x%10 == 0 { 10 | return false 11 | } 12 | 13 | digits := []int{} 14 | y := x 15 | for y > 0 { 16 | digits = append(digits, y%10) 17 | y = y / 10 18 | } 19 | 20 | newSum := 0 21 | for i := 0; i < len(digits); i++ { 22 | newSum = newSum*10 + digits[i] 23 | } 24 | 25 | if newSum == x { 26 | return true 27 | } 28 | 29 | return false 30 | 31 | } 32 | -------------------------------------------------------------------------------- /0009-palindrome-number/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type TestCase struct { 11 | input int 12 | expected bool 13 | } 14 | 15 | func TestIsPalindrome(t *testing.T) { 16 | cases := []TestCase{ 17 | TestCase{input: 0, expected: true}, 18 | TestCase{input: 121, expected: true}, 19 | TestCase{input: -121, expected: false}, 20 | } 21 | 22 | for _, cas := range cases { 23 | res := isPalindrome(cas.input) 24 | assert.Equal(t, cas.expected, res, "input: "+fmt.Sprint(cas.input)) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /0009-palindrome-number/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/palindrome-number/description/ 4 | 5 | # desc 6 | 7 | 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 8 | 9 | 示例 1: 10 | 11 | 输入: 121 12 | 输出: true 13 | 示例 2: 14 | 15 | 输入: -121 16 | 输出: false 17 | 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 18 | 示例 3: 19 | 20 | 输入: 10 21 | 输出: false 22 | 解释: 从右向左读, 为 01 。因此它不是一个回文数。 23 | 进阶: 24 | 25 | 你能不将整数转为字符串来解决这个问题吗? -------------------------------------------------------------------------------- /0018-4sum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func exist(nums []int, numsCollection [][]int) bool { 6 | sort.Ints(nums) 7 | 8 | for _, n := range numsCollection { 9 | sort.Ints(n) 10 | equal := true 11 | for i := 0; i < len(n); i++ { 12 | if nums[i] != n[i] { 13 | equal = false 14 | break 15 | } 16 | } 17 | 18 | if equal { 19 | return true 20 | } 21 | } 22 | return false 23 | } 24 | 25 | func fourSum(nums []int, target int) [][]int { 26 | result := [][]int{} 27 | for i := 0; i < len(nums); i++ { 28 | for j := i + 1; j < len(nums); j++ { 29 | for k := j + 1; k < len(nums); k++ { 30 | for l := k + 1; l < len(nums); l++ { 31 | if nums[i]+nums[j]+nums[k]+nums[l] == target { 32 | current := []int{nums[i], nums[j], nums[k], nums[l]} 33 | if !exist(current, result) { 34 | result = append(result, []int{nums[i], nums[j], nums[k], nums[l]}) 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } 41 | return result 42 | } 43 | -------------------------------------------------------------------------------- /0022-generate-parentheses/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(generateParenthesis(3)) 7 | } 8 | 9 | var res = []string{} 10 | 11 | func goDeeper(curVal int, currentStr string, leftLeft int, rightLeft int) { 12 | if curVal > 0 { 13 | // 放 ( 14 | if leftLeft > 0 { 15 | goDeeper(curVal+1, currentStr+string('('), leftLeft-1, rightLeft) 16 | } 17 | // 放 ) 18 | if rightLeft > 0 { 19 | goDeeper(curVal-1, currentStr+string(')'), leftLeft, rightLeft-1) 20 | } 21 | } 22 | 23 | if curVal == 0 { 24 | if leftLeft == 0 && rightLeft == 0 { 25 | //res++ 26 | res = append(res, currentStr) 27 | return 28 | } 29 | 30 | // 只能放 ( 31 | if leftLeft > 0 { 32 | goDeeper(curVal+1, currentStr+string('('), leftLeft-1, rightLeft) 33 | } 34 | } 35 | 36 | if curVal < 0 { 37 | return 38 | } 39 | } 40 | 41 | func generateParenthesis(n int) []string { 42 | res = res[:0] 43 | goDeeper(0, "", n, n) 44 | return res 45 | } 46 | -------------------------------------------------------------------------------- /0031-next-permutation/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func main() { 6 | } 7 | 8 | func nextPermutation(nums []int) { 9 | found := false 10 | for i := len(nums) - 1; i >= 1; i-- { 11 | if nums[i] > nums[i-1] { 12 | found = true 13 | swapIdx := i 14 | for j := i + 1; j < len(nums); j++ { 15 | if nums[j] > nums[i-1] && nums[j] < nums[i] { 16 | swapIdx = j 17 | } 18 | } 19 | nums[i-1], nums[swapIdx] = nums[swapIdx], nums[i-1] 20 | sort.Ints(nums[i:]) 21 | break 22 | } 23 | } 24 | 25 | if found == false { 26 | for i := 0; i < len(nums)/2; i++ { 27 | nums[i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[i] 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0035-search-insert-position/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func searchInsert(nums []int, target int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | 8 | if target <= nums[0] { 9 | return 0 10 | } 11 | 12 | if target > nums[len(nums)-1] { 13 | return len(nums) 14 | } 15 | 16 | for i := 0; i < len(nums)-1; i++ { 17 | if target > nums[i] && target <= nums[i+1] { 18 | return i + 1 19 | } 20 | } 21 | return 0 22 | } 23 | -------------------------------------------------------------------------------- /0035-search-insert-position/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type TestCase struct { 11 | nums []int 12 | target int 13 | expected int 14 | } 15 | 16 | func TestSearchInsert(t *testing.T) { 17 | cases := []TestCase{ 18 | TestCase{nums: []int{1, 3, 5, 6}, target: 5, expected: 2}, 19 | TestCase{nums: []int{1, 3, 5, 6}, target: 2, expected: 1}, 20 | TestCase{nums: []int{1, 3, 5, 6}, target: 7, expected: 4}, 21 | TestCase{nums: []int{1, 3, 5, 6}, target: 0, expected: 0}, 22 | } 23 | 24 | for _, cas := range cases { 25 | assert.Equal(t, cas.expected, searchInsert(cas.nums, cas.target), "input"+fmt.Sprint(cas.nums)+"target"+fmt.Sprint(cas.target)) 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /0038-count-and-say/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var res = []string{"1", "1"} //"11", "21", "1211", "111221"} 6 | 7 | func countInt(n int) string { 8 | countStr := "" 9 | nStr := res[n-1] 10 | for i := 0; i < len(nStr); i++ { 11 | cnt := 1 12 | currentChar := nStr[i] 13 | for i+1 < len(nStr) && nStr[i+1] == nStr[i] { 14 | cnt++ 15 | i++ 16 | } 17 | countStr = countStr + fmt.Sprint(cnt) + string([]byte{currentChar}) 18 | } 19 | 20 | return countStr 21 | } 22 | 23 | func countAndSay(n int) string { 24 | if n < len(res) { 25 | return res[n] 26 | } 27 | 28 | // init result 29 | for i := len(res); i <= n; i++ { 30 | res = append(res, countInt(i)) 31 | } 32 | 33 | return res[n] 34 | } 35 | -------------------------------------------------------------------------------- /0038-count-and-say/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | n int 11 | expected string 12 | } 13 | 14 | func TestCountAndSay(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{n: 1, expected: "1"}, 17 | TestCase{n: 4, expected: "1211"}, 18 | TestCase{n: 5, expected: "111221"}, 19 | } 20 | 21 | for _, cas := range cases { 22 | res := countAndSay(cas.n) 23 | assert.Equal(t, cas.expected, res) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0039-combination-sum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func combinationSum(candidates []int, target int) [][]int { 4 | fmt.Println(candidates, target) 5 | if target == 0 { 6 | return [][]int{[]int{}} 7 | } 8 | 9 | if len(candidates) == 0 { 10 | // 无解 11 | return nil 12 | } 13 | 14 | if len(candidates) == 1 { 15 | if target%candidates[0] == 0 { 16 | result := []int{} 17 | for i := 0; i < (target / candidates[0]); i++ { 18 | result = append(result, candidates[0]) 19 | } 20 | return [][]int{result} 21 | } 22 | 23 | // 无解 24 | return nil 25 | } 26 | 27 | result := [][]int{} 28 | for i := 0; i <= target/candidates[0]; i++ { 29 | subResult := combinationSum(candidates[1:], target-i*candidates[0]) 30 | if subResult != nil { 31 | // [][]int{} 32 | // 里的每个数组都追加上当前的 candidate 0 即可 33 | for j := 0; j < len(subResult); j++ { 34 | for k := 0; k < i; k++ { 35 | subResult[j] = append(subResult[j], candidates[0]) 36 | } 37 | result = append(result, subResult[j]) 38 | } 39 | } 40 | } 41 | return result 42 | } 43 | 44 | -------------------------------------------------------------------------------- /0041-first-missing-positive/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func firstMissingPositive(nums []int) int { 4 | if len(nums) == 0 { 5 | return 1 6 | } 7 | 8 | var arr = make([]bool, len(nums)+1) 9 | var idx = 1 10 | for i := 0; i < len(nums); i++ { 11 | if nums[i] >= 0 && nums[i] < len(arr) { 12 | arr[nums[i]] = true 13 | } 14 | } 15 | 16 | for i := 1; i < len(arr); i++ { 17 | if arr[i] == false { 18 | idx = i 19 | break 20 | } else { 21 | idx = i + 1 22 | } 23 | } 24 | 25 | return idx 26 | } 27 | -------------------------------------------------------------------------------- /0041-first-missing-positive/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | nums []int 11 | expected int 12 | } 13 | 14 | func TestFirstMissingPositive(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{nums: []int{}, expected: 1}, 17 | TestCase{nums: []int{1}, expected: 2}, 18 | TestCase{nums: []int{1, 2, 0}, expected: 3}, 19 | TestCase{nums: []int{3, 4, -1, 1}, expected: 2}, 20 | TestCase{nums: []int{7, 8, 9, 11, 12}, expected: 1}, 21 | } 22 | 23 | for _, cas := range cases { 24 | res := firstMissingPositive(cas.nums) 25 | assert.Equal(t, cas.expected, res) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /0041-first-missing-positive/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/first-missing-positive/description/ 4 | 5 | # desc 6 | 7 | 给定一个未排序的整数数组,找出其中没有出现的最小的正整数。 8 | 9 | 示例 1: 10 | 11 | ``` 12 | 输入: [1,2,0] 13 | 输出: 3 14 | ``` 15 | 16 | 示例 2: 17 | 18 | ``` 19 | 输入: [3,4,-1,1] 20 | 输出: 2 21 | ``` 22 | 23 | 示例 3: 24 | 25 | ``` 26 | 输入: [7,8,9,11,12] 27 | 输出: 1 28 | ``` 29 | 30 | 说明: 31 | 32 | 你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。 -------------------------------------------------------------------------------- /0042-trapping-rain-water/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func copyAndSum(height []int) ([]int, int) { 4 | dstArr := make([]int, len(height)) 5 | sum := 0 6 | for i := 0; i < len(height); i++ { 7 | dstArr[i] = height[i] 8 | sum += height[i] 9 | } 10 | return dstArr, sum 11 | } 12 | 13 | func sum(height []int) int { 14 | res := 0 15 | for i := 0; i < len(height); i++ { 16 | res += height[i] 17 | } 18 | return res 19 | } 20 | 21 | func min(x, y int) int { 22 | if x < y { 23 | return x 24 | } 25 | return y 26 | } 27 | 28 | func trap(height []int) int { 29 | dstArr, originalSum := copyAndSum(height) 30 | 31 | for i := 0; i < len(height); i++ { 32 | // println(i) 33 | if height[i] != 0 { 34 | // find the first that >= height[i] 35 | // if there is not such one 36 | // return the right max 37 | rightMax, idx, found := 0, 0, false 38 | for j := i + 1; j < len(height); j++ { 39 | if height[j] > rightMax { 40 | rightMax = height[j] 41 | idx = j 42 | found = true 43 | } 44 | if height[j] >= height[i] { 45 | rightMax = height[j] 46 | idx = j 47 | found = true 48 | break 49 | } 50 | } 51 | 52 | if !found { 53 | continue 54 | } 55 | // println(rightMax, height[i]) 56 | minimum := min(rightMax, height[i]) 57 | for k := i + 1; k < idx; k++ { 58 | dstArr[k] = minimum 59 | } 60 | i = idx - 1 61 | } 62 | } 63 | // fmt.Println(dstArr) 64 | 65 | newSum := sum(dstArr) 66 | return newSum - originalSum 67 | } 68 | -------------------------------------------------------------------------------- /0042-trapping-rain-water/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | height []int 11 | expected int 12 | } 13 | 14 | func TestTrap(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{height: []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}, expected: 6}, 17 | } 18 | 19 | for _, cas := range cases { 20 | res := trap(cas.height) 21 | assert.Equal(t, cas.expected, res) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /0042-trapping-rain-water/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/trapping-rain-water/description/ 4 | 5 | # desc 6 | 7 | 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 8 | 9 | ![](https://leetcode-cn.com/static/images/problemset/rainwatertrap.png) 10 | 11 | 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。 12 | 13 | 示例: 14 | 15 | ``` 16 | 输入: [0,1,0,2,1,0,1,3,2,1,2,1] 17 | 输出: 6 18 | ``` 19 | -------------------------------------------------------------------------------- /0045-jump-game-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(jump([]int{2, 3, 1, 1, 4})) 7 | } 8 | 9 | func jump(nums []int) int { 10 | minSteps := make([]int, len(nums)) 11 | for i := 1; i < len(minSteps); i++ { 12 | minSteps[i] = len(nums) + 100 13 | } 14 | 15 | for i := 0; i < len(nums); i++ { 16 | for j := i + 1; j <= i+nums[i] && j < len(nums); j++ { 17 | if minSteps[i]+1 < minSteps[j] { 18 | minSteps[j] = minSteps[i] + 1 19 | } 20 | } 21 | } 22 | fmt.Println(minSteps) 23 | return minSteps[len(nums)-1] 24 | } 25 | -------------------------------------------------------------------------------- /0046-permutations/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func pickOutIthElem(arr []int, i int) []int { 4 | if len(arr) == 0 { 5 | return arr 6 | } 7 | 8 | // copy arr to another slice 9 | res := make([]int, 0, len(arr)-1) 10 | for j := 0; j < len(arr); j++ { 11 | if j == i { 12 | continue 13 | } 14 | res = append(res, arr[j]) 15 | } 16 | 17 | return res 18 | } 19 | 20 | func appendToEveryArr(arr [][]int, elem int) [][]int { 21 | var res [][]int 22 | for i := 0; i < len(arr); i++ { 23 | arr[i] = append(arr[i], elem) 24 | res = append(res, arr[i]) 25 | } 26 | return res 27 | } 28 | 29 | func getPermutation(arr []int) [][]int { 30 | 31 | // 递归终止 32 | if len(arr) == 1 || len(arr) == 0 { 33 | return [][]int{arr} 34 | } 35 | 36 | var result = [][]int{} 37 | 38 | for i := 0; i < len(arr); i++ { 39 | // 去除 arr[i] 40 | arrWithOutIthElem := pickOutIthElem(arr, i) 41 | 42 | midResult := getPermutation(arrWithOutIthElem) 43 | 44 | // 给每一个子数组,都 append 上当前挑出的元素 45 | result = append(result, appendToEveryArr(midResult, arr[i])...) 46 | } 47 | return result 48 | } 49 | 50 | func permute(nums []int) [][]int { 51 | return getPermutation(nums) 52 | } 53 | -------------------------------------------------------------------------------- /0047-permutations-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func permuteUnique(nums []int) [][]int { 6 | sort.Ints(nums) 7 | copyNum := append([]int{}, nums...) 8 | 9 | res := [][]int{} 10 | res = append(res, copyNum) 11 | for { 12 | canBeBigger := false 13 | for i := len(nums) - 1; i >= 1; i-- { 14 | if nums[i] > nums[i-1] { 15 | canBeBigger = true 16 | // 从 i 向后找最小的 > nums[i-1] 的数 17 | // 排序 nums[i:] 18 | for j := i; j < len(nums); j++ { 19 | if nums[j] < nums[i] && nums[j] > nums[i-1] { 20 | nums[j], nums[i] = nums[i], nums[j] 21 | } 22 | } 23 | nums[i], nums[i-1] = nums[i-1], nums[i] 24 | sort.Ints(nums[i:]) 25 | internalRes := append([]int{}, nums...) 26 | res = append(res, internalRes) 27 | break 28 | } 29 | } 30 | if !canBeBigger { 31 | break 32 | } 33 | } 34 | return res 35 | } 36 | 37 | func main() {} 38 | -------------------------------------------------------------------------------- /0051-n-queens/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(solveNQueens(4)) 7 | } 8 | 9 | func abs(a int) int { 10 | if a < 0 { 11 | return -a 12 | } 13 | return a 14 | } 15 | 16 | func getResult(stack []int) []string { 17 | result := []string{} 18 | n := len(stack) 19 | for i := 0; i < len(stack); i++ { 20 | line := make([]byte, n) 21 | for j := 0; j < len(line); j++ { 22 | line[j] = '.' 23 | } 24 | line[stack[i]] = 'Q' 25 | result = append(result, string(line)) 26 | } 27 | 28 | return result 29 | } 30 | 31 | func traverse(parentStack []int, currentLevel int, maxLevel int, res *[][]string) { 32 | //fmt.Println(parentStack, currentLevel, maxLevel) 33 | if currentLevel == maxLevel { 34 | currentMatrix := getResult(parentStack) 35 | *res = append(*res, currentMatrix) 36 | return 37 | } 38 | 39 | for i := 0; i < maxLevel; i++ { 40 | valid := true 41 | for j := 0; j < len(parentStack); j++ { 42 | r1, c1 := j, parentStack[j] 43 | r2, c2 := currentLevel, i 44 | if c1 == c2 || abs(r1-r2) == abs(c1-c2) { 45 | // valid 46 | valid = false 47 | } 48 | } 49 | if valid { 50 | currentStack := append([]int{}, parentStack...) 51 | currentStack = append(currentStack, i) 52 | traverse(currentStack, currentLevel+1, maxLevel, res) 53 | } 54 | } 55 | } 56 | 57 | func solveNQueens(n int) [][]string { 58 | res := [][]string{} 59 | traverse([]int{}, 0, n, &res) 60 | return res 61 | } 62 | -------------------------------------------------------------------------------- /0052-n-queens-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(4, totalNQueens(4)) 7 | fmt.Println(8, totalNQueens(8)) 8 | } 9 | 10 | func abs(a int) int { 11 | if a < 0 { 12 | return -a 13 | } 14 | return a 15 | } 16 | 17 | func traverse(parentStack []int, level int, n int, res *int) { 18 | //fmt.Println("level", level, "n", n, parentStack) 19 | if level == n { 20 | //fmt.Println(parentStack) 21 | *res++ 22 | } 23 | 24 | for i := 0; i < n; i++ { 25 | valid := true 26 | for j := 0; j < len(parentStack); j++ { 27 | if parentStack[j] == i || abs(parentStack[j]-i) == abs(j-level) { 28 | valid = false 29 | break 30 | } 31 | } 32 | 33 | if valid { 34 | currentStack := append([]int{}, parentStack...) 35 | currentStack = append(currentStack, i) 36 | traverse(currentStack, level+1, n, res) 37 | } 38 | } 39 | } 40 | 41 | func totalNQueens(n int) int { 42 | var res int 43 | traverse([]int{}, 0, n, &res) 44 | return res 45 | } 46 | -------------------------------------------------------------------------------- /0053-maximum-subarray/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxSubArray(nums []int) int { 4 | sumMax := make([]int, len(nums)) 5 | sumMaxResult := nums[0] 6 | for i := 0; i < len(nums); i++ { 7 | if i == 0 { 8 | sumMax[i] = nums[i] 9 | if sumMax[i] > sumMaxResult { 10 | sumMaxResult = sumMax[i] 11 | } 12 | } else { 13 | if sumMax[i-1] > 0 { 14 | sumMax[i] = sumMax[i-1] + nums[i] 15 | } else { 16 | sumMax[i] = nums[i] 17 | } 18 | } 19 | 20 | if sumMax[i] > sumMaxResult { 21 | sumMaxResult = sumMax[i] 22 | } 23 | } 24 | return sumMaxResult 25 | } 26 | -------------------------------------------------------------------------------- /0053-maximum-subarray/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | nums []int 11 | expected int 12 | } 13 | 14 | func TestMaxSubArray(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{ 17 | nums: []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}, 18 | expected: 6, 19 | }, 20 | TestCase{ 21 | nums: []int{1, 2, 3, 4, 5}, 22 | expected: 15, 23 | }, 24 | TestCase{ 25 | nums: []int{-1}, 26 | expected: -1, 27 | }, 28 | } 29 | 30 | for _, cas := range cases { 31 | res := maxSubArray(cas.nums) 32 | assert.Equal(t, cas.expected, res) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /0053-maximum-subarray/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/maximum-subarray/description/ 4 | 5 | # desc 6 | 7 | 8 | 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 9 | 10 | 示例: 11 | 12 | ``` 13 | 输入: [-2,1,-3,4,-1,2,1,-5,4], 14 | 输出: 6 15 | 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 16 | ``` 17 | 18 | 进阶: 19 | 20 | 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 -------------------------------------------------------------------------------- /0055-jump-game/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(canJump([]int{3, 2, 1, 0, 4})) 7 | fmt.Println(canJump([]int{0})) 8 | } 9 | 10 | func canJump(nums []int) bool { 11 | 12 | var can = make([]bool, len(nums)) 13 | can[0] = true 14 | 15 | for i := 0; i < len(nums); i++ { 16 | if can[i] != true { 17 | continue 18 | } 19 | 20 | for j := i + 1; j <= i+nums[i] && j < len(nums); j++ { 21 | can[j] = true 22 | } 23 | } 24 | 25 | fmt.Println(can) 26 | 27 | return can[len(nums)-1] 28 | } 29 | -------------------------------------------------------------------------------- /0058-length-of-last-word/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func lengthOfLastWord(s string) int { 4 | var res = []byte{} 5 | for i := len(s) - 1; i >= 0; i-- { 6 | if (s[i] >= 'A' && s[i] <= 'Z') || 7 | (s[i] >= 'a' && s[i] <= 'z') { 8 | res = append(res, s[i]) 9 | } else { 10 | if len(res) > 0 { 11 | break 12 | } 13 | } 14 | } 15 | 16 | return len(res) 17 | } 18 | -------------------------------------------------------------------------------- /0064-minimum-path-sum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(minPathSum([][]int{[]int{1, 3, 1}, []int{1, 5, 1}, []int{4, 2, 1}})) 7 | } 8 | 9 | type point struct { 10 | x int 11 | y int 12 | } 13 | 14 | func dfs(res [][]int, grid [][]int, next []point) { 15 | if len(next) == 0 { 16 | return 17 | } 18 | 19 | // 计算现在的 20 | if len(next) >= 1 { 21 | for i := 0; i < len(next); i++ { 22 | // left 23 | x, y := next[i].x, next[i].y-1 24 | if y >= 0 && res[x][y]+grid[x][y+1] < res[x][y+1] { 25 | res[x][y+1] = res[x][y] + grid[x][y+1] 26 | } 27 | // up 28 | x, y = next[i].x-1, next[i].y 29 | if x >= 0 && res[x][y]+grid[x+1][y] < res[x+1][y] { 30 | res[x+1][y] = res[x][y] + grid[x+1][y] 31 | } 32 | } 33 | } 34 | 35 | newNext := []point{} 36 | distinctMap := map[point]bool{} 37 | for i := 0; i < len(next); i++ { 38 | // right 39 | x, y := next[i].x, next[i].y+1 40 | _, ok := distinctMap[point{x, y}] 41 | if y < len(grid[0]) && !ok { 42 | newNext = append(newNext, point{x, y}) 43 | distinctMap[point{x, y}] = true 44 | } 45 | // down 46 | x, y = next[i].x+1, next[i].y 47 | _, ok = distinctMap[point{x, y}] 48 | if x < len(grid) && !ok { 49 | newNext = append(newNext, point{x, y}) 50 | distinctMap[point{x, y}] = true 51 | } 52 | } 53 | dfs(res, grid, newNext) 54 | } 55 | 56 | func minPathSum(grid [][]int) int { 57 | if len(grid) == 0 { 58 | return 0 59 | } 60 | 61 | res := make([][]int, len(grid)) 62 | for i := 0; i < len(grid); i++ { 63 | res[i] = make([]int, len(grid[0])) 64 | for j := 0; j < len(res[i]); j++ { 65 | res[i][j] = 99999999999999999 66 | } 67 | } 68 | res[0][0] = grid[0][0] 69 | dfs(res, grid, []point{point{0, 0}}) 70 | return res[len(grid)-1][len(grid[0])-1] 71 | } 72 | -------------------------------------------------------------------------------- /0066-plus-one/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func plusOne(digits []int) []int { 4 | l := len(digits) 5 | pos := l - 1 6 | for pos >= 0 { 7 | digits[pos]++ 8 | if digits[pos] <= 9 { 9 | return digits 10 | } 11 | 12 | digits[pos] = 0 13 | pos-- 14 | } 15 | 16 | return append([]int{1}, digits...) 17 | } 18 | -------------------------------------------------------------------------------- /0073-set-matrix-zeroes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func rowResultWillBeZero(matrix [][]int, row int) bool { 6 | r := matrix[row] 7 | for i := 0; i < len(r); i++ { 8 | if r[i] == 0 { 9 | return true 10 | } 11 | } 12 | return false 13 | } 14 | 15 | func colResultWillBeZero(matrix [][]int, col int) bool { 16 | for i := 0; i < len(matrix); i++ { 17 | if matrix[i][col] == 0 { 18 | return true 19 | } 20 | } 21 | return false 22 | } 23 | 24 | func setZeroes(matrix [][]int) { 25 | if len(matrix) == 0 { 26 | return 27 | } 28 | 29 | markRow, markCol := 0, -1 30 | colCnt := len(matrix[0]) 31 | firstRow := matrix[0] 32 | 33 | for i := 0; i < colCnt; i++ { 34 | if firstRow[i] != 0 { 35 | markCol = i 36 | break 37 | } 38 | } 39 | 40 | if markCol == -1 { 41 | // mark all to zero 42 | for i := 0; i < len(matrix); i++ { 43 | for j := 0; j < len(matrix[0]); j++ { 44 | matrix[i][j] = 0 45 | } 46 | } 47 | return 48 | } 49 | markRowIsZero := rowResultWillBeZero(matrix, markRow) 50 | markColIsZero := colResultWillBeZero(matrix, markCol) 51 | 52 | // traverse 53 | 54 | for i := 1; i < len(matrix); i++ { 55 | for j := 0; j < len(matrix[0]); j++ { 56 | if j == markCol { 57 | continue 58 | } 59 | if matrix[i][j] == 0 { 60 | // set mark pos = 0 61 | matrix[markRow][j] = 0 62 | matrix[i][markCol] = 0 63 | } 64 | } 65 | } 66 | 67 | for i := 1; i < len(matrix); i++ { 68 | for j := 0; j < len(matrix[0]); j++ { 69 | if j == markCol { 70 | continue 71 | } 72 | if matrix[markRow][j] == 0 || matrix[i][markCol] == 0 { 73 | matrix[i][j] = 0 74 | } 75 | } 76 | } 77 | 78 | // mark markrow and markcol 79 | if markRowIsZero { 80 | for i := 0; i < len(matrix[0]); i++ { 81 | matrix[0][i] = 0 82 | } 83 | } 84 | 85 | if markColIsZero { 86 | for i := 0; i < len(matrix); i++ { 87 | matrix[i][markCol] = 0 88 | } 89 | } 90 | 91 | } 92 | 93 | func main() { 94 | var m = [][]int{[]int{0}} 95 | setZeroes(m) 96 | fmt.Println(m) 97 | m = [][]int{[]int{0, 1, 2, 0}, []int{3, 4, 5, 2}, []int{1, 3, 1, 5}} 98 | setZeroes(m) 99 | fmt.Println(m) 100 | m = [][]int{[]int{0}, []int{1}} 101 | setZeroes(m) 102 | fmt.Println(m) 103 | } 104 | -------------------------------------------------------------------------------- /0077-combinations/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func main() {} 8 | func getResult(pickArr []int) []int { 9 | currentCombi := []int{} 10 | for j := 0; j < len(pickArr); j++ { 11 | if pickArr[j] == 1 { 12 | currentCombi = append(currentCombi, j+1) 13 | } 14 | } 15 | return currentCombi 16 | } 17 | 18 | func combine(n int, k int) [][]int { 19 | pickArr := make([]int, n) 20 | for i := 0; i < k; i++ { 21 | pickArr[i] = 1 22 | } 23 | 24 | res := append([][]int{}, getResult(pickArr)) 25 | 26 | for { 27 | // find the first 10 28 | // swap 10 -> 01 29 | // move all 1 left of 01 to the left 30 | found := false 31 | for i := 0; i < len(pickArr)-1; i++ { 32 | if pickArr[i] == 1 && pickArr[i+1] == 0 { 33 | found = true 34 | pickArr[i], pickArr[i+1] = 0, 1 35 | onePos := 0 36 | for j := 0; j < i; j++ { 37 | if pickArr[j] == 1 { 38 | pickArr[j], pickArr[onePos] = pickArr[onePos], pickArr[j] 39 | onePos++ 40 | } 41 | } 42 | sort.Slice(pickArr[:i], func(x, y int) bool { 43 | return pickArr[x] > pickArr[y] 44 | }) 45 | break 46 | } 47 | } 48 | 49 | if !found { 50 | break 51 | } 52 | // found 53 | res = append(res, getResult(pickArr)) 54 | } 55 | return res 56 | } 57 | -------------------------------------------------------------------------------- /0078-subsets/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(subsets([]int{1, 2, 3})) 7 | } 8 | 9 | func dfs(parentNums []int, nums []int, res *[][]int) { 10 | for i := 0; i < len(nums); i++ { 11 | current := make([]int, len(parentNums)+1) 12 | copy(current, parentNums) 13 | current[len(current)-1] = nums[i] 14 | *res = append(*res, current) 15 | if i < len(nums) { 16 | dfs(current, nums[i+1:], res) 17 | } 18 | } 19 | } 20 | 21 | func subsets(nums []int) [][]int { 22 | res := [][]int{[]int{}} 23 | dfs([]int{}, nums, &res) 24 | return res 25 | } 26 | -------------------------------------------------------------------------------- /0082-remove-duplicates-from-sorted-list-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | } 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * type ListNode struct { 9 | * Val int 10 | * Next *ListNode 11 | * } 12 | */ 13 | 14 | // ListNode ... 15 | type ListNode struct { 16 | Val int 17 | Next *ListNode 18 | } 19 | 20 | func deleteDuplicates(head *ListNode) *ListNode { 21 | if head == nil { 22 | return head 23 | } 24 | var valMap = map[int]int{} 25 | cur := head 26 | for cur != nil { 27 | valMap[cur.Val]++ 28 | cur = cur.Next 29 | } 30 | 31 | cur = head 32 | // change head 33 | for cur != nil && valMap[cur.Val] > 1 { 34 | cur = cur.Next 35 | } 36 | 37 | head = cur 38 | if head == nil { 39 | return head 40 | } 41 | 42 | cur = head.Next 43 | lastValid := head 44 | for cur != nil { 45 | if valMap[cur.Val] > 1 { 46 | lastValid.Next = cur.Next 47 | cur = cur.Next 48 | continue 49 | } 50 | 51 | lastValid = cur 52 | cur = cur.Next 53 | } 54 | 55 | return head 56 | } 57 | -------------------------------------------------------------------------------- /0083-remove-duplicates-from-sorted-list/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | // ListNode ... 8 | type ListNode struct { 9 | Val int 10 | Next *ListNode 11 | } 12 | 13 | /* 14 | * Definition for singly-linked list. 15 | * type ListNode struct { 16 | * Val int 17 | * Next *ListNode 18 | * } 19 | */ 20 | func deleteDuplicates(head *ListNode) *ListNode { 21 | if head == nil { 22 | return head 23 | } 24 | cur := head 25 | for cur.Next != nil { 26 | if cur.Next.Val == cur.Val { 27 | cur.Next = cur.Next.Next 28 | } else { 29 | cur = cur.Next 30 | } 31 | } 32 | return head 33 | } 34 | -------------------------------------------------------------------------------- /0090-subsets-ii/eq.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println([]int{1, 2} == []int{1, 2}) 7 | } 8 | -------------------------------------------------------------------------------- /0090-subsets-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(subsetsWithDup([]int{1, 2, 2})) 10 | } 11 | 12 | func dfs(parentNums []int, nums []int, res *[][]int) { 13 | for i := 0; i < len(nums); i++ { 14 | current := make([]int, len(parentNums)+1) 15 | copy(current, parentNums) 16 | current[len(current)-1] = nums[i] 17 | *res = append(*res, current) 18 | if i < len(nums) { 19 | dfs(current, nums[i+1:], res) 20 | } 21 | } 22 | } 23 | 24 | func equal(a, b []int) bool { 25 | if len(a) != len(b) { 26 | return false 27 | } 28 | for i := 0; i < len(a); i++ { 29 | if a[i] != b[i] { 30 | return false 31 | } 32 | } 33 | return true 34 | } 35 | 36 | func subsetsWithDup(nums []int) [][]int { 37 | sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] }) 38 | if len(nums) == 0 { 39 | return [][]int{} 40 | } 41 | res := [][]int{[]int{}} 42 | dfs([]int{}, nums, &res) 43 | sort.Slice(res, func(x, y int) bool { 44 | if len(res[x]) < len(res[y]) { 45 | return true 46 | } 47 | if len(res[x]) > len(res[y]) { 48 | return false 49 | } 50 | for i := 0; i < len(res[x]); i++ { 51 | if res[x][i] < res[y][i] { 52 | return true 53 | } 54 | if res[x][i] > res[y][i] { 55 | return false 56 | } 57 | } 58 | return false 59 | }) 60 | 61 | finalRes := [][]int{res[0]} 62 | 63 | for i := 1; i < len(res); i++ { 64 | if equal(res[i], res[i-1]) { 65 | // skip 66 | continue 67 | } 68 | finalRes = append(finalRes, res[i]) 69 | } 70 | return finalRes 71 | } 72 | -------------------------------------------------------------------------------- /0098-validate-binary-search-tree/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // TreeNode ... 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func isValidBSTWithBounds(root *TreeNode, lowerBound int, upperBound int) bool { 19 | if root == nil { 20 | return true 21 | } 22 | 23 | if (lowerBound != -1 && root.Val <= lowerBound) || (upperBound != -1 && root.Val >= upperBound) { 24 | return false 25 | } 26 | 27 | leftUpperBound := root.Val 28 | if upperBound != -1 && upperBound <= leftUpperBound { 29 | leftUpperBound = upperBound 30 | } 31 | 32 | rightLowerBound := root.Val 33 | if lowerBound != -1 && lowerBound >= rightLowerBound { 34 | rightLowerBound = lowerBound 35 | } 36 | 37 | return isValidBSTWithBounds(root.Left, lowerBound, leftUpperBound) && 38 | isValidBSTWithBounds(root.Right, rightLowerBound, upperBound) 39 | 40 | } 41 | 42 | func isValidBST(root *TreeNode) bool { 43 | if root == nil { 44 | return true 45 | } 46 | 47 | // left 48 | leftUpperBound := root.Val 49 | if root.Left != nil { 50 | if !isValidBSTWithBounds(root.Left, -1, leftUpperBound) { 51 | return false 52 | } 53 | } 54 | 55 | // right 56 | rightLowerBound := root.Val 57 | if root.Right != nil { 58 | if !isValidBSTWithBounds(root.Right, rightLowerBound, -1) { 59 | return false 60 | } 61 | } 62 | 63 | return true 64 | } 65 | -------------------------------------------------------------------------------- /0098-validate-binary-search-tree/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | input *TreeNode 11 | expected bool 12 | } 13 | 14 | func TestIsValidBST(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{ 17 | input: &TreeNode{ 18 | Val: 2, 19 | Left: &TreeNode{Val: 1}, 20 | Right: &TreeNode{Val: 3}, 21 | }, 22 | expected: true, 23 | }, 24 | TestCase{ 25 | input: &TreeNode{ 26 | Val: 5, 27 | Left: &TreeNode{Val: 1}, 28 | Right: &TreeNode{Val: 4, 29 | Left: &TreeNode{Val: 3}, 30 | Right: &TreeNode{Val: 6}, 31 | }, 32 | }, 33 | }, 34 | } 35 | 36 | for _, cas := range cases { 37 | res := isValidBST(cas.input) 38 | assert.Equal(t, cas.expected, res) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /0098-validate-binary-search-tree/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/validate-binary-search-tree/description/ 4 | 5 | # desc 6 | 7 | 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 8 | 9 | 一个二叉搜索树具有如下特征: 10 | 11 | 节点的左子树只包含小于当前节点的数。 12 | 节点的右子树只包含大于当前节点的数。 13 | 所有左子树和右子树自身必须也是二叉搜索树。 14 | 示例 1: 15 | 16 | ``` 17 | 输入: 18 | 2 19 | / \ 20 | 1 3 21 | 输出: true 22 | ``` 23 | 24 | 示例 2: 25 | 26 | ``` 27 | 输入: 28 | 5 29 | / \ 30 | 1 4 31 | / \ 32 | 3 6 33 | 输出: false 34 | 解释: 输入为: [5,1,4,null,null,3,6]。 35 | 根节点的值为 5 ,但是其右子节点值为 4 。 36 | ``` 37 | -------------------------------------------------------------------------------- /0101-symmetric-tree/main.go: -------------------------------------------------------------------------------- 1 | package main 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 ... 13 | type TreeNode struct { 14 | Val int 15 | Left *TreeNode 16 | Right *TreeNode 17 | } 18 | 19 | func reverseTree(root *TreeNode) { 20 | if root == nil { 21 | return 22 | } 23 | 24 | if root.Left != nil || root.Right != nil { 25 | root.Left, root.Right = root.Right, root.Left 26 | } 27 | 28 | reverseTree(root.Left) 29 | reverseTree(root.Right) 30 | } 31 | 32 | func traverseAndCompare(node1 *TreeNode, node2 *TreeNode) bool { 33 | if node1 == nil && node2 == nil { 34 | return true 35 | } 36 | 37 | if node1 == nil && node2 != nil { 38 | return false 39 | } 40 | 41 | if node1 != nil && node2 == nil { 42 | return false 43 | } 44 | 45 | if node1.Val != node2.Val { 46 | return false 47 | } 48 | 49 | return traverseAndCompare(node1.Left, node2.Left) && 50 | traverseAndCompare(node1.Right, node2.Right) 51 | 52 | } 53 | 54 | func isSymmetric(root *TreeNode) bool { 55 | if root == nil { 56 | return true 57 | } 58 | reverseTree(root.Right) 59 | return traverseAndCompare(root.Left, root.Right) 60 | } 61 | -------------------------------------------------------------------------------- /0102-binary-tree-level-order-traversal/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 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 | type node struct { 18 | Val int 19 | level int 20 | } 21 | 22 | func tranv(input []*TreeNode) []*TreeNode { 23 | res := []*TreeNode{} 24 | for i := 0; i < len(input); i++ { 25 | if input[i].Left != nil { 26 | res = append(res, input[i].Left) 27 | } 28 | if input[i].Right != nil { 29 | res = append(res, input[i].Right) 30 | } 31 | } 32 | return res 33 | } 34 | 35 | func levelOrder(root *TreeNode) [][]int { 36 | var res = [][]int{} 37 | if root == nil { 38 | return res 39 | } 40 | 41 | level := 0 42 | currentLevelNodeList := []*TreeNode{root} 43 | for len(currentLevelNodeList) > 0 { 44 | // append to result 45 | currentLevelValList := []int{} 46 | for _, n := range currentLevelNodeList { 47 | currentLevelValList = append(currentLevelValList, n.Val) 48 | } 49 | res = append(res, currentLevelValList) 50 | 51 | // next level 52 | currentLevelNodeList = tranv(currentLevelNodeList) 53 | level++ 54 | } 55 | return res 56 | } 57 | -------------------------------------------------------------------------------- /0102-binary-tree-level-order-traversal/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | root *TreeNode 11 | expected [][]int 12 | } 13 | 14 | func TestLevelOrder(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{ 17 | root: &TreeNode{ 18 | Val: 3, 19 | Left: &TreeNode{Val: 9}, 20 | Right: &TreeNode{ 21 | Val: 20, 22 | Left: &TreeNode{Val: 15}, 23 | Right: &TreeNode{Val: 7}, 24 | }, 25 | }, 26 | expected: [][]int{ 27 | []int{3}, []int{9, 20}, []int{15, 7}, 28 | }, 29 | }, 30 | TestCase{ 31 | root: nil, 32 | expected: [][]int{}, 33 | }, 34 | } 35 | 36 | for _, cas := range cases { 37 | res := levelOrder(cas.root) 38 | assert.Equal(t, cas.expected, res) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /0102-binary-tree-level-order-traversal/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/binary-tree-level-order-traversal/description/ 4 | 5 | # desc 6 | 7 | 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 8 | 9 | 例如: 10 | 给定二叉树: [3,9,20,null,null,15,7], 11 | 12 | ``` 13 | 14 | 3 15 | / \ 16 | 9 20 17 | / \ 18 | 15 7 19 | ``` 20 | 21 | 返回其层次遍历结果: 22 | 23 | ``` 24 | [ 25 | [3], 26 | [9,20], 27 | [15,7] 28 | ] 29 | ``` 30 | -------------------------------------------------------------------------------- /0103-binary-tree-zigzag-level-order-traversal/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type TreeNode struct { 6 | Val int 7 | Left *TreeNode 8 | Right *TreeNode 9 | } 10 | 11 | /** 12 | * Definition for a binary tree node. 13 | * type TreeNode struct { 14 | * Val int 15 | * Left *TreeNode 16 | * Right *TreeNode 17 | * } 18 | */ 19 | func zigzagLevelOrder(root *TreeNode) [][]int { 20 | if root == nil { 21 | return [][]int{} 22 | } 23 | 24 | res := [][]int{} 25 | 26 | currentLevelNodes := []*TreeNode{root} 27 | for len(currentLevelNodes) > 0 { 28 | traverseResult := []int{} 29 | var nextLevelNodes = []*TreeNode{} 30 | for i := 0; i < len(currentLevelNodes); i++ { 31 | traverseResult = append(traverseResult, currentLevelNodes[i].Val) 32 | if currentLevelNodes[i].Left != nil { 33 | nextLevelNodes = append(nextLevelNodes, currentLevelNodes[i].Left) 34 | } 35 | if currentLevelNodes[i].Right != nil { 36 | nextLevelNodes = append(nextLevelNodes, currentLevelNodes[i].Right) 37 | 38 | } 39 | } 40 | res = append(res, traverseResult) 41 | currentLevelNodes = nextLevelNodes 42 | } 43 | for i := 0; i < len(res); i++ { 44 | if i%2 == 0 { 45 | continue 46 | } 47 | 48 | for j := 0; j < len(res[i])/2; j++ { 49 | res[i][j], res[i][len(res[i])-1-j] = res[i][len(res[i])-1-j], res[i][j] 50 | } 51 | } 52 | return res 53 | } 54 | 55 | func main() { 56 | tree := &TreeNode{ 57 | Val: 3, 58 | Left: &TreeNode{Val: 9}, 59 | Right: &TreeNode{ 60 | Val: 20, 61 | Left: &TreeNode{Val: 15}, 62 | Right: &TreeNode{Val: 7}, 63 | }, 64 | } 65 | fmt.Println(zigzagLevelOrder(tree)) 66 | tree = &TreeNode{ 67 | Val: 1, 68 | Left: &TreeNode{ 69 | Val: 2, 70 | Left: &TreeNode{ 71 | Val: 1, 72 | Left: &TreeNode{}, 73 | }, 74 | Right: &TreeNode{ 75 | Left: &TreeNode{ 76 | Left: &TreeNode{}, 77 | }, 78 | }, 79 | }, 80 | Right: &TreeNode{ 81 | Val: 2, 82 | }, 83 | } 84 | fmt.Println(zigzagLevelOrder(tree)) 85 | } 86 | -------------------------------------------------------------------------------- /0107-binary-tree-level-order-traversal-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // TreeNode ... 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func levelOrderBottom(root *TreeNode) [][]int { 19 | var res = [][]int{} 20 | currentLevel := []*TreeNode{root} 21 | for len(currentLevel) > 0 { 22 | nextLevel := []*TreeNode{} 23 | currentLevelTraverseResult := []int{} 24 | 25 | for _, n := range currentLevel { 26 | if n != nil { 27 | currentLevelTraverseResult = append(currentLevelTraverseResult, n.Val) 28 | } 29 | 30 | if n != nil && n.Left != nil { 31 | nextLevel = append(nextLevel, n.Left) 32 | } 33 | 34 | if n != nil && n.Right != nil { 35 | nextLevel = append(nextLevel, n.Right) 36 | } 37 | } 38 | 39 | if len(currentLevelTraverseResult) > 0 { 40 | res = append(res, currentLevelTraverseResult) 41 | } 42 | 43 | currentLevel = nextLevel 44 | } 45 | for i := 0; i < len(res)/2; i++ { 46 | res[i], res[len(res)-i-1] = res[len(res)-i-1], res[i] 47 | } 48 | return res 49 | } 50 | -------------------------------------------------------------------------------- /0110-balanced-binary-tree/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | // TreeNode ... 6 | type TreeNode struct { 7 | Val int 8 | Left *TreeNode 9 | Right *TreeNode 10 | } 11 | 12 | func max(a, b int) int { 13 | if a > b { 14 | return a 15 | } 16 | return b 17 | } 18 | func abs(a int) int { 19 | if a < 0 { 20 | return -a 21 | } 22 | return a 23 | } 24 | 25 | func depth(n *TreeNode) int { 26 | if n == nil { 27 | return 0 28 | } 29 | 30 | leftDepth := depth(n.Left) 31 | rightDepth := depth(n.Right) 32 | if leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1 { 33 | return -1 34 | } 35 | return max(leftDepth, rightDepth) + 1 36 | 37 | } 38 | 39 | func isBalanced(root *TreeNode) bool { 40 | return depth(root) != -1 41 | } 42 | -------------------------------------------------------------------------------- /0111-minimum-depth-of-binary-tree/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | // TreeNode ... 6 | type TreeNode struct { 7 | Val int 8 | Left *TreeNode 9 | Right *TreeNode 10 | } 11 | 12 | func traverse(n *TreeNode, parentDepth int, minDepth *int) { 13 | if n == nil { 14 | return 15 | } 16 | currentDep := parentDepth + 1 17 | if n.Left == nil && n.Right == nil { 18 | if currentDep < *minDepth { 19 | *minDepth = currentDep 20 | } 21 | return 22 | } 23 | 24 | traverse(n.Left, currentDep, minDepth) 25 | traverse(n.Right, currentDep, minDepth) 26 | } 27 | 28 | func minDepth(root *TreeNode) int { 29 | var res = 999999999 30 | traverse(root, 0, &res) 31 | return res 32 | } 33 | -------------------------------------------------------------------------------- /0112-path-sum/main.go: -------------------------------------------------------------------------------- 1 | package main 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 | func traverse(node *TreeNode, parentSum int, target int) bool { 12 | if node == nil { 13 | return false 14 | } 15 | 16 | currentSum := parentSum + node.Val 17 | 18 | if node.Left == nil && node.Right == nil && currentSum == target { 19 | return true 20 | } 21 | 22 | return traverse(node.Left, currentSum, target) || traverse(node.Right, currentSum, target) 23 | } 24 | 25 | func hasPathSum(root *TreeNode, sum int) bool { 26 | return traverse(root, 0, sum) 27 | } 28 | -------------------------------------------------------------------------------- /0113-path-sum-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // TreeNode ... 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func traverse(node *TreeNode, parentSum int, parentPath []int, target int, result *[][]int) { 19 | if node == nil { 20 | return 21 | } 22 | 23 | currentPath := append([]int{}, parentPath...) 24 | currentPath = append(currentPath, node.Val) 25 | currentSum := parentSum + node.Val 26 | 27 | // is leaf 28 | if node.Left == nil && node.Right == nil && currentSum == target { 29 | *result = append(*result, currentPath) 30 | return 31 | } 32 | 33 | if node.Left != nil { 34 | traverse(node.Left, currentSum, currentPath, target, result) 35 | } 36 | 37 | if node.Right != nil { 38 | traverse(node.Right, currentSum, currentPath, target, result) 39 | } 40 | } 41 | 42 | func pathSum(root *TreeNode, sum int) [][]int { 43 | res := [][]int{} 44 | traverse(root, 0, []int{}, sum, &res) 45 | return res 46 | } 47 | -------------------------------------------------------------------------------- /0118-pascals-triangle/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func generate(numRows int) [][]int { 6 | if numRows == 0 { 7 | return [][]int{} 8 | } 9 | 10 | var res = make([][]int, numRows) 11 | res[0] = []int{1} 12 | for i := 1; i < numRows; i++ { 13 | internalArr := make([]int, i+1) 14 | internalArr[0] = 1 15 | internalArr[len(internalArr)-1] = 1 16 | for j := 1; j < len(internalArr)-1; j++ { 17 | internalArr[j] = res[i-1][j-1] + res[i-1][j] 18 | } 19 | res[i] = internalArr 20 | } 21 | return res 22 | } 23 | 24 | func main() { 25 | fmt.Println(generate(5)) 26 | } 27 | -------------------------------------------------------------------------------- /0119-pascals-triangle-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func getRow(rowIndex int) []int { 6 | 7 | if rowIndex == 0 { 8 | return []int{1} 9 | } 10 | 11 | var res = make([][]int, rowIndex+1) 12 | res[0] = []int{1} 13 | for i := 1; i <= rowIndex; i++ { 14 | internalArr := make([]int, i+1) 15 | internalArr[0] = 1 16 | internalArr[len(internalArr)-1] = 1 17 | for j := 1; j < len(internalArr)-1; j++ { 18 | internalArr[j] = res[i-1][j-1] + res[i-1][j] 19 | } 20 | res[i] = internalArr 21 | } 22 | return res[len(res)-1] 23 | } 24 | 25 | func main() { 26 | fmt.Println(getRow(3)) 27 | fmt.Println(getRow(5)) 28 | } 29 | -------------------------------------------------------------------------------- /0125-valid-palindrome/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | func isPalindrome(s string) bool { 8 | lowered := strings.ToLower(s) 9 | 10 | filtered := "" 11 | 12 | for i := 0; i < len(lowered); i++ { 13 | if lowered[i] >= 'a' && lowered[i] <= 'z' { 14 | filtered += string([]byte{lowered[i]}) 15 | } 16 | if lowered[i] >= '0' && lowered[i] <= '9' { 17 | filtered += string([]byte{lowered[i]}) 18 | } 19 | } 20 | 21 | for i := 0; i < len(filtered)/2; i++ { 22 | if filtered[i] != filtered[len(filtered)-i-1] { 23 | return false 24 | } 25 | } 26 | return true 27 | } 28 | -------------------------------------------------------------------------------- /0125-valid-palindrome/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | s string 11 | expected bool 12 | } 13 | 14 | func TestIsPalindrome(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{s: "A man, a plan, a canal: Panama", expected: true}, 17 | TestCase{s: "race a car", expected: false}, 18 | TestCase{s: "", expected: true}, 19 | } 20 | for _, cas := range cases { 21 | res := isPalindrome(cas.s) 22 | assert.Equal(t, cas.expected, res, "input: "+cas.s) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /0125-valid-palindrome/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/valid-palindrome/description/ 4 | 5 | # desc 6 | 7 | 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 8 | 9 | 说明:本题中,我们将空字符串定义为有效的回文串。 10 | 11 | 示例 1: 12 | 13 | 输入: "A man, a plan, a canal: Panama" 14 | 输出: true 15 | 示例 2: 16 | 17 | 输入: "race a car" 18 | 输出: false 19 | -------------------------------------------------------------------------------- /0128-longest-consecutive-sequence/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type bounds struct { 4 | lowerBound int 5 | upperBound int 6 | } 7 | 8 | func longestConsecutive(nums []int) int { 9 | var boundsMap = map[int]bounds{} 10 | var recordMap = map[int]bool{} 11 | var maxLen = 0 12 | 13 | for _, num := range nums { 14 | if recordMap[num] == true { 15 | // 已经处理过的应该跳过,要么可能影响后续的后并 16 | continue 17 | } 18 | 19 | left := num - 1 20 | right := num + 1 21 | newBounds := bounds{ 22 | lowerBound: num, 23 | upperBound: num, 24 | } 25 | 26 | if _, ok := boundsMap[left]; ok { 27 | leftBounds := boundsMap[left] 28 | if leftBounds.upperBound >= num { 29 | continue 30 | } 31 | 32 | if leftBounds.upperBound == left { 33 | // 可以合并 34 | newBounds.lowerBound = leftBounds.lowerBound 35 | delete(boundsMap, left) 36 | } 37 | } 38 | 39 | if _, ok := boundsMap[right]; ok { 40 | rightBounds := boundsMap[right] 41 | if rightBounds.lowerBound <= num { 42 | continue 43 | } 44 | 45 | if rightBounds.lowerBound == right { 46 | // 可以合并 47 | newBounds.upperBound = rightBounds.upperBound 48 | delete(boundsMap, right) 49 | } 50 | } 51 | 52 | boundsMap[newBounds.lowerBound] = newBounds 53 | boundsMap[newBounds.upperBound] = newBounds 54 | currentLen := newBounds.upperBound - newBounds.lowerBound + 1 55 | if currentLen > maxLen { 56 | maxLen = currentLen 57 | } 58 | recordMap[num] = true 59 | } 60 | return maxLen 61 | } 62 | -------------------------------------------------------------------------------- /0128-longest-consecutive-sequence/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | nums []int 11 | expected int 12 | } 13 | 14 | func TestLongestConsecutive(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{nums: []int{100, 4, 200, 1, 3, 2}, expected: 4}, 17 | TestCase{nums: []int{0}, expected: 1}, 18 | TestCase{nums: []int{}, expected: 0}, 19 | TestCase{nums: []int{0, 1, 2, 3, 4}, expected: 5}, 20 | TestCase{nums: []int{4, 3, 2, -1, 1, 0}, expected: 6}, 21 | TestCase{nums: []int{4, 3, 2, -1, 1, 0, 5}, expected: 7}, 22 | TestCase{nums: []int{4, 4, 4, 4, 4, 4, 3, 2, -1, 1, 0, 5}, expected: 7}, 23 | TestCase{nums: []int{-7, -1, 3, -9, -4, 7, -3, 2, 4, 9, 4, -9, 8, -7, 5, -1, -7}, expected: 4}, 24 | } 25 | 26 | for _, cas := range cases { 27 | res := longestConsecutive(cas.nums) 28 | assert.Equal(t, cas.expected, res) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0128-longest-consecutive-sequence/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/longest-consecutive-sequence/description/ 4 | 5 | # desc 6 | 7 | 给定一个未排序的整数数组,找出最长连续序列的长度。 8 | 9 | 要求算法的时间复杂度为 O(n)。 10 | 11 | 示例: 12 | 13 | ``` 14 | 输入: [100, 4, 200, 1, 3, 2] 15 | 输出: 4 16 | 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。 17 | ``` -------------------------------------------------------------------------------- /0129-sum-root-to-leaf-numbers/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // TreeNode ... 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func traverse(node *TreeNode, parentSum int, resultArr *[]int) { 19 | if node == nil { 20 | return 21 | } 22 | 23 | currentSum := parentSum*10 + node.Val 24 | if node.Left == nil && node.Right == nil { 25 | *resultArr = append(*resultArr, currentSum) 26 | } 27 | 28 | traverse(node.Left, currentSum, resultArr) 29 | traverse(node.Right, currentSum, resultArr) 30 | } 31 | 32 | func sumNumbers(root *TreeNode) int { 33 | leafNums := []int{} 34 | traverse(root, 0, &leafNums) 35 | sum := 0 36 | for _, num := range leafNums { 37 | sum += num 38 | } 39 | return sum 40 | } 41 | -------------------------------------------------------------------------------- /0137-single-number-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func singleNumber(nums []int) int { 6 | res := 0 7 | for j := 0; j < 64; j++ { 8 | sum := 0 9 | for i := 0; i < len(nums); i++ { 10 | if (nums[i] >> uint(j) & 1) > 0 { 11 | sum++ 12 | } 13 | } 14 | if sum%3 > 0 { 15 | res |= 1 << uint(j) 16 | } 17 | } 18 | return res 19 | } 20 | 21 | func main() { 22 | fmt.Println(singleNumber([]int{2, 2, 3, 2})) 23 | } 24 | -------------------------------------------------------------------------------- /0139-word-break/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(wordBreak("leetcode", []string{"leet", "code"})) 10 | fmt.Println(wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", []string{"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"})) 11 | } 12 | 13 | func mark(s string, offset int, wordDict []string, marks []bool) { 14 | fmt.Println(s[offset:], offset, marks) 15 | if len(s) == 0 || offset >= len(s) { 16 | return 17 | } 18 | for i := 0; i < len(wordDict); i++ { 19 | if len(s[offset:]) >= len(wordDict[i]) && strings.HasPrefix(s[offset:], wordDict[i]) { 20 | if marks[offset+len(wordDict[i])-1] == true { 21 | // 这里是为了递归剪枝 22 | // 否则的话数量级会非常之大 23 | // 比如这里的例子: 24 | // 10 ^ len(s) 25 | continue 26 | } 27 | marks[offset+len(wordDict[i])-1] = true 28 | println(wordDict[i]) 29 | mark(s, offset+len(wordDict[i]), wordDict, marks) 30 | } 31 | } 32 | } 33 | 34 | func wordBreak(s string, wordDict []string) bool { 35 | marks := make([]bool, len(s)) 36 | mark(s, 0, wordDict, marks) 37 | return marks[len(s)-1] 38 | } 39 | -------------------------------------------------------------------------------- /0139-word-break/main_time_exceed.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(wordBreak("leetcode", []string{"leet", "code"})) 10 | fmt.Println(wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", []string{"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"})) 11 | } 12 | 13 | func wordBreak(s string, wordDict []string) bool { 14 | if s == "" { 15 | } 16 | 17 | var res bool 18 | resArr := []bool{} 19 | for i := 0; i < len(wordDict); i++ { 20 | if len(wordDict[i]) <= len(s) && strings.HasPrefix(s, wordDict[i]) { 21 | curr := wordBreak(s[len(wordDict[i]):], wordDict) 22 | if curr == true { 23 | return true 24 | } 25 | resArr = append(resArr, curr) 26 | } 27 | } 28 | //fmt.Println(resArr, s, wordDict) 29 | for i := 0; i < len(resArr); i++ { 30 | res = res || resArr[i] 31 | if res == true { 32 | return res 33 | } 34 | } 35 | return res 36 | } 37 | -------------------------------------------------------------------------------- /0140-word-break-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(wordBreak("catsanddog", []string{"cat", "cats", "and", "sand", "dog"})) 10 | } 11 | 12 | var res = [][]string{} 13 | 14 | func dfs(s string, offset int, wordDict []string, current []string) { 15 | if offset == len(s) { 16 | res = append(res, current) 17 | return 18 | } 19 | 20 | for i := 0; i < len(wordDict); i++ { 21 | if len(s[offset:]) >= len(wordDict[i]) && strings.HasPrefix(s[offset:], wordDict[i]) { 22 | path := make([]string, len(current)+1) 23 | copy(path, current) 24 | path[len(path)-1] = wordDict[i] 25 | dfs(s, offset+len(wordDict[i]), wordDict, path) 26 | } 27 | } 28 | } 29 | 30 | // dfs 31 | func wordBreak(s string, wordDict []string) []string { 32 | if !wordBreak1(s, wordDict) { 33 | return []string{} 34 | } 35 | res = res[:0] 36 | dfs(s, 0, wordDict, []string{}) 37 | final := []string{} 38 | fmt.Println(res) 39 | for i := 0; i < len(res); i++ { 40 | final = append(final, strings.Join(res[i], " ")) 41 | } 42 | return final 43 | } 44 | 45 | func mark(s string, offset int, wordDict []string, marks []bool) { 46 | fmt.Println(s[offset:], offset, marks) 47 | if len(s) == 0 || offset >= len(s) { 48 | return 49 | } 50 | for i := 0; i < len(wordDict); i++ { 51 | if len(s[offset:]) >= len(wordDict[i]) && strings.HasPrefix(s[offset:], wordDict[i]) { 52 | if marks[offset+len(wordDict[i])-1] == true { 53 | // 这里是为了递归剪枝 54 | // 否则的话数量级会非常之大 55 | // 比如这里的例子: 56 | // 10 ^ len(s) 57 | continue 58 | } 59 | marks[offset+len(wordDict[i])-1] = true 60 | println(wordDict[i]) 61 | mark(s, offset+len(wordDict[i]), wordDict, marks) 62 | } 63 | } 64 | } 65 | 66 | func wordBreak1(s string, wordDict []string) bool { 67 | marks := make([]bool, len(s)) 68 | mark(s, 0, wordDict, marks) 69 | return marks[len(s)-1] 70 | } 71 | -------------------------------------------------------------------------------- /0140-word-break-ii/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 需要优化,这样写太恶心了 4 | -------------------------------------------------------------------------------- /0141-linked-list-cycle/main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode(int x) : val(x), next(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | bool hasCycle(ListNode *head) { 13 | if (head == NULL || head->next == NULL) { 14 | return false; 15 | } 16 | 17 | ListNode * n1 = head; 18 | ListNode * n2 = head; 19 | while(n1 != NULL && n2 != NULL) { 20 | n1 = n1->next; 21 | if(n1 != NULL) { 22 | n1 = n1->next; 23 | } else { 24 | continue; 25 | } 26 | 27 | n2 = n2->next; 28 | if (n1 == n2 && n1 != NULL) { 29 | return true; 30 | } 31 | } 32 | 33 | return false; 34 | } 35 | }; 36 | 37 | int main() { 38 | ListNode *head = new ListNode(1); 39 | Solution s; 40 | cout << s.hasCycle(head) << endl; 41 | return 1; 42 | } -------------------------------------------------------------------------------- /0142-linked-list-cycle-ii/main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct ListNode { 6 | int val; 7 | ListNode *next; 8 | ListNode(int x) : val(x), next(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | ListNode *detectCycle(ListNode *head) { 14 | if(head == NULL) { 15 | return NULL; 16 | } 17 | 18 | unordered_map ptrMap; 19 | while(head != NULL) { 20 | if(ptrMap[long(head)]== 1) { 21 | return head; 22 | } 23 | 24 | // why?????? 25 | // ptrMap.insert(make_pair(long(head), 1)); 26 | ptrMap[long(head)] = 1; 27 | head = head->next; 28 | } 29 | 30 | return NULL; 31 | } 32 | }; 33 | 34 | int main() { 35 | Solution s; 36 | ListNode *head = new ListNode(1); 37 | head->next = head; 38 | cout << s.detectCycle(head) << endl; 39 | /* 40 | unordered_map ptrMap; 41 | ptrMap.insert(make_pair(long(head), 1)); 42 | cout << long(head) <<" " << ptrMap[long(head)] << endl; 43 | */ 44 | } -------------------------------------------------------------------------------- /0152-maximum-product-subarray/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxAndMin(sl ...int) (int, int) { 4 | var max = sl[0] 5 | var min = sl[0] 6 | for _, s := range sl { 7 | if s > max { 8 | max = s 9 | } 10 | if s < min { 11 | min = s 12 | } 13 | } 14 | return max, min 15 | } 16 | 17 | // 最大 18 | // 要么就是当前元素乘前面的最小值(当都为负时得到) 19 | // 要么就是当前元素乘前面的最大值(当都为正时得到) 20 | // 要么就是当前元素,当之前的值 * 当前的值还不如只保留当前值更大时 21 | func maxProduct(nums []int) int { 22 | if len(nums) == 1 { 23 | return nums[0] 24 | } 25 | 26 | var res = nums[0] 27 | var max = nums[0] 28 | var min = nums[0] 29 | 30 | for i := 1; i < len(nums); i++ { 31 | max, min = maxAndMin(nums[i], nums[i]*max, nums[i]*min) 32 | if max > res { 33 | res = max 34 | } 35 | } 36 | 37 | return res 38 | } 39 | -------------------------------------------------------------------------------- /0152-maximum-product-subarray/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | nums []int 11 | expected int 12 | } 13 | 14 | func TestMaxProduct(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{nums: []int{2, -5, -2, -4, 3}, expected: 24}, 17 | TestCase{nums: []int{2, 3, -2, 4}, expected: 6}, 18 | TestCase{nums: []int{-2, 0, -1}, expected: 0}, 19 | } 20 | 21 | for _, cas := range cases { 22 | res := maxProduct(cas.nums) 23 | assert.Equal(t, cas.expected, res) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0152-maximum-product-subarray/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/maximum-product-subarray/description/ 4 | 5 | # desc 6 | 7 | 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 8 | 9 | 示例 1: 10 | 11 | ``` 12 | 输入: [2,3,-2,4] 13 | 输出: 6 14 | 解释: 子数组 [2,3] 有最大乘积 6。 15 | ``` 16 | 17 | 示例 2: 18 | 19 | ``` 20 | 输入: [-2,0,-1] 21 | 输出: 0 22 | 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 23 | ``` -------------------------------------------------------------------------------- /0155-min-stack/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type MinStack struct { 4 | elems []int 5 | mins []int 6 | } 7 | 8 | /** initialize your data structure here. */ 9 | func Constructor() MinStack { 10 | return MinStack{ 11 | elems: make([]int, 0), 12 | mins: make([]int, 0), 13 | } 14 | } 15 | 16 | func (this *MinStack) Push(x int) { 17 | this.elems = append(this.elems, x) 18 | topIdx := len(this.mins) - 1 19 | if topIdx >= 0 && this.mins[topIdx] < x { 20 | this.mins = append(this.mins, this.mins[topIdx]) 21 | } else { 22 | this.mins = append(this.mins, x) 23 | } 24 | } 25 | 26 | func (this *MinStack) Pop() { 27 | l := len(this.elems) 28 | this.elems = this.elems[0 : l-1] 29 | this.mins = this.mins[0 : l-1] 30 | } 31 | 32 | func (this *MinStack) Top() int { 33 | topIdx := len(this.elems) - 1 34 | return this.elems[topIdx] 35 | } 36 | 37 | func (this *MinStack) GetMin() int { 38 | topIdx := len(this.mins) - 1 39 | return this.mins[topIdx] 40 | } 41 | 42 | /** 43 | * Your MinStack object will be instantiated and called as such: 44 | * obj := Constructor(); 45 | * obj.Push(x); 46 | * obj.Pop(); 47 | * param_3 := obj.Top(); 48 | * param_4 := obj.GetMin(); 49 | */ 50 | -------------------------------------------------------------------------------- /0155-min-stack/main_test.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cch123/leetcode-go/4b6504edcdd8b80d202848e6e18596c7e82a48af/0155-min-stack/main_test.go -------------------------------------------------------------------------------- /0155-min-stack/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/min-stack/description/ 4 | 5 | # desc 6 | 7 | 8 | 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 9 | 10 | ``` 11 | push(x) -- 将元素 x 推入栈中。 12 | pop() -- 删除栈顶的元素。 13 | top() -- 获取栈顶元素。 14 | getMin() -- 检索栈中的最小元素。 15 | ``` 16 | 17 | 示例: 18 | 19 | ``` 20 | MinStack minStack = new MinStack(); 21 | minStack.push(-2); 22 | minStack.push(0); 23 | minStack.push(-3); 24 | minStack.getMin(); --> 返回 -3. 25 | minStack.pop(); 26 | minStack.top(); --> 返回 0. 27 | minStack.getMin(); --> 返回 -2. 28 | ``` 29 | -------------------------------------------------------------------------------- /0162-find-peak-element/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var res = []int{} 4 | 5 | func find(nums []int, startIdx, endIdx int) { 6 | if startIdx > endIdx { 7 | return 8 | } 9 | 10 | mid := startIdx + (endIdx-startIdx)/2 11 | if mid == 0 && nums[mid] > nums[mid+1] { 12 | res = append(res, mid) 13 | return 14 | } 15 | 16 | if mid == len(nums)-1 && nums[mid] > nums[mid-1] { 17 | res = append(res, mid) 18 | return 19 | } 20 | 21 | if mid > 0 && mid < len(nums)-1 && nums[mid] > nums[mid-1] && 22 | nums[mid] > nums[mid+1] { 23 | res = append(res, mid) 24 | return 25 | } 26 | find(nums, startIdx, mid-1) 27 | find(nums, mid+1, endIdx) 28 | } 29 | 30 | func findPeakElement(nums []int) int { 31 | if len(nums) == 1 { 32 | return 0 33 | } 34 | 35 | if len(nums) == 2 { 36 | if nums[0] > nums[1] { 37 | return 0 38 | } 39 | return 1 40 | } 41 | 42 | res = res[:0] 43 | 44 | startIdx, endIdx := 0, len(nums)-1 45 | 46 | mid := startIdx + (endIdx-startIdx)/2 47 | 48 | find(nums, startIdx, mid-1) 49 | find(nums, mid, endIdx) 50 | 51 | if len(res) == 0 { 52 | return 0 53 | } 54 | 55 | return res[0] 56 | } 57 | -------------------------------------------------------------------------------- /0162-find-peak-element/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | nums []int 11 | expected int 12 | } 13 | 14 | func TestFindPeakElement(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{nums: []int{2, 1}, expected: 0}, 17 | TestCase{nums: []int{1, 2}, expected: 1}, 18 | TestCase{nums: []int{1, 2, 3}, expected: 2}, 19 | TestCase{nums: []int{3, 2, 1}, expected: 0}, 20 | TestCase{nums: []int{1, 2, 3, 2, 1}, expected: 2}, 21 | TestCase{nums: []int{1, 2, 2, 3, 2, 1}, expected: 3}, 22 | TestCase{nums: []int{1, 2, 3, 1}, expected: 2}, 23 | TestCase{nums: []int{1, 2, 1, 3, 5, 6, 4}, expected: 1}, 24 | } 25 | 26 | for _, cas := range cases { 27 | res := findPeakElement(cas.nums) 28 | assert.Equal(t, cas.expected, res) 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /0162-find-peak-element/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/find-peak-element/description/ 4 | 5 | # desc 6 | 7 | 峰值元素是指其值大于左右相邻值的元素。 8 | 9 | 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 10 | 11 | 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 12 | 13 | 你可以假设 nums[-1] = nums[n] = -∞。 14 | 15 | 示例 1: 16 | 17 | ``` 18 | 输入: nums = [1,2,3,1] 19 | 输出: 2 20 | 解释: 3 是峰值元素,你的函数应该返回其索引 2。 21 | ``` 22 | 23 | 示例 2: 24 | 25 | ``` 26 | 输入: nums = [1,2,1,3,5,6,4] 27 | 输出: 1 或 5 28 | 解释: 你的函数可以返回索引 1,其峰值元素为 2; 29 | 或者返回索引 5, 其峰值元素为 6。 30 | ``` 31 | 32 | 说明: 33 | 34 | 你的解法应该是 O(logN) 时间复杂度的。 -------------------------------------------------------------------------------- /0167-two-sum-ii-input-array-is-sorted/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func twoSum(numbers []int, target int) []int { 4 | var numMap = map[int]int{} 5 | for i := 0; i < len(numbers); i++ { 6 | numMap[numbers[i]] = i 7 | } 8 | 9 | for i := 0; i < len(numbers); i++ { 10 | if numMap[target-numbers[i]] > 0 && numMap[target-numbers[i]] != i { 11 | return []int{i + 1, numMap[target-numbers[i]] + 1} 12 | } 13 | } 14 | return []int{} 15 | } 16 | -------------------------------------------------------------------------------- /0179-largest-number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func compare(x, y int) bool { 9 | iStr := fmt.Sprint(x) 10 | jStr := fmt.Sprint(y) 11 | if iStr+jStr > jStr+iStr { 12 | return true 13 | } 14 | return false 15 | } 16 | 17 | func largestNumber(nums []int) string { 18 | res := "" 19 | sort.Slice(nums, func(i, j int) bool { 20 | return compare(nums[i], nums[j]) 21 | }) 22 | 23 | for i := 0; i < len(nums); i++ { 24 | res += fmt.Sprint(nums[i]) 25 | } 26 | 27 | // check whether all zero 28 | var allZeroFlag = true 29 | for i := 0; i < len(res); i++ { 30 | if res[i] != '0' { 31 | allZeroFlag = false 32 | } 33 | } 34 | 35 | if allZeroFlag { 36 | res = "0" 37 | } 38 | 39 | return res 40 | } 41 | -------------------------------------------------------------------------------- /0179-largest-number/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | nums []int 11 | expected string 12 | } 13 | 14 | func TestLargestNumber(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{nums: []int{0, 0}, expected: "0"}, 17 | TestCase{nums: []int{121, 12}, expected: "12121"}, 18 | TestCase{nums: []int{128, 12}, expected: "12812"}, 19 | TestCase{nums: []int{2, 1}, expected: "21"}, 20 | TestCase{nums: []int{20, 1}, expected: "201"}, 21 | TestCase{nums: []int{10, 2}, expected: "210"}, 22 | TestCase{nums: []int{3, 30, 34, 5, 9}, expected: "9534330"}, 23 | } 24 | 25 | for _, cas := range cases { 26 | res := largestNumber(cas.nums) 27 | assert.Equal(t, cas.expected, res) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /0179-largest-number/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/largest-number/description/ 4 | 5 | # desc 6 | 7 | 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。 8 | 9 | 示例 1: 10 | 11 | ``` 12 | 输入: [10,2] 13 | 输出: 210 14 | ``` 15 | 16 | 示例 2: 17 | 18 | ``` 19 | 输入: [3,30,34,5,9] 20 | 输出: 9534330 21 | ``` 22 | 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。 23 | 24 | # hint 25 | 26 | a > b 说明 concat(a, b) > concat(b, a) 27 | -------------------------------------------------------------------------------- /0191-number-of-1-bits/main.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdint.h" 3 | 4 | int hammingWeight(uint32_t n) { 5 | int cnt = 0; 6 | while(1) { 7 | if(n == 0) { 8 | break; 9 | } 10 | 11 | if (n%2 == 1) { 12 | cnt ++; 13 | } 14 | 15 | n = n/2; 16 | } 17 | return cnt; 18 | } 19 | 20 | int main() { 21 | return 0; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /0202-happy-number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | } 5 | 6 | func next(n int) int { 7 | sum := 0 8 | for n > 0 { 9 | mod := n % 10 10 | sum += mod * mod 11 | n /= 10 12 | } 13 | return sum 14 | } 15 | 16 | func isHappy(n int) bool { 17 | seenBefore := map[int]bool{} 18 | for { 19 | if n == 1 { 20 | return true 21 | } 22 | 23 | if seenBefore[n] == true { 24 | return false 25 | } 26 | 27 | seenBefore[n] = true 28 | n = next(n) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0203-remove-linked-list-elements/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // ListNode ... 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * type ListNode struct { 12 | * Val int 13 | * Next *ListNode 14 | * } 15 | */ 16 | func removeElements(head *ListNode, val int) *ListNode { 17 | 18 | // decide head 19 | for head != nil && head.Val == val { 20 | head = head.Next 21 | } 22 | 23 | if head == nil { 24 | return nil 25 | } 26 | 27 | cur := head 28 | for cur.Next != nil { 29 | if cur.Next.Val == val { 30 | cur.Next = cur.Next.Next 31 | } else { 32 | cur = cur.Next 33 | } 34 | } 35 | 36 | return head 37 | } 38 | 39 | func main() { 40 | root := &ListNode{Val: 1, 41 | Next: &ListNode{Val: 2, 42 | Next: &ListNode{Val: 6, 43 | Next: &ListNode{Val: 3, 44 | Next: &ListNode{Val: 4, 45 | Next: &ListNode{Val: 5, 46 | Next: &ListNode{Val: 6}}}}}}} 47 | removeElements(root, 3) 48 | for root != nil { 49 | println(root.Val) 50 | root = root.Next 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /0204-count-primes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func main() { 8 | println(countPrimes(10)) 9 | println(countPrimes(20)) 10 | println(countPrimes(100)) 11 | } 12 | 13 | func countPrimes(n int) int { 14 | if n < 2 { 15 | return 0 16 | } 17 | var numArr = make([]int, n+1) 18 | numArr[0] = -1 19 | numArr[1] = -1 20 | for i := 2; i <= int(math.Sqrt(float64(n)))+1; i++ { 21 | for j := 2 * i; j <= n; j += i { 22 | numArr[j] = -1 23 | } 24 | } 25 | cnt := 0 26 | for i := 2; i < n; i++ { 27 | if numArr[i] != -1 { 28 | cnt++ 29 | } 30 | } 31 | //fmt.Printf("%#v\n", numArr) 32 | return cnt 33 | } 34 | -------------------------------------------------------------------------------- /0205-isomorphic-strings/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | func sliceEqual(a []int, b []int) bool { 8 | if len(a) != len(b) { 9 | return false 10 | } 11 | for i := 0; i < len(a); i++ { 12 | if a[i] != b[i] { 13 | return false 14 | } 15 | } 16 | return true 17 | } 18 | 19 | func isIsomorphic(s string, t string) bool { 20 | if len(s) != len(t) { 21 | return false 22 | } 23 | 24 | var byteMapS = map[byte][]int{} 25 | var byteMapT = map[byte][]int{} 26 | for i := 0; i < len(s); i++ { 27 | currentChar := s[i] 28 | byteMapS[currentChar] = append(byteMapS[currentChar], i) 29 | currentCharT := t[i] 30 | byteMapT[currentCharT] = append(byteMapT[currentCharT], i) 31 | if !sliceEqual(byteMapS[currentChar], byteMapT[currentCharT]) { 32 | return false 33 | } 34 | } 35 | return true 36 | } 37 | -------------------------------------------------------------------------------- /0216-combination-sum-iii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(combinationSum3(3, 7)) 7 | fmt.Println(combinationSum3(3, 2)) 8 | fmt.Println(combinationSum3(2, 18)) 9 | } 10 | 11 | func nextCombination(zoArr []int) bool { 12 | // 从左向右找第一个 10 13 | // swap 10 => 01 14 | // 把 01 之前所有的 1 移到开头位置 15 | found := false 16 | for i := 0; i < len(zoArr)-1; i++ { 17 | if zoArr[i] == 1 && zoArr[i+1] == 0 { 18 | if i >= 8 { 19 | break 20 | } 21 | zoArr[i], zoArr[i+1] = zoArr[i+1], zoArr[i] 22 | posForOne := 0 23 | for j := 0; j < i; j++ { 24 | if zoArr[j] == 1 { 25 | zoArr[j] = 0 26 | zoArr[posForOne] = 1 27 | posForOne++ 28 | } 29 | } 30 | found = true 31 | break 32 | } 33 | } 34 | fmt.Println(zoArr) 35 | return found 36 | } 37 | 38 | func calcSum(zoArr []int) int { 39 | sum := 0 40 | for i := 0; i < len(zoArr); i++ { 41 | if zoArr[i] == 1 { 42 | sum += i + 1 43 | } 44 | } 45 | return sum 46 | } 47 | 48 | func combinationSum3(k int, n int) [][]int { 49 | if k >= n { 50 | return [][]int{} 51 | } 52 | zoArr := make([]int, n) 53 | // init 54 | for i := 0; i < k; i++ { 55 | zoArr[i] = 1 56 | } 57 | 58 | var res = [][]int{} 59 | for { 60 | if calcSum(zoArr) == n { 61 | currentArr := []int{} 62 | for i := 0; i < len(zoArr); i++ { 63 | if zoArr[i] == 1 { 64 | currentArr = append(currentArr, i+1) 65 | } 66 | } 67 | res = append(res, currentArr) 68 | } 69 | 70 | if !nextCombination(zoArr) { 71 | break 72 | } 73 | } 74 | return res 75 | } 76 | -------------------------------------------------------------------------------- /0219-contains-duplicate-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func containsNearbyDuplicate(nums []int, k int) bool { 4 | var numMap = map[int]int{} 5 | for i := 0; i < len(nums); i++ { 6 | if _, ok := numMap[nums[i]]; ok { 7 | if i-numMap[nums[i]] <= k { 8 | return true 9 | } 10 | } 11 | numMap[nums[i]] = i 12 | } 13 | return false 14 | } 15 | -------------------------------------------------------------------------------- /0231-power-of-two/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | func isPowerOfTwo(n int) bool { 8 | if n <= 0 { 9 | return false 10 | } 11 | return (n & (n - 1)) == 0 12 | } 13 | -------------------------------------------------------------------------------- /0232-implement-queue-using-stacks/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | type MyQueue struct { 8 | stackLeft []int 9 | stackRight []int 10 | } 11 | 12 | /** Initialize your data structure here. */ 13 | func Constructor() MyQueue { 14 | return MyQueue{ 15 | stackLeft: []int{}, 16 | stackRight: []int{}, 17 | } 18 | } 19 | 20 | /** Push element x to the back of queue. */ 21 | func (this *MyQueue) Push(x int) { 22 | if len(this.stackLeft) == 0 && len(this.stackRight) != 0 { 23 | for i := len(this.stackRight) - 1; i >= 0; i-- { 24 | this.stackLeft = append(this.stackLeft, this.stackRight[i]) 25 | } 26 | this.stackRight = this.stackRight[:0] 27 | } 28 | 29 | this.stackLeft = append(this.stackLeft, x) 30 | } 31 | 32 | /** Removes the element from in front of queue and returns that element. */ 33 | func (this *MyQueue) Pop() int { 34 | if len(this.stackLeft) != 0 { 35 | for i := len(this.stackLeft) - 1; i >= 0; i-- { 36 | this.stackRight = append(this.stackRight, this.stackLeft[i]) 37 | } 38 | this.stackLeft = this.stackLeft[:0] 39 | } 40 | popElem := this.stackRight[len(this.stackRight)-1] 41 | this.stackRight = this.stackRight[:len(this.stackRight)-1] 42 | return popElem 43 | } 44 | 45 | /** Get the front element. */ 46 | func (this *MyQueue) Peek() int { 47 | if len(this.stackLeft) > 0 { 48 | return this.stackLeft[0] 49 | } 50 | return this.stackRight[len(this.stackRight)-1] 51 | } 52 | 53 | /** Returns whether the queue is empty. */ 54 | func (this *MyQueue) Empty() bool { 55 | if len(this.stackRight) > 0 || len(this.stackLeft) > 0 { 56 | return false 57 | } 58 | 59 | return true 60 | } 61 | 62 | /** 63 | * Your MyQueue object will be instantiated and called as such: 64 | * obj := Constructor(); 65 | * obj.Push(x); 66 | * param_2 := obj.Pop(); 67 | * param_3 := obj.Peek(); 68 | * param_4 := obj.Empty(); 69 | */ 70 | -------------------------------------------------------------------------------- /0235-lowest-common-ancestor-of-a-binary-search-tree/main.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | TreeNode * cur = root; 14 | if (cur->val >= p->val && cur->val <=q->val) { 15 | return cur; 16 | } 17 | if (cur->val >=q->val && cur->val <=p->val) { 18 | return cur; 19 | } 20 | if (cur->val > p->val && cur->val > q->val) { 21 | return lowestCommonAncestor(cur->left, p, q); 22 | } 23 | if (cur->val < p->val && cur->val < q->val) { 24 | return lowestCommonAncestor(cur->right, p, q); 25 | } 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /0237-delete-node-in-a-linked-list/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | 9 | func deleteNode(node *ListNode) { 10 | node.Val = node.Next.Val 11 | node.Next = node.Next.Next 12 | } 13 | 14 | func main() { 15 | } 16 | -------------------------------------------------------------------------------- /0257-binary-tree-paths/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // TreeNode ... 6 | type TreeNode struct { 7 | Val int 8 | Left *TreeNode 9 | Right *TreeNode 10 | } 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * type TreeNode struct { 15 | * Val int 16 | * Left *TreeNode 17 | * Right *TreeNode 18 | * } 19 | */ 20 | 21 | func traverse(node *TreeNode, parentPath string, resultMap map[string]struct{}) { 22 | currentPath := parentPath + "->" + fmt.Sprint(node.Val) 23 | if parentPath == "" { 24 | currentPath = fmt.Sprint(node.Val) 25 | } 26 | if node.Left == nil && node.Right == nil { 27 | resultMap[currentPath] = struct{}{} 28 | } 29 | 30 | if node.Left != nil { 31 | traverse(node.Left, currentPath, resultMap) 32 | } 33 | 34 | if node.Right != nil { 35 | traverse(node.Right, currentPath, resultMap) 36 | } 37 | } 38 | 39 | func binaryTreePaths(root *TreeNode) []string { 40 | var resultMap = map[string]struct{}{} 41 | var res = []string{} 42 | if root == nil { 43 | return res 44 | } 45 | 46 | traverse(root, "", resultMap) 47 | for k := range resultMap { 48 | res = append(res, k) 49 | } 50 | return res 51 | } 52 | -------------------------------------------------------------------------------- /0260-single-number-iii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func singleNumber(nums []int) []int { 6 | bitMask := 0 7 | for _, num := range nums { 8 | bitMask = bitMask ^ num 9 | } 10 | singleBitMask := 1 11 | for singleBitMask&bitMask == 0 { 12 | singleBitMask <<= 1 13 | } 14 | n1, n2 := 0, 0 15 | for _, num := range nums { 16 | if num&singleBitMask == 0 { 17 | n1 = n1 ^ num 18 | } else { 19 | n2 = n2 ^ num 20 | } 21 | } 22 | return []int{n1, n2} 23 | } 24 | -------------------------------------------------------------------------------- /0263-ugly-number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // 如果条件改了,可以考虑把 2/3/5/7 放在数组里 4 | // 双层 for 循环 5 | 6 | func isUgly(num int) bool { 7 | if num == 0 { 8 | return false 9 | } 10 | for num%2 == 0 { 11 | num = num / 2 12 | } 13 | for num%3 == 0 { 14 | num = num / 3 15 | } 16 | for num%5 == 0 { 17 | num = num / 5 18 | } 19 | if num == 1 { 20 | return true 21 | } 22 | return false 23 | } 24 | -------------------------------------------------------------------------------- /0283-move-zeroes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | func moveZeroes(nums []int) { 5 | nonZeroPos := 0 6 | for i := 0; i < len(nums); i++ { 7 | if nums[i] != 0 { 8 | nums[i], nums[nonZeroPos] = nums[nonZeroPos], nums[i] 9 | nonZeroPos++ 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /0292-nim-game/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func canWinNim(n int) bool { 4 | if n % 4 > 0 { 5 | return true 6 | } 7 | 8 | return false 9 | } 10 | -------------------------------------------------------------------------------- /0338-counting-bits/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(countBits(5)) 7 | } 8 | 9 | func countBits(num int) []int { 10 | if num == 0 { 11 | return []int{0} 12 | } 13 | if num == 1 { 14 | return []int{0, 1} 15 | } 16 | res := make([]int, num+1) 17 | res[0], res[1] = 0, 1 18 | round := 1 19 | outer: 20 | for { 21 | round = round * 2 22 | for i := round; i < round*2; i++ { 23 | if i > num { 24 | break outer 25 | } 26 | res[i] = res[i-round] + 1 27 | } 28 | } 29 | return res 30 | } 31 | -------------------------------------------------------------------------------- /0342-power-of-four/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func isPowerOfFour(num int) bool { 6 | if num <= 0 { 7 | return false 8 | } 9 | return (num&(num-1)) == 0 && (num&0x55555555) == num 10 | 11 | } 12 | -------------------------------------------------------------------------------- /0345-reverse-vowels-of-a-string/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func reverseVowels(s string) string { 6 | vowelArr := []byte{} 7 | var m = map[byte]bool{ 8 | 'a': true, 9 | 'A': true, 10 | 'e': true, 11 | 'E': true, 12 | 'i': true, 13 | 'I': true, 14 | 'o': true, 15 | 'u': true, 16 | 'O': true, 17 | 'U': true, 18 | } 19 | 20 | for i := 0; i < len(s); i++ { 21 | if m[s[i]] == true { 22 | vowelArr = append(vowelArr, s[i]) 23 | } 24 | } 25 | 26 | res := []byte{} 27 | pos := len(vowelArr) - 1 28 | for i := 0; i < len(s); i++ { 29 | if m[s[i]] == true { 30 | vowelArr = append(vowelArr, s[i]) 31 | res = append(res, vowelArr[pos]) 32 | pos-- 33 | } else { 34 | res = append(res, s[i]) 35 | } 36 | } 37 | return string(res) 38 | } 39 | -------------------------------------------------------------------------------- /0349-intersection-of-two-arrays/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func intersection(nums1 []int, nums2 []int) []int { 4 | res := []int{} 5 | var valMap = map[int]bool{} 6 | for i:=0;i num1Map[num] { 18 | num2Map[num] = num1Map[num] 19 | } 20 | } 21 | } 22 | res := []int{} 23 | for num, cnt := range num2Map { 24 | for i := 0; i < cnt; i++ { 25 | res = append(res, num) 26 | } 27 | } 28 | return res 29 | } 30 | -------------------------------------------------------------------------------- /0383-ransom-note/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func canConstruct(ransomNote string, magazine string) bool { 6 | byteMap := map[byte]int{} 7 | for i := 0; i < len(magazine); i++ { 8 | byteMap[magazine[i]]++ 9 | } 10 | byteMapForR := map[byte]int{} 11 | for i := 0; i < len(ransomNote); i++ { 12 | byteMapForR[ransomNote[i]]++ 13 | if byteMap[ransomNote[i]] < byteMapForR[ransomNote[i]] { 14 | return false 15 | } 16 | } 17 | return true 18 | 19 | } 20 | -------------------------------------------------------------------------------- /0384-shuffle-an-array/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math/rand" 4 | 5 | func main() { 6 | 7 | } 8 | 9 | type Solution struct { 10 | initial []int 11 | } 12 | 13 | func Constructor(nums []int) Solution { 14 | initial := append([]int{}, nums...) 15 | return Solution{initial: initial} 16 | } 17 | 18 | /** Resets the array to its original configuration and return it. */ 19 | func (this *Solution) Reset() []int { 20 | return this.initial 21 | } 22 | 23 | /** Returns a random shuffling of the array. */ 24 | func (this *Solution) Shuffle() []int { 25 | copied := append([]int{}, this.initial...) 26 | for i := 0; i < len(this.initial); i++ { 27 | elemCnt := len(this.initial) - i 28 | j := rand.Intn(elemCnt) 29 | copied[j], copied[elemCnt-1] = copied[elemCnt-1], copied[j] 30 | } 31 | return copied 32 | } 33 | 34 | /** 35 | * Your Solution object will be instantiated and called as such: 36 | * obj := Constructor(nums); 37 | * param_1 := obj.Reset(); 38 | * param_2 := obj.Shuffle(); 39 | */ 40 | -------------------------------------------------------------------------------- /0389-find-the-difference/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // t 是先重排 s,再添加字母的结果 4 | func findTheDifference(s string, t string) byte { 5 | var sMap = map[byte]int{} 6 | var tMap = map[byte]int{} 7 | for i := 0; i < len(s); i++ { 8 | sMap[s[i]]++ 9 | tMap[t[i]]++ 10 | } 11 | tMap[t[len(s)]]++ 12 | for b, cnt := range tMap { 13 | if cnt-sMap[b] == 1 { 14 | return b 15 | } 16 | } 17 | 18 | return 0 19 | } 20 | -------------------------------------------------------------------------------- /0404-sum-of-left-leaves/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // TreeNode ... 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func traverse(node *TreeNode, sum *int) { 19 | if node == nil { 20 | return 21 | } 22 | 23 | if node.Left != nil && node.Left.Left == nil && node.Left.Right == nil { 24 | *sum += node.Left.Val 25 | } 26 | traverse(node.Left, sum) 27 | traverse(node.Right, sum) 28 | } 29 | 30 | func sumOfLeftLeaves(root *TreeNode) int { 31 | sum := 0 32 | traverse(root, &sum) 33 | return sum 34 | } 35 | -------------------------------------------------------------------------------- /0412-fizz-buzz/main.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cch123/leetcode-go/4b6504edcdd8b80d202848e6e18596c7e82a48af/0412-fizz-buzz/main.go -------------------------------------------------------------------------------- /0415-add-strings/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func reverse(str string) string { 4 | strBytes := []byte(str) 5 | for i := 0; i < len(strBytes)/2; i++ { 6 | strBytes[i], strBytes[len(strBytes)-1-i] = strBytes[len(strBytes)-1-i], strBytes[i] 7 | } 8 | return string(strBytes) 9 | } 10 | 11 | var byteArr = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} 12 | var byteMap = map[byte]int{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} 13 | 14 | func addStrings(num1 string, num2 string) string { 15 | num1 = reverse(num1) 16 | num2 = reverse(num2) 17 | if len(num2) < len(num1) { 18 | num1, num2 = num2, num1 19 | } 20 | resInts := []int{} 21 | // num1 比 num2 短 22 | for i := 0; i < len(num1); i++ { 23 | plusRes := byteMap[num1[i]] + byteMap[num2[i]] 24 | resInts = append(resInts, plusRes) 25 | } 26 | for i := len(num1); i < len(num2); i++ { 27 | resInts = append(resInts, byteMap[num2[i]]) 28 | } 29 | 30 | // 进位 31 | for i := 0; i < len(resInts)-1; i++ { 32 | if resInts[i] >= 10 && i+1 < len(resInts) { 33 | resInts[i+1]++ 34 | resInts[i] -= 10 35 | continue 36 | } 37 | } 38 | 39 | // 最后一位特殊处理 40 | if resInts[len(resInts)-1] >= 10 { 41 | resInts[len(resInts)-1] -= 10 42 | resInts = append(resInts, 1) 43 | } 44 | 45 | resBytes := []byte{} 46 | // gen bytes 47 | for i := 0; i < len(resInts); i++ { 48 | resBytes = append(resBytes, byteArr[resInts[i]]) 49 | } 50 | return reverse(string(resBytes)) 51 | } 52 | 53 | func main() { 54 | println(addStrings("1", "9")) 55 | } 56 | -------------------------------------------------------------------------------- /0434-number-of-segments-in-a-string/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strings" 4 | 5 | func main() {} 6 | 7 | func countSegments(s string) int { 8 | arr := strings.Split(s, " ") 9 | cnt := 0 10 | for _, x := range arr { 11 | if len(x) > 0 { 12 | cnt++ 13 | } 14 | } 15 | return cnt 16 | } 17 | -------------------------------------------------------------------------------- /0459-repeated-substring-pattern/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(repeatedSubstringPattern("abab")) 7 | } 8 | 9 | func match(s, substr string) bool { 10 | if len(s)%len(substr) != 0 || len(s) == len(substr) { 11 | return false 12 | } 13 | 14 | for i := 0; i < len(s); i += len(substr) { 15 | if s[i:i+len(substr)] != substr { 16 | return false 17 | } 18 | } 19 | return true 20 | } 21 | 22 | func repeatedSubstringPattern(s string) bool { 23 | for i := 1; i < len(s); i++ { 24 | substr := s[0:i] 25 | if match(s, substr) { 26 | return true 27 | } 28 | } 29 | return false 30 | } 31 | -------------------------------------------------------------------------------- /0461-hamming-distance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func hammingDistance(x int, y int) int { 4 | // 将 x 与 y 不同的位置 1 5 | // 所以就是异或的逻辑 6 | xorResult := x ^ y 7 | cnt := 0 8 | for xorResult > 0 { 9 | if xorResult%2 == 1 { 10 | cnt++ 11 | } 12 | xorResult /= 2 13 | } 14 | return cnt 15 | } 16 | -------------------------------------------------------------------------------- /0476-number-complement/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findComplement(num int) int { 4 | var mask = ^0 5 | for num&mask > 0 { 6 | mask <<= 1 7 | } 8 | mask = ^mask 9 | return mask ^ num 10 | } 11 | -------------------------------------------------------------------------------- /0486-max-consecutive-ones/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findMaxConsecutiveOnes(nums []int) int { 4 | max := 0 5 | currentCnt := 0 6 | for i := 0; i < len(nums); i++ { 7 | if nums[i] == 1 { 8 | currentCnt++ 9 | if currentCnt > max { 10 | max = currentCnt 11 | } 12 | } else { 13 | currentCnt = 0 14 | } 15 | } 16 | return max 17 | } 18 | -------------------------------------------------------------------------------- /0496-next-greater-element-i/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func nextGreaterElement(findNums []int, nums []int) []int { 6 | var elemBiggerMap = map[int]int{} 7 | for i := 0; i < len(nums); i++ { 8 | biggerIdx := -1 9 | for j := i + 1; j < len(nums); j++ { 10 | if nums[j] > nums[i] { 11 | biggerIdx = nums[j] 12 | break 13 | } 14 | } 15 | elemBiggerMap[nums[i]] = biggerIdx 16 | } 17 | var res []int 18 | for i := 0; i < len(findNums); i++ { 19 | res = append(res, elemBiggerMap[findNums[i]]) 20 | } 21 | return res 22 | } 23 | 24 | func main() { 25 | fmt.Println(nextGreaterElement([]int{4, 1, 2}, []int{1, 3, 4, 2})) 26 | } 27 | -------------------------------------------------------------------------------- /0500-keyboard-row/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | var byteMap = map[byte]int{ 9 | 'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 10 | 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 11 | 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 12 | 'h': 2, 'j': 2, 'k': 2, 'l': 2, 13 | 'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, 14 | 'n': 3, 'm': 3, 15 | } 16 | 17 | func findWords(words []string) []string { 18 | res := []string{} 19 | outer: 20 | for i := 0; i < len(words); i++ { 21 | wordL := strings.ToLower(words[i]) 22 | for j := 1; j < len(wordL); j++ { 23 | if byteMap[wordL[j]] != byteMap[wordL[j-1]] { 24 | continue outer 25 | } 26 | } 27 | res = append(res, words[i]) 28 | } 29 | return res 30 | } 31 | 32 | func main() { 33 | fmt.Println(findWords([]string{"Hello", "Alaska", "Dad", "Peace"})) 34 | } 35 | -------------------------------------------------------------------------------- /0503-next-greater-element-ii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func nextGreaterElements(nums []int) []int { 6 | numsMore := append([]int{}, nums...) 7 | numsMore = append(numsMore, nums...) 8 | result := []int{} 9 | for i := 0; i < len(nums); i++ { 10 | biggerResult := -1 11 | for j := i + 1; j < i+len(nums); j++ { 12 | if numsMore[j] > nums[i] { 13 | biggerResult = numsMore[j] 14 | break 15 | } 16 | } 17 | result = append(result, biggerResult) 18 | } 19 | return result 20 | } 21 | 22 | func main() { 23 | fmt.Println(nextGreaterElements([]int{1, 2, 1})) 24 | } 25 | -------------------------------------------------------------------------------- /0504-base-7/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func convertToBase7(num int) string { 6 | if num == 0 { 7 | return "0" 8 | } 9 | negFlag := false 10 | if num < 0 { 11 | num = -num 12 | negFlag = true 13 | } 14 | 15 | var res = "" 16 | 17 | for num != 0 { 18 | mod := num % 7 19 | res = fmt.Sprint(mod) + res 20 | num /= 7 21 | } 22 | 23 | if negFlag { 24 | return "-" + res 25 | } 26 | 27 | return res 28 | } 29 | 30 | func main() { 31 | 32 | println(convertToBase7(100)) 33 | } 34 | -------------------------------------------------------------------------------- /0515-find-largest-value-in-each-tree-row/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | // TreeNode ... 6 | type TreeNode struct { 7 | Val int 8 | Left *TreeNode 9 | Right *TreeNode 10 | } 11 | 12 | func largestValues(root *TreeNode) []int { 13 | if root == nil { 14 | return []int{} 15 | } 16 | 17 | cur := []*TreeNode{root} 18 | next := []*TreeNode{} 19 | res := []int{} 20 | for { 21 | if len(cur) == 0 { 22 | break 23 | } 24 | max := cur[0].Val 25 | // find biggest of cur 26 | for i := 0; i < len(cur); i++ { 27 | if cur[i].Val > max { 28 | max = cur[i].Val 29 | } 30 | if cur[i].Left != nil { 31 | next = append(next, cur[i].Left) 32 | } 33 | if cur[i].Right != nil { 34 | next = append(next, cur[i].Right) 35 | } 36 | } 37 | res = append(res, max) 38 | cur = append([]*TreeNode{}, next...) 39 | next = next[:0] 40 | } 41 | return res 42 | } 43 | -------------------------------------------------------------------------------- /0540-single-element-in-a-sorted-array/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func singleNonDuplicate(nums []int) int { 6 | fmt.Println(nums) 7 | if len(nums) == 1 { 8 | return nums[0] 9 | } 10 | 11 | if nums[0] < nums[1] { 12 | return nums[0] 13 | } 14 | 15 | if nums[len(nums)-1] > nums[len(nums)-2] { 16 | return nums[len(nums)-1] 17 | } 18 | 19 | // binary search 20 | low, high := 1, len(nums)-2 21 | for low <= high { 22 | mid := low + (high-low)/2 23 | println(low, high, mid) 24 | if nums[mid] != nums[mid-1] && nums[mid] != nums[mid+1] { 25 | return nums[mid] 26 | } 27 | 28 | if mid%2 == 0 { 29 | if nums[mid] == nums[mid-1] { 30 | high = mid - 1 31 | } 32 | 33 | if nums[mid] == nums[mid+1] { 34 | low = mid + 1 35 | } 36 | } else { 37 | if nums[mid] == nums[mid-1] { 38 | low = mid + 1 39 | } 40 | 41 | if nums[mid] == nums[mid+1] { 42 | high = mid - 1 43 | } 44 | } 45 | } 46 | return 0 47 | } 48 | 49 | func main() { 50 | fmt.Println(singleNonDuplicate([]int{3, 3, 7, 7, 10, 11, 11})) 51 | fmt.Println(singleNonDuplicate([]int{1, 1, 2, 3, 3, 4, 4, 8, 8})) 52 | 53 | } 54 | -------------------------------------------------------------------------------- /0551-student-attendance-record-i/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkRecord(s string) bool { 4 | var currentChar byte 5 | var currentCharCnt int 6 | var totalAbsentCnt int 7 | for i := 0; i < len(s); i++ { 8 | if s[i] == currentChar { 9 | currentCharCnt++ 10 | } else { 11 | currentChar = s[i] 12 | currentCharCnt = 1 13 | } 14 | 15 | if currentChar == 'L' && currentCharCnt > 2 { 16 | return false 17 | } 18 | 19 | if currentChar == 'A' { 20 | totalAbsentCnt++ 21 | if totalAbsentCnt > 1 { 22 | return false 23 | } 24 | } 25 | } 26 | return true 27 | } 28 | 29 | func main() { 30 | } 31 | -------------------------------------------------------------------------------- /0556-next-greater-element-iii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "strconv" 7 | ) 8 | 9 | func nextGreaterElement(n int) int { 10 | nStr := []byte(fmt.Sprint(n)) 11 | res := -1 12 | has := false 13 | for i := 1; i < len(nStr); i++ { 14 | if nStr[i] > nStr[i-1] { 15 | has = true 16 | } 17 | } 18 | 19 | if has == false { 20 | return res 21 | } 22 | 23 | for i := len(nStr) - 1; i >= 1; i-- { 24 | if nStr[i] > nStr[i-1] { 25 | // 从 i 开始,向后,找一个最小的,且大于 i-1 元素的 index,交换 26 | minMax, minMaxIdx := nStr[i], i 27 | for j := i; j < len(nStr); j++ { 28 | if nStr[j] < minMax && nStr[j] > nStr[i-1] { 29 | minMax, minMaxIdx = nStr[j], j 30 | } 31 | } 32 | nStr[minMaxIdx], nStr[i-1] = nStr[i-1], nStr[minMaxIdx] 33 | // i 和其之后的都需要再次排序 34 | subSlice := nStr[i:] 35 | sort.Slice(subSlice, func(x, y int) bool { 36 | return subSlice[x] < subSlice[y] 37 | }) 38 | break 39 | } 40 | } 41 | 42 | res64, _ := strconv.ParseInt(string(nStr), 10, 64) 43 | 44 | if res64 > 2147483648 { 45 | return -1 46 | } 47 | 48 | return int(res64) 49 | 50 | } 51 | -------------------------------------------------------------------------------- /0560-subarray-sum-equals-k/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(subarraySum([]int{1, 1, 1}, 2)) 7 | fmt.Println(subarraySum([]int{1}, 0)) 8 | } 9 | 10 | func subarraySum(nums []int, k int) int { 11 | sumMap := map[int]int{0: 1} 12 | sum := 0 13 | res := 0 14 | for i := 0; i < len(nums); i++ { 15 | sum += nums[i] 16 | fmt.Println(sum, k, sumMap) 17 | if sumMap[sum-k] > 0 { 18 | res += sumMap[sum-k] 19 | } 20 | sumMap[sum]++ 21 | } 22 | return res 23 | } 24 | -------------------------------------------------------------------------------- /0575-distribute-candies/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func distributeCandies(candies []int) int { 4 | recMap := map[int]bool{} 5 | typeCnt := 0 6 | for i:=0;i len(candies)/2 { 14 | return len(candies)/2 15 | } 16 | 17 | return typeCnt 18 | } 19 | -------------------------------------------------------------------------------- /0594-longest-harmonious-subsequence/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func findLHS(nums []int) int { 6 | var valMap = map[int]int{} 7 | maxLen := 0 8 | for i := 0; i < len(nums); i++ { 9 | num := nums[i] 10 | valMap[num]++ 11 | if valMap[num+1] == 0 && valMap[num-1] == 0 { 12 | continue 13 | } 14 | 15 | if valMap[num]+valMap[num-1] > maxLen { 16 | maxLen = valMap[num] + valMap[num-1] 17 | } 18 | 19 | if valMap[num]+valMap[num+1] > maxLen { 20 | maxLen = valMap[num] + valMap[num+1] 21 | } 22 | } 23 | return maxLen 24 | } 25 | -------------------------------------------------------------------------------- /0599-minimum-index-sum-of-two-lists/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func findRestaurant(list1 []string, list2 []string) []string { 6 | l1Map := map[string]int{} 7 | l2Map := map[string]int{} 8 | var res []string 9 | for i := 0; i < len(list1); i++ { 10 | l1Map[list1[i]] = i 11 | } 12 | for i := 0; i < len(list2); i++ { 13 | l2Map[list2[i]] = i 14 | } 15 | 16 | var max = len(list1) + len(list2) 17 | for i := 0; i < len(list1); i++ { 18 | l1Str := list1[i] 19 | if _, ok := l2Map[l1Str]; ok { 20 | sum := l2Map[l1Str] + i 21 | if sum < max { 22 | max = sum 23 | res = res[:0] 24 | res = append(res, list1[i]) 25 | continue 26 | } 27 | 28 | if sum == max { 29 | res = append(res, list1[i]) 30 | continue 31 | } 32 | } 33 | } 34 | 35 | return res 36 | 37 | } 38 | 39 | func main() { 40 | fmt.Println(findRestaurant([]string{"Shogun", "Tapioca Express", "Burger King", "KFC"}, []string{"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"})) 41 | } 42 | -------------------------------------------------------------------------------- /0606-construct-string-from-binary-tree/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | tree := &TreeNode{ 7 | Val: 4, 8 | //Left: &TreeNode{Val: 6}, 9 | Right: &TreeNode{Val: 4}, 10 | } 11 | fmt.Println(tree2str(tree)) 12 | } 13 | 14 | // TreeNode ... 15 | type TreeNode struct { 16 | Val int 17 | Left *TreeNode 18 | Right *TreeNode 19 | } 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * type TreeNode struct { 24 | * Val int 25 | * Left *TreeNode 26 | * Right *TreeNode 27 | * } 28 | */ 29 | 30 | func traverse(n *TreeNode) string { 31 | if n == nil { 32 | return "" 33 | } 34 | 35 | if n.Left == nil && n.Right == nil { 36 | return fmt.Sprint(n.Val) 37 | } 38 | 39 | str := fmt.Sprint(n.Val) + "(" + traverse(n.Left) + ")" 40 | if n.Right != nil { 41 | str += "(" + traverse(n.Right) + ")" 42 | } 43 | 44 | return str 45 | } 46 | 47 | func tree2str(t *TreeNode) string { 48 | if t == nil { 49 | return "" 50 | } 51 | 52 | return traverse(t) 53 | } 54 | -------------------------------------------------------------------------------- /0617-merge-two-binary-trees/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | // TreeNode ... 8 | type TreeNode struct { 9 | Val int 10 | Left *TreeNode 11 | Right *TreeNode 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 traverse(n1 *TreeNode, n2 *TreeNode) { 23 | // TODO, fix this? 24 | if n1 == nil || n2 == nil { 25 | return 26 | } 27 | n1.Val += n2.Val 28 | 29 | if n1.Left != nil && n2.Left != nil { 30 | traverse(n1.Left, n2.Left) 31 | } 32 | 33 | /* 34 | if n1.Left == nil && n2.Left == nil { 35 | // do nothing 36 | } 37 | 38 | if n1.Left != nil && n2.Left == nil { 39 | // do nothing 40 | } 41 | */ 42 | 43 | if n1.Left == nil && n2.Left != nil { 44 | n1.Left = n2.Left 45 | n2.Left = nil 46 | } 47 | 48 | if n1.Right != nil && n2.Right != nil { 49 | traverse(n1.Right, n2.Right) 50 | } 51 | 52 | if n1.Right == nil && n2.Right != nil { 53 | n1.Right = n2.Right 54 | n2.Right = nil 55 | } 56 | 57 | /* 58 | if n1.Right != nil && n2.Right == nil { 59 | // do nothing 60 | } 61 | 62 | if n1.Right == nil && n2.Right == nil { 63 | // do nothing 64 | } 65 | */ 66 | } 67 | 68 | func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { 69 | if t1 == nil { 70 | // 让 t1 尽量不是 nil 71 | t1, t2 = t2, t1 72 | } 73 | traverse(t1, t2) 74 | return t1 75 | } 76 | -------------------------------------------------------------------------------- /0653-two-sum-iv-input-is-a-bst/main.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cch123/leetcode-go/4b6504edcdd8b80d202848e6e18596c7e82a48af/0653-two-sum-iv-input-is-a-bst/main.go -------------------------------------------------------------------------------- /0657-judge-route-circle/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func judgeCircle(moves string) bool { 4 | var stepMap = map[byte]int{} 5 | for i:=0;i 1 { 17 | return false 18 | } 19 | 20 | // 如果前面的前面有值 21 | if i-2 >= 0 { 22 | if nums[i-2] <= nums[i] { 23 | // 说明改成 nums[i] 是安全的 24 | nums[i-1] = nums[i] 25 | } else { 26 | // 说明 nums[i-1] > nums[i-2] > nums[i] 27 | // 只能改 nums[i] = nums[i-1] 28 | nums[i] = nums[i-1] 29 | } 30 | continue 31 | } 32 | 33 | // 如果前面的前面没值 34 | if i-2 < 0 { 35 | nums[i-1] = nums[i] 36 | continue 37 | } 38 | } 39 | } 40 | 41 | return true 42 | } 43 | -------------------------------------------------------------------------------- /0674-longest-continuous-increasing-subsequence/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func findLengthOfLCIS(nums []int) int { 6 | if len(nums) <= 1 { 7 | return len(nums) 8 | } 9 | 10 | f := make([]int, len(nums)) 11 | max := 1 12 | for i := 0; i < len(nums); i++ { 13 | if i == 0 || nums[i] <= nums[i-1] { 14 | f[i] = 1 15 | continue 16 | } 17 | 18 | if nums[i] > nums[i-1] { 19 | f[i] = f[i-1] + 1 20 | } 21 | 22 | if f[i] > max { 23 | max = f[i] 24 | } 25 | } 26 | return max 27 | } 28 | -------------------------------------------------------------------------------- /0686-repeated-string-match/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(repeatedStringMatch("abcd", "cdabcdab")) 10 | fmt.Println(repeatedStringMatch("abc", "cabcabca")) 11 | fmt.Println(repeatedStringMatch("abcbc", "cabcbca")) 12 | } 13 | func repeatedStringMatch(A string, B string) int { 14 | startA := A 15 | maxLen := len(B) * 2 16 | if len(A) > len(B) { 17 | maxLen = 2 * len(A) 18 | } 19 | for i := 0; ; i++ { 20 | if strings.Contains(A, B) { 21 | return i + 1 22 | } 23 | if len(A) > maxLen { 24 | break 25 | } 26 | A += startA 27 | } 28 | return -1 29 | } 30 | -------------------------------------------------------------------------------- /0693-binary-number-with-alternating-bits/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func hasAlternatingBits(n int) bool { 4 | first := 1 5 | if n%2 == 0 { 6 | first = 2 7 | } 8 | 9 | for i := first; n > 0; i *= 4 { 10 | n -= i 11 | } 12 | 13 | if n == 0 { 14 | return true 15 | } 16 | 17 | return false 18 | 19 | } 20 | -------------------------------------------------------------------------------- /0700-search-in-a-binary-search-tree/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | // TreeNode ... 8 | type TreeNode struct { 9 | Val int 10 | Left *TreeNode 11 | Right *TreeNode 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 searchBST(root *TreeNode, val int) *TreeNode { 23 | for { 24 | if root == nil { 25 | return nil 26 | } 27 | 28 | if val == root.Val { 29 | return root 30 | } 31 | if val < root.Val { 32 | root = root.Left 33 | continue 34 | } 35 | 36 | if val > root.Val { 37 | root = root.Right 38 | continue 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /0704-binary-search/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func search(nums []int, target int) int { 4 | low, high := 0, len(nums)-1 5 | for low <= high { 6 | mid := low + (high-low)/2 7 | if nums[mid] > target { 8 | high = mid - 1 9 | continue 10 | } 11 | if nums[mid] < target { 12 | low = mid + 1 13 | continue 14 | } 15 | if nums[mid] == target { 16 | return mid 17 | } 18 | } 19 | return -1 20 | } 21 | -------------------------------------------------------------------------------- /0717-1-bit-and-2-bit-characters/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(isOneBitCharacter([]int{1, 0, 0})) 7 | fmt.Println(isOneBitCharacter([]int{1, 1, 1, 0})) 8 | } 9 | 10 | func isOneBitCharacter(bits []int) bool { 11 | if len(bits) == 1 { 12 | return true 13 | } 14 | for i := 0; i < len(bits)-1; { 15 | if bits[i] == 0 { 16 | i++ 17 | if i == len(bits)-1 { 18 | return true 19 | } 20 | continue 21 | } 22 | if bits[i] == 1 && bits[i+1] == 0 { 23 | i += 2 24 | if i == len(bits)-1 { 25 | return true 26 | } 27 | continue 28 | } 29 | if bits[i] == 1 && bits[i+1] == 1 { 30 | i += 2 31 | if i == len(bits)-1 { 32 | return true 33 | } 34 | continue 35 | } 36 | } 37 | return false 38 | } 39 | -------------------------------------------------------------------------------- /0724-find-pivot-index/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type lrSum struct { 6 | LSum int 7 | RSum int 8 | } 9 | 10 | func pivotIndex(nums []int) int { 11 | if len(nums) == 0 { 12 | return -1 13 | } 14 | 15 | sumArr := make([]lrSum, len(nums)) 16 | 17 | rSum := 0 18 | for i := len(nums) - 1; i >= 0; i-- { 19 | rSum += nums[i] 20 | sumArr[i].RSum = rSum 21 | } 22 | 23 | lSum := 0 24 | for i := 0; i < len(nums); i++ { 25 | lSum += nums[i] 26 | sumArr[i].LSum = lSum 27 | } 28 | fmt.Println(sumArr) 29 | 30 | if sumArr[1].RSum == 0 { 31 | return 0 32 | } 33 | 34 | for i := 1; i < len(nums)-1; i++ { 35 | if sumArr[i-1].LSum == sumArr[i+1].RSum { 36 | return i 37 | } 38 | } 39 | 40 | if sumArr[len(sumArr)-2].LSum == 0 { 41 | return len(sumArr) - 1 42 | } 43 | 44 | return -1 45 | } 46 | 47 | func main() { 48 | fmt.Println(pivotIndex([]int{1, 7, 3, 6, 5, 6})) 49 | fmt.Println(pivotIndex([]int{1, 2, 3})) 50 | fmt.Println(pivotIndex([]int{-1, -1, -1, 0, 1, 1})) 51 | fmt.Println(pivotIndex([]int{-1, -1, -1, 1, 1, 1})) 52 | } 53 | -------------------------------------------------------------------------------- /0728-self-dividing-numbers/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func selfDividingNumbers(left int, right int) []int { 6 | res := []int{} 7 | outer: 8 | for i := left; i <= right; i++ { 9 | iStr := fmt.Sprint(i) 10 | for j := 0; j < len(iStr); j++ { 11 | if iStr[j] == '0' { 12 | continue outer 13 | } 14 | 15 | if i%(int(iStr[j])-int('0')) != 0 { 16 | continue outer 17 | } 18 | } 19 | res = append(res, i) 20 | } 21 | return res 22 | } 23 | 24 | func main() { 25 | fmt.Println(selfDividingNumbers(1, 22)) 26 | } 27 | -------------------------------------------------------------------------------- /0744-find-smallest-letter-greater-than-target/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(nextGreatestLetter([]byte{'c', 'f', 'j'}, 'a')) 7 | } 8 | 9 | func nextGreatestLetter(letters []byte, target byte) byte { 10 | // 记录比 target 小的最小 11 | // 记录比 target 大的最小 12 | var minLess, minBigger byte 13 | var minLessSet, minBiggerSet bool 14 | for i := 0; i < len(letters); i++ { 15 | if minLessSet { 16 | if letters[i] <= target && letters[i] <= minLess { 17 | minLess = letters[i] 18 | } 19 | } else { 20 | if letters[i] <= target { 21 | minLess = letters[i] 22 | minLessSet = true 23 | } 24 | } 25 | if minBiggerSet { 26 | if letters[i] > target && letters[i] < minBigger { 27 | minBigger = letters[i] 28 | } 29 | } else { 30 | if letters[i] > target { 31 | minBigger = letters[i] 32 | minBiggerSet = true 33 | } 34 | } 35 | } 36 | fmt.Println(minLessSet, minBiggerSet) 37 | fmt.Println(minLess, minBigger) 38 | if minBiggerSet { 39 | return minBigger 40 | } 41 | return minLess 42 | } 43 | -------------------------------------------------------------------------------- /0747-largest-number-at-least-twice-of-others/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | type nu struct { 8 | num int 9 | idx int 10 | } 11 | 12 | func dominantIndex(nums []int) int { 13 | if len(nums) == 1 { 14 | return 0 15 | } 16 | 17 | if len(nums) == 0 { 18 | return -1 19 | } 20 | 21 | top1, top2 := nu{num: nums[0], idx: 0}, nu{num: nums[1], idx: 1} 22 | if top1.num < top2.num { 23 | top1, top2 = top2, top1 24 | } 25 | 26 | for i := 2; i < len(nums); i++ { 27 | if nums[i] > top1.num { 28 | top2 = top1 29 | top1 = nu{ 30 | num: nums[i], 31 | idx: i, 32 | } 33 | continue 34 | } 35 | if nums[i] > top2.num { 36 | top2 = nu{ 37 | num: nums[i], 38 | idx: i, 39 | } 40 | } 41 | } 42 | 43 | if top1.num >= top2.num*2 { 44 | return top1.idx 45 | } 46 | 47 | return -1 48 | } 49 | -------------------------------------------------------------------------------- /0762-prime-number-of-set-bits-in-binary-representation/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func main() { 6 | } 7 | 8 | func countPrimeSetBits(L int, R int) int { 9 | cnt := 0 10 | for i := L; i <= R; i++ { 11 | bitCnt := countBits(i) 12 | if isPrime(bitCnt) { 13 | cnt++ 14 | } 15 | } 16 | return cnt 17 | } 18 | 19 | func countBits(n int) int { 20 | cnt := 0 21 | for n > 0 { 22 | if n&1 > 0 { 23 | cnt++ 24 | } 25 | n = n >> 1 26 | } 27 | return cnt 28 | } 29 | 30 | func isPrime(n int) bool { 31 | if n < 2 { 32 | return false 33 | } 34 | 35 | for i := 2; i < int(math.Sqrt(float64(n)))+1; i++ { 36 | if n%i == 0 { 37 | return false 38 | } 39 | } 40 | return true 41 | } 42 | -------------------------------------------------------------------------------- /0771-jewels-and-stones/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numJewelsInStones(J string, S string) int { 4 | var diamondMap = map[byte]bool{} 5 | for i := 0; i < len(J); i++ { 6 | diamondMap[J[i]] = true 7 | } 8 | 9 | cnt := 0 10 | for i := 0; i < len(S); i++ { 11 | if diamondMap[S[i]] == true { 12 | cnt++ 13 | } 14 | } 15 | return cnt 16 | } 17 | -------------------------------------------------------------------------------- /0778-swim-in-rising-water/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(swimInWater([][]int{[]int{0, 2}, []int{1, 3}})) 7 | fmt.Println(swimInWater([][]int{[]int{10, 12, 4, 6}, []int{9, 11, 3, 5}, []int{1, 7, 13, 8}, []int{2, 0, 15, 14}})) 8 | } 9 | 10 | type point struct { 11 | x, y int 12 | } 13 | 14 | type r struct { 15 | left, right, down, up bool 16 | } 17 | 18 | func swimInWater(grid [][]int) int { 19 | reached := map[point]bool{ 20 | point{0, 0}: true, 21 | } 22 | traversed := map[point]bool{point{x: 0, y: 0}: true} 23 | res := grid[0][0] 24 | for { 25 | // reached 的所有 adjacent node 26 | // 均需要加入到 reached 27 | curReached := []point{} 28 | for p := range reached { 29 | curReached = append(curReached, p) 30 | } 31 | for { 32 | newReached := []point{} 33 | //fmt.Println(traversed) 34 | for _, p := range curReached { 35 | // 左 36 | leftP := point{x: p.x, y: p.y - 1} 37 | if !traversed[leftP] { 38 | if leftP.y >= 0 && !reached[leftP] && grid[leftP.x][leftP.y] <= res { 39 | newReached = append(newReached, leftP) 40 | traversed[leftP] = true 41 | } 42 | } 43 | // 下 44 | downP := point{x: p.x + 1, y: p.y} 45 | if !traversed[downP] { 46 | if downP.x < len(grid) && !reached[downP] && grid[downP.x][downP.y] <= res { 47 | newReached = append(newReached, downP) 48 | traversed[downP] = true 49 | } 50 | } 51 | // 上 52 | upP := point{x: p.x - 1, y: p.y} 53 | if !traversed[upP] { 54 | if upP.x >= 0 && !reached[upP] && grid[upP.x][upP.y] <= res { 55 | newReached = append(newReached, upP) 56 | traversed[upP] = true 57 | } 58 | } 59 | // 右 60 | rightP := point{x: p.x, y: p.y + 1} 61 | if !traversed[rightP] { 62 | if rightP.y < len(grid[0]) && !reached[rightP] && grid[rightP.x][rightP.y] <= res { 63 | newReached = append(newReached, rightP) 64 | traversed[rightP] = true 65 | } 66 | } 67 | } 68 | if len(newReached) == 0 { 69 | break 70 | } 71 | 72 | // 把 newReached 加到 reach map 73 | // 然后 curReached = newReached 74 | for _, p := range newReached { 75 | reached[p] = true 76 | } 77 | curReached = newReached 78 | } 79 | //fmt.Println(res, reached) 80 | if reached[point{x: len(grid) - 1, y: len(grid) - 1}] == true { 81 | return res 82 | } 83 | res++ 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /0778-swim-in-rising-water/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 在图遍历时,需要注意剪枝(即,在已经遍历过的上下左右,要标记上),否则容易超时 4 | -------------------------------------------------------------------------------- /0783-minimum-distance-between-bst-nodes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // TreeNode ... 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func traverse(node *TreeNode, res *[]int) { 19 | if node == nil { 20 | return 21 | } 22 | 23 | traverse(node.Left, res) 24 | *res = append(*res, node.Val) 25 | traverse(node.Right, res) 26 | } 27 | func minDiffInBST(root *TreeNode) int { 28 | traverseResult := []int{} 29 | traverse(root, &traverseResult) 30 | min := 300 31 | for i := 1; i < len(traverseResult); i++ { 32 | if traverseResult[i]-traverseResult[i-1] < min { 33 | min = traverseResult[i] - traverseResult[i-1] 34 | } 35 | } 36 | return min 37 | } 38 | 39 | func main() { 40 | 41 | } 42 | -------------------------------------------------------------------------------- /0784-letter-case-permutation/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func letterCasePermutation(S string) []string { 9 | if len(S) == 0 { 10 | return []string{S} 11 | } 12 | 13 | if len(S) == 1 { 14 | if S[0] >= '0' && S[0] <= '9' { 15 | return []string{S} 16 | } 17 | 18 | // 说明是字母 19 | return []string{strings.ToLower(S), strings.ToUpper(S)} 20 | } 21 | 22 | subStringResult := letterCasePermutation(S[1:]) 23 | 24 | result := []string{} 25 | var leadingStrings []string 26 | if S[0] >= '0' && S[0] <= '9' { 27 | leadingStrings = []string{S[:1]} 28 | } else { 29 | leadingStrings = []string{ 30 | strings.ToLower(S[:1]), 31 | strings.ToUpper(S[:1]), 32 | } 33 | } 34 | 35 | for i := 0; i < len(leadingStrings); i++ { 36 | for j := 0; j < len(subStringResult); j++ { 37 | result = append(result, leadingStrings[i]+subStringResult[j]) 38 | } 39 | } 40 | 41 | return result 42 | } 43 | 44 | func main() { 45 | fmt.Println(letterCasePermutation("a1b2")) 46 | fmt.Println(letterCasePermutation("12345")) 47 | fmt.Println(letterCasePermutation("3z4")) 48 | } 49 | -------------------------------------------------------------------------------- /0785-is-graph-bipartite/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(isBipartite([][]int{[]int{1, 3}, []int{0, 2}, []int{1, 3}, []int{0, 2}})) 7 | fmt.Println(isBipartite([][]int{[]int{1, 2, 3}, []int{0, 2}, []int{0, 1, 3}, []int{0, 2}})) 8 | fmt.Println(isBipartite([][]int{[]int{}, 9 | []int{2, 4, 6}, []int{1, 4, 8, 9}, 10 | []int{7, 8}, []int{1, 2, 8, 9}, 11 | []int{6, 9}, []int{1, 5, 7, 8, 9}, 12 | []int{3, 6, 9}, []int{2, 3, 4, 6, 9}, 13 | []int{2, 4, 5, 6, 7, 8}, 14 | })) 15 | } 16 | 17 | func isBipartite(graph [][]int) bool { 18 | bigraphLeft := map[int]bool{} 19 | bigraphRight := map[int]bool{} 20 | traversed := map[int]bool{} 21 | var useLeft bool 22 | for i := 0; i < len(graph); i++ { 23 | if traversed[i] == true { 24 | continue 25 | } 26 | // bfs this node and the connected dots 27 | useLeft, bigraphLeft[i] = false, true 28 | current := []int{i} 29 | for { 30 | next := []int{} 31 | allTraversed := true 32 | for j := 0; j < len(current); j++ { 33 | // connected to current[j] 34 | // traversed 表示该节点的子节点是否被访问过了 35 | if traversed[current[j]] != true { 36 | next = append(next, graph[current[j]]...) 37 | traversed[current[j]] = true 38 | allTraversed = false 39 | } 40 | } 41 | 42 | for j := 0; j < len(next); j++ { 43 | if useLeft { 44 | bigraphLeft[next[j]] = true 45 | } else { 46 | bigraphRight[next[j]] = true 47 | } 48 | 49 | if bigraphLeft[next[j]] == true && bigraphRight[next[j]] == true { 50 | //println(next[j]) 51 | return false 52 | } 53 | } 54 | useLeft = !useLeft 55 | 56 | // 该连通分量已全部遍历到 57 | if allTraversed { 58 | break 59 | } 60 | 61 | current = next 62 | //fmt.Println(bigraphLeft, bigraphRight) 63 | } 64 | } 65 | return true 66 | } 67 | -------------------------------------------------------------------------------- /0788-rotated-digits/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var arr1 = map[int]bool{ 6 | 0: true, 7 | 1: true, 8 | 8: true, 9 | 2: true, 10 | 5: true, 11 | 6: true, 12 | 9: true, 13 | } 14 | 15 | var arr2 = map[int]bool{ 16 | 0: true, 17 | 1: true, 18 | 8: true, 19 | } 20 | 21 | func isSubSet(arr []int, t map[int]bool) bool { 22 | res := true 23 | for _, num := range arr { 24 | if t[num] == false { 25 | res = false 26 | break 27 | } 28 | } 29 | return res 30 | } 31 | 32 | func splitToInts(N int) []int { 33 | nStr := fmt.Sprint(N) 34 | res := []int{} 35 | for _, c := range nStr { 36 | res = append(res, int(c)-int('0')) 37 | } 38 | return res 39 | } 40 | 41 | func isGood(N int) bool { 42 | nums := splitToInts(N) 43 | //fmt.Println(nums) 44 | if isSubSet(nums, arr1) && !isSubSet(nums, arr2) { 45 | return true 46 | } 47 | 48 | return false 49 | } 50 | 51 | func rotatedDigits(N int) int { 52 | cnt := 0 53 | for i := 1; i <= N; i++ { 54 | if isGood(i) { 55 | cnt++ 56 | } 57 | } 58 | return cnt 59 | } 60 | 61 | func main() { 62 | fmt.Println(rotatedDigits(10)) 63 | } 64 | -------------------------------------------------------------------------------- /0791-custom-sort-string/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(customSortString("kqep", "pekeq")) 10 | } 11 | func customSortString(S string, T string) string { 12 | var byteMap = map[byte]int{} 13 | for i := 0; i < len(S); i++ { 14 | byteMap[S[i]] = i 15 | } 16 | 17 | tBytes := []byte(T) 18 | 19 | sort.Slice(tBytes, func(x, y int) bool { 20 | c1, c2 := tBytes[x], tBytes[y] 21 | return byteMap[c1] < byteMap[c2] 22 | }) 23 | 24 | return string(tBytes) 25 | } 26 | -------------------------------------------------------------------------------- /0796-rotate-string/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(rotateString("abcde", "cdeab")) 7 | fmt.Println(rotateString("abcde", "abced")) 8 | } 9 | 10 | func rotateString(A string, B string) bool { 11 | if len(A) != len(B) { 12 | return false 13 | } 14 | 15 | if (len(A) == 1 || len(A) == 0) && A != B { 16 | return false 17 | } 18 | 19 | for i := 0; i < len(A); i++ { 20 | A = A[1:] + A[:1] 21 | if A == B { 22 | return true 23 | } 24 | } 25 | 26 | return false 27 | } 28 | -------------------------------------------------------------------------------- /0797-all-paths-from-source-to-target/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(allPathsSourceTarget([][]int{[]int{1, 2}, []int{3}, []int{3}, []int{}})) 7 | } 8 | 9 | func traverse(elem, target int, parentPath []int, 10 | traversed map[int]bool, res *[][]int, graph [][]int) { 11 | 12 | currentPath := append([]int{}, parentPath...) 13 | currentPath = append(currentPath, elem) 14 | 15 | if elem == target { 16 | resultPathElem := append([]int{}, currentPath...) 17 | *res = append(*res, resultPathElem) 18 | } 19 | 20 | children := graph[elem] 21 | for i := 0; i < len(children); i++ { 22 | traverse(children[i], target, currentPath, traversed, res, graph) 23 | } 24 | } 25 | 26 | func allPathsSourceTarget(graph [][]int) [][]int { 27 | if len(graph) == 0 { 28 | return [][]int{} 29 | } 30 | 31 | var res = [][]int{} 32 | target := len(graph) - 1 33 | traversed := map[int]bool{} 34 | traverse(0, target, []int{}, traversed, &res, graph) 35 | 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /0811-subdomain-visit-count/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | ) 8 | 9 | // ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"] 10 | func subdomainVisits(cpdomains []string) []string { 11 | resultMap := map[string]int64{} 12 | for i := 0; i < len(cpdomains); i++ { 13 | numDomain := strings.Split(cpdomains[i], " ") 14 | num, _ := strconv.ParseInt(numDomain[0], 10, 64) 15 | resultMap[numDomain[1]] += num 16 | 17 | // 逆方向遍历 cpdomains[i] 字符串,一旦在第 i 个位置遇到了 . 18 | // 那么就对 str[i+1:] 进行计数 19 | for j := len(cpdomains[i]) - 1; j >= 0; j-- { 20 | if cpdomains[i][j] == '.' { 21 | subdomain := cpdomains[i][j+1:] 22 | resultMap[subdomain] += num 23 | } 24 | } 25 | } 26 | 27 | res := []string{} 28 | for k, v := range resultMap { 29 | str := fmt.Sprint(v) + " " + k 30 | res = append(res, str) 31 | } 32 | return res 33 | } 34 | -------------------------------------------------------------------------------- /0819-most-common-word/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(mostCommonWord("Bob. hIt, baLl", []string{"bob", "hit"})) 10 | } 11 | 12 | func mostCommonWord(paragraph string, banned []string) string { 13 | paraBytes := bytes.ToLower([]byte(paragraph)) 14 | cur := []byte{} 15 | str2Cnt := map[string]int{} 16 | bannedMap := map[string]bool{} 17 | for i := 0; i < len(banned); i++ { 18 | bannedMap[banned[i]] = true 19 | } 20 | max, res := 0, "" 21 | 22 | for i := 0; i < len(paraBytes); i++ { 23 | if paraBytes[i] > 'z' || paraBytes[i] < 'a' { 24 | if len(cur) == 0 { 25 | continue 26 | } 27 | str2Cnt[string(cur)]++ 28 | if str2Cnt[string(cur)] > max && bannedMap[string(cur)] == false { 29 | max = str2Cnt[string(cur)] 30 | res = string(cur) 31 | } 32 | cur = cur[:0] 33 | } else if i == len(paraBytes)-1 && len(cur) > 0 { 34 | cur = append(cur, paraBytes[i]) 35 | str2Cnt[string(cur)]++ 36 | if str2Cnt[string(cur)] > max && bannedMap[string(cur)] == false { 37 | max = str2Cnt[string(cur)] 38 | res = string(cur) 39 | } 40 | } else { 41 | cur = append(cur, paraBytes[i]) 42 | } 43 | } 44 | fmt.Println(str2Cnt) 45 | return res 46 | } 47 | -------------------------------------------------------------------------------- /0821-shortest-distance-to-a-character/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func shortestToChar(S string, C byte) []int { 6 | res := make([]int, len(S)) 7 | for i := 0; i < len(S); i++ { 8 | if S[i] == C { 9 | res[i] = 0 10 | continue 11 | } 12 | // left 13 | leftDis := len(S) + 1 14 | rightDis := len(S) + 1 15 | for j := i - 1; j >= 0; j-- { 16 | if S[j] == C { 17 | leftDis = i - j 18 | break 19 | } 20 | } 21 | // right 22 | for j := i + 1; j < len(S); j++ { 23 | if S[j] == C { 24 | rightDis = j - i 25 | break 26 | } 27 | } 28 | if leftDis < rightDis { 29 | res[i] = leftDis 30 | } else { 31 | res[i] = rightDis 32 | } 33 | } 34 | return res 35 | } 36 | -------------------------------------------------------------------------------- /0829-consecutive-numbers-sum/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkValid(N int, part int) (bool, int) { 4 | avg := N / part 5 | var first int 6 | if part%2 == 0 { 7 | first = avg - (part/2 - 1) 8 | } else { 9 | first = avg - part/2 10 | } 11 | 12 | if first <= 0 { 13 | return false, first 14 | } 15 | 16 | last := first + part - 1 17 | sum := (first + last) * part / 2 18 | if sum == N { 19 | return true, first 20 | } 21 | return false, first 22 | } 23 | 24 | func consecutiveNumbersSum(N int) int { 25 | sum := 0 26 | for i := 1; i <= N; i++ { 27 | valid, first := checkValid(N, i) 28 | if valid { 29 | sum++ 30 | } 31 | if first <= 0 { 32 | break 33 | } 34 | } 35 | return sum 36 | } 37 | -------------------------------------------------------------------------------- /0829-consecutive-numbers-sum/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type TestCase struct { 11 | N int 12 | expected int 13 | } 14 | 15 | func TestConsecutiveNumbersSum(t *testing.T) { 16 | cases := []TestCase{ 17 | TestCase{N: 1, expected: 1}, 18 | TestCase{N: 2, expected: 1}, 19 | TestCase{N: 3, expected: 2}, 20 | TestCase{N: 5, expected: 2}, 21 | TestCase{N: 9, expected: 3}, 22 | TestCase{N: 15, expected: 4}, 23 | } 24 | 25 | for _, cas := range cases { 26 | res := consecutiveNumbersSum(cas.N) 27 | assert.Equal(t, cas.expected, res, "input: "+fmt.Sprint(cas.N)) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /0829-consecutive-numbers-sum/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/consecutive-numbers-sum/description/ 4 | 5 | # desc 6 | 7 | 给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N? 8 | 9 | 示例 1: 10 | 11 | ``` 12 | 输入: 5 13 | 输出: 2 14 | 解释: 5 = 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。 15 | ``` 16 | 17 | 示例 2: 18 | 19 | ``` 20 | 输入: 9 21 | 输出: 3 22 | 解释: 9 = 9 = 4 + 5 = 2 + 3 + 4 23 | ``` 24 | 25 | 示例 3: 26 | 27 | ``` 28 | 输入: 15 29 | 输出: 4 30 | 解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 31 | ``` 32 | 33 | 说明: 1 <= N <= 10 ^ 9 -------------------------------------------------------------------------------- /0830-positions-of-large-groups/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | } 5 | 6 | func largeGroupPositions(S string) [][]int { 7 | res := [][]int{} 8 | start := 0 9 | for i := 1; i < len(S); i++ { 10 | if S[i] != S[i-1] { 11 | end := i - 1 12 | if end-start+1 >= 3 { 13 | res = append(res, []int{start, end}) 14 | } 15 | start = i 16 | } 17 | 18 | // final group 19 | if i == len(S)-1 && i-start+1 >= 3 { 20 | res = append(res, []int{start, i}) 21 | } 22 | } 23 | return res 24 | } 25 | -------------------------------------------------------------------------------- /0832-flipping-an-image/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func flipAndInvertImage(A [][]int) [][]int { 4 | for i := 0; i < len(A); i++ { 5 | mid := (len(A[i]) + 1) / 2 6 | for j := 0; j < mid; j++ { 7 | k := len(A[i]) - 1 - j 8 | A[i][j], A[i][k] = 1-A[i][k], 1-A[i][j] 9 | } 10 | 11 | } 12 | 13 | return A 14 | } 15 | -------------------------------------------------------------------------------- /0832-flipping-an-image/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | A [][]int 11 | expected [][]int 12 | } 13 | 14 | func TestFlipAndInvertImage(t *testing.T) { 15 | cases := []TestCase{ 16 | TestCase{ 17 | A: [][]int{[]int{1, 1, 0}, []int{1, 0, 1}, []int{0, 0, 0}}, 18 | expected: [][]int{[]int{1, 0, 0}, []int{0, 1, 0}, []int{1, 1, 1}}, 19 | }, 20 | TestCase{ 21 | A: [][]int{[]int{1, 1, 0, 0}, []int{1, 0, 0, 1}, []int{0, 1, 1, 1}, []int{1, 0, 1, 0}}, 22 | expected: [][]int{[]int{1, 1, 0, 0}, []int{0, 1, 1, 0}, []int{0, 0, 0, 1}, []int{1, 0, 1, 0}}, 23 | }, 24 | } 25 | 26 | for _, cas := range cases { 27 | res := flipAndInvertImage(cas.A) 28 | assert.Equal(t, cas.expected, res) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0832-flipping-an-image/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/flipping-an-image/description/ 4 | 5 | # desc 6 | 7 | 给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。 8 | 9 | 水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。 10 | 11 | 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。 12 | 13 | 示例 1: 14 | 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 | ``` 21 | 22 | 示例 2: 23 | 24 | ``` 25 | 输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 26 | 输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 27 | 解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]; 28 | 然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 29 | ``` 30 | 31 | 说明: 32 | 33 | 1 <= A.length = A[0].length <= 20 34 | 35 | 0 <= A[i][j] <= 1 36 | -------------------------------------------------------------------------------- /0836-rectangle-overlap/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | } 5 | func isRectangleOverlap(rec1 []int, rec2 []int) bool { 6 | // 在 x 轴上的投影没有重合,或者在 y 轴上的投影没有重合,即认为两个矩形不相交 7 | if rec1[0] >= rec2[2] || rec2[0] >= rec1[2] { 8 | return false 9 | } 10 | if rec1[1] >= rec2[3] || rec2[1] >= rec1[3] { 11 | return false 12 | } 13 | return true 14 | } 15 | -------------------------------------------------------------------------------- /0841-keys-and-rooms/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //fmt.Println(canVisitAllRooms([][]int{[]int{1}, []int{2}, []int{3}, []int{}})) 7 | //fmt.Println(canVisitAllRooms([][]int{[]int{1, 3, 2}, []int{2, 3}, []int{2, 1, 3, 1}, []int{}})) 8 | fmt.Println(canVisitAllRooms([][]int{[]int{1}, []int{}, []int{0, 3}, []int{1}})) 9 | } 10 | 11 | func canVisitAllRooms(rooms [][]int) bool { 12 | //for i := 0; i < len(rooms); i++ { 13 | // start from rooms[i] 14 | visited := map[int]bool{0: true} 15 | nextVisit := rooms[0] 16 | for { 17 | newToVisit := []int{} 18 | for j := 0; j < len(nextVisit); j++ { 19 | if visited[nextVisit[j]] == true { 20 | continue 21 | } 22 | visited[nextVisit[j]] = true 23 | newToVisit = append(newToVisit, rooms[nextVisit[j]]...) 24 | } 25 | if len(newToVisit) == 0 { 26 | break 27 | } 28 | nextVisit = newToVisit 29 | //fmt.Println(nextVisit) 30 | } 31 | 32 | // check all 33 | if len(visited) == len(rooms) { 34 | //fmt.Println(visited, i) 35 | return true 36 | } 37 | //} 38 | return false 39 | } 40 | -------------------------------------------------------------------------------- /0844-backspace-string-compare/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func backspaceCompare(S string, T string) bool { 4 | sResultBytes := []byte{} 5 | tResultBytes := []byte{} 6 | for i := 0; i < len(S); i++ { 7 | if S[i] != '#' { 8 | sResultBytes = append(sResultBytes, S[i]) 9 | continue 10 | } 11 | if len(sResultBytes) > 0 { 12 | sResultBytes = sResultBytes[:len(sResultBytes)-1] 13 | } 14 | } 15 | for i := 0; i < len(T); i++ { 16 | if T[i] != '#' { 17 | tResultBytes = append(tResultBytes, T[i]) 18 | continue 19 | } 20 | if len(tResultBytes) > 0 { 21 | tResultBytes = tResultBytes[:len(tResultBytes)-1] 22 | } 23 | } 24 | 25 | return string(sResultBytes) == string(tResultBytes) 26 | } 27 | 28 | func main() { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /0845-longest-mountain-in-array/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | type direction int 6 | 7 | const ( 8 | up direction = iota 9 | down 10 | unavail 11 | ) 12 | 13 | func longestMountain(A []int) int { 14 | flag := unavail 15 | mountainLen := 0 16 | maxMountainLen := 0 17 | for i := 0; i < len(A)-1; i++ { 18 | switch flag { 19 | case unavail: 20 | if A[i+1] <= A[i] { 21 | // do nothing 22 | } 23 | if A[i+1] > A[i] { 24 | flag = up 25 | mountainLen++ 26 | } 27 | case up: 28 | if A[i+1] < A[i] { 29 | flag = down 30 | mountainLen++ 31 | } 32 | if A[i+1] > A[i] { 33 | mountainLen++ 34 | } 35 | if A[i+1] == A[i] { 36 | mountainLen = 0 37 | flag = unavail 38 | } 39 | case down: 40 | if A[i+1] < A[i] { 41 | mountainLen++ 42 | } 43 | if A[i+1] > A[i] { 44 | flag = up 45 | mountainLen++ 46 | if maxMountainLen < mountainLen { 47 | maxMountainLen = mountainLen 48 | } 49 | mountainLen = 1 50 | } 51 | if A[i+1] == A[i] { 52 | flag = unavail 53 | mountainLen++ 54 | if maxMountainLen < mountainLen { 55 | maxMountainLen = mountainLen 56 | } 57 | mountainLen = 0 58 | } 59 | } 60 | } 61 | if flag == down && A[len(A)-1] < A[len(A)-2] { 62 | mountainLen++ 63 | if mountainLen > maxMountainLen { 64 | maxMountainLen = mountainLen 65 | } 66 | } 67 | return maxMountainLen 68 | } 69 | -------------------------------------------------------------------------------- /0849-maximize-distance-to-closest-person/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(maxDistToClosest([]int{1, 0, 0, 0})) 7 | } 8 | 9 | func maxDistToClosest(seats []int) int { 10 | f := make([]int, len(seats)) 11 | for i := 0; i < len(f); i++ { 12 | f[i] = len(seats) + 10 13 | } 14 | for i := 0; i < len(seats); i++ { 15 | if seats[i] == 0 { 16 | continue 17 | } 18 | f[i] = 0 19 | 20 | // seats[i] == 0 21 | // 向左 22 | for j := i - 1; j >= 0; j-- { 23 | if seats[j] == 1 { 24 | break 25 | } 26 | if f[j] > i-j { 27 | f[j] = i - j 28 | } else { 29 | break 30 | } 31 | } 32 | // 向右 33 | for j := i + 1; j < len(seats); j++ { 34 | if seats[j] == 1 { 35 | i = j - 1 36 | break 37 | } 38 | f[j] = j - i 39 | } 40 | } 41 | max := 0 42 | for i := 0; i < len(f); i++ { 43 | if f[i] > max { 44 | max = f[i] 45 | } 46 | } 47 | return max 48 | } 49 | -------------------------------------------------------------------------------- /0852-peak-index-in-a-mountain-array/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // binary 6 | func peakIndexInMountainArray(A []int) int { 7 | low, high := 1, len(A)-2 8 | for low <= high { 9 | mid := low + (high-low)/2 10 | if A[mid] > A[mid-1] && A[mid] > A[mid+1] { 11 | return mid 12 | } 13 | 14 | if A[mid] > A[mid-1] && A[mid] < A[mid+1] { 15 | low = mid + 1 16 | continue 17 | } 18 | 19 | if A[mid] < A[mid-1] && A[mid] > A[mid+1] { 20 | high = mid - 1 21 | continue 22 | } 23 | } 24 | return 0 25 | } 26 | 27 | func main() { 28 | fmt.Println(peakIndexInMountainArray([]int{1, 2, 3, 1})) 29 | } 30 | -------------------------------------------------------------------------------- /0856-score-of-parentheses/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type stack struct { 4 | arr []int 5 | } 6 | 7 | func (s *stack) push(elem int) { 8 | s.arr = append(s.arr, elem) 9 | } 10 | 11 | func (s *stack) pop() { 12 | s.arr = s.arr[:len(s.arr)-1] 13 | } 14 | 15 | func (s *stack) top() int { 16 | return s.arr[len(s.arr)-1] 17 | } 18 | 19 | func (s *stack) findTopMostLeftParen() int { 20 | for i := len(s.arr) - 1; i >= 0; i-- { 21 | if s.arr[i] == int('(') { 22 | return i 23 | } 24 | } 25 | return -1 26 | } 27 | 28 | func scoreOfParentheses(S string) int { 29 | st := stack{arr: make([]int, 0)} 30 | for _, b := range S { 31 | if b == '(' { 32 | st.push(int(b)) 33 | } 34 | 35 | if b == ')' { 36 | if st.top() == int('(') { 37 | st.pop() 38 | st.push(1) 39 | } else { 40 | // 一直找到匹配的括号 41 | idx := st.findTopMostLeftParen() 42 | sum := 0 43 | for i := idx + 1; i < len(st.arr); i++ { 44 | sum += st.arr[i] 45 | } 46 | sum *= 2 47 | 48 | for st.top() != int('(') { 49 | st.pop() 50 | } 51 | // pop the '(' 52 | st.pop() 53 | st.push(sum) 54 | } 55 | } 56 | } 57 | 58 | res := 0 59 | for _, n := range st.arr { 60 | res += n 61 | } 62 | 63 | return res 64 | } 65 | -------------------------------------------------------------------------------- /0856-score-of-parentheses/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type TestCase struct { 11 | S string 12 | expected int 13 | } 14 | 15 | func TestScoreOfParentheses(t *testing.T) { 16 | cases := []TestCase{ 17 | TestCase{S: "(())", expected: 2}, 18 | TestCase{S: "(()(()))", expected: 6}, 19 | TestCase{S: "()", expected: 1}, 20 | TestCase{S: "()()", expected: 2}, 21 | } 22 | 23 | for _, cas := range cases { 24 | res := scoreOfParentheses(cas.S) 25 | assert.Equal(t, cas.expected, res, "input: "+fmt.Sprint(cas.S)) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /0856-score-of-parentheses/readme.md: -------------------------------------------------------------------------------- 1 | # solution 2 | 3 | 当前为 ( 时,入栈 4 | 5 | 当前为 ) 时,看栈顶是否为 (,是的话推 1 进栈 6 | 7 | 否则为乘法模式,向栈底方向找最近的 (,并把中间的所有数字加起来,然后 *2,再把这段数字和符号弹出,再推进刚刚算完的结果 8 | 9 | 符号过完之后,把栈中所有的数字加起来,就是结果了 10 | -------------------------------------------------------------------------------- /0859-buddy-strings/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func buddyStrings(A string, B string) bool { 6 | if len(A) != len(B) { 7 | return false 8 | } 9 | 10 | diffPos := []int{} 11 | byteCnt := map[byte]int{} 12 | 13 | canSwapToTheSameFlag := false 14 | 15 | for i := 0; i < len(A); i++ { 16 | if A[i] != B[i] { 17 | diffPos = append(diffPos, i) 18 | } 19 | byteCnt[A[i]]++ 20 | if byteCnt[A[i]] == 2 { 21 | canSwapToTheSameFlag = true 22 | } 23 | } 24 | 25 | if len(diffPos) == 0 && canSwapToTheSameFlag { 26 | return true 27 | } 28 | 29 | if len(diffPos) != 2 { 30 | return false 31 | } 32 | 33 | x, y := diffPos[0], diffPos[1] 34 | if A[x] == B[y] && A[y] == B[x] { 35 | return true 36 | } 37 | 38 | return false 39 | } 40 | -------------------------------------------------------------------------------- /0860-lemonade-change/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | 7 | func lemonadeChange(bills []int) bool { 8 | var valMap = map[int]int{} 9 | for i := 0; i < len(bills); i++ { 10 | if bills[i] == 5 { 11 | valMap[5]++ 12 | } 13 | if bills[i] == 10 { 14 | if valMap[5] == 0 { 15 | return false 16 | } 17 | valMap[5]-- 18 | valMap[10]++ 19 | } 20 | if bills[i] == 20 { 21 | if valMap[10] > 0 && valMap[5] > 0 { 22 | valMap[10]-- 23 | valMap[5]-- 24 | continue 25 | } 26 | if valMap[5] > 3 { 27 | valMap[5] = valMap[5] - 3 28 | continue 29 | } 30 | return false 31 | } 32 | } 33 | 34 | return true 35 | } 36 | -------------------------------------------------------------------------------- /0865-smallest-subtree-with-all-the-deepest-nodes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | tree := &TreeNode{ 5 | Val: 1, 6 | Left: &TreeNode{ 7 | Val: 2, 8 | }, 9 | Right: &TreeNode{ 10 | Val: 3, 11 | }, 12 | } 13 | subtreeWithAllDeepest(tree) 14 | } 15 | 16 | // TreeNode ... 17 | type TreeNode struct { 18 | Val int 19 | Left *TreeNode 20 | Right *TreeNode 21 | } 22 | 23 | func traverse(n *TreeNode, parentPath []*TreeNode, leafMaxLen *int, leafNodeToPath map[*TreeNode][]*TreeNode) { 24 | if n == nil { 25 | return 26 | } 27 | 28 | currentPath := append([]*TreeNode{}, parentPath...) 29 | currentPath = append(currentPath, n) 30 | if n.Left == nil && n.Right == nil { 31 | currentLen := len(parentPath) + 1 32 | leafNodeToPath[n] = currentPath 33 | if currentLen > *leafMaxLen { 34 | *leafMaxLen = currentLen 35 | } 36 | return 37 | } 38 | traverse(n.Left, currentPath, leafMaxLen, leafNodeToPath) 39 | traverse(n.Right, currentPath, leafMaxLen, leafNodeToPath) 40 | } 41 | 42 | /** 43 | * Definition for a binary tree node. 44 | * type TreeNode struct { 45 | * Val int 46 | * Left *TreeNode 47 | * Right *TreeNode 48 | * } 49 | */ 50 | func subtreeWithAllDeepest(root *TreeNode) *TreeNode { 51 | var leafNodeToPath = map[*TreeNode][]*TreeNode{} 52 | var leafMaxLen int 53 | traverse(root, []*TreeNode{}, &leafMaxLen, leafNodeToPath) 54 | 55 | previousPath := []*TreeNode{} 56 | //fmt.Println(leafNodeToPath) 57 | 58 | for _, path := range leafNodeToPath { 59 | if len(path) == leafMaxLen { 60 | if len(previousPath) == 0 { 61 | previousPath = path 62 | continue 63 | } 64 | // previousPath 和 path 的交集 65 | newPath := []*TreeNode{} 66 | x, y := 0, 0 67 | for x < len(previousPath) && y < len(path) && previousPath[x] == path[y] { 68 | newPath = append(newPath, previousPath[x]) 69 | x++ 70 | y++ 71 | } 72 | previousPath = newPath 73 | } 74 | } 75 | //fmt.Println(previousPath) 76 | return previousPath[len(previousPath)-1] 77 | } 78 | -------------------------------------------------------------------------------- /0867-transpose-matrix/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func transpose(A [][]int) [][]int { 4 | if len(A) == 0 { 5 | return A 6 | } 7 | x := len(A) 8 | y := len(A[0]) 9 | resultMatrix := make([][]int, y) 10 | for i := 0; i < len(resultMatrix); i++ { 11 | resultMatrix[i] = make([]int, x) 12 | } 13 | 14 | for i := 0; i < x; i++ { 15 | for j := 0; j < y; j++ { 16 | resultMatrix[j][i] = A[i][j] 17 | } 18 | } 19 | return resultMatrix 20 | } 21 | -------------------------------------------------------------------------------- /0868-binary-gap/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func binaryGap(N int) int { 8 | nBinaryStr := strconv.FormatInt(int64(N), 2) 9 | maxGap := 0 10 | currentGap := 0 11 | for i := 1; i < len(nBinaryStr); i++ { 12 | currentGap++ 13 | if nBinaryStr[i] == '0' { 14 | continue 15 | } 16 | 17 | if nBinaryStr[i] == '1' { 18 | if currentGap > maxGap { 19 | maxGap = currentGap 20 | } 21 | currentGap = 0 22 | } 23 | } 24 | 25 | return maxGap 26 | } 27 | 28 | func main() { 29 | println(binaryGap(22)) 30 | println(binaryGap(5)) 31 | println(binaryGap(6)) 32 | } 33 | -------------------------------------------------------------------------------- /0872-leaf-similar-trees/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 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 | var tree1LeafArr = []int{} 18 | var tree2LeafArr = []int{} 19 | 20 | func preTraversal(node *TreeNode, which int) { 21 | if node == nil { 22 | return 23 | } 24 | preTraversal(node.Left, which) 25 | preTraversal(node.Right, which) 26 | 27 | // is leaf 28 | if node.Left == nil && node.Right == nil { 29 | if which == 1 { 30 | tree1LeafArr = append(tree1LeafArr, node.Val) 31 | } else { 32 | tree2LeafArr = append(tree2LeafArr, node.Val) 33 | } 34 | } 35 | 36 | } 37 | 38 | func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { 39 | tree1LeafArr = tree1LeafArr[:0] 40 | tree1LeafArr = tree1LeafArr[:0] 41 | preTraversal(root1, 1) 42 | preTraversal(root2, 2) 43 | if len(tree1LeafArr) != len(tree2LeafArr) { 44 | return false 45 | } 46 | 47 | for i := 0; i < len(tree1LeafArr); i++ { 48 | if tree1LeafArr[i] != tree2LeafArr[i] { 49 | return false 50 | } 51 | } 52 | return true 53 | } 54 | -------------------------------------------------------------------------------- /0872-leaf-similar-trees/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | -------------------------------------------------------------------------------- /0872-leaf-similar-trees/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/leaf-similar-trees/description/ 4 | 5 | # desc 6 | 7 | 考虑一个二叉树的所有叶子。这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。 8 | 9 | ![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png) 10 | 11 | 举个例子,给定一个如上图所示的树,其叶值序列为 (6, 7, 4, 9, 8) 。 12 | 13 | 如果两个二叉树的叶值序列相同,我们就认为它们是 叶相似的。 14 | 15 | 如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,返回 true;否则返回 false 。 16 | 17 | 18 | 提示: 19 | 20 | 给定的两个树会有 1 到 100 个结点。 -------------------------------------------------------------------------------- /0873-length-of-longest-fibonacci-subsequence/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func lenLongestFibSubseq(A []int) int { 4 | if len(A) < 3 { 5 | return 0 6 | } 7 | 8 | var indexMap = map[int]int{} 9 | for i := 0; i < len(A); i++ { 10 | indexMap[A[i]] = i 11 | } 12 | 13 | var maxLen = 2 14 | 15 | for i := 0; i < len(A); i++ { 16 | for j := i + 1; j < len(A); j++ { 17 | currentLen := 2 18 | i, j := i, j 19 | for { 20 | sum := A[i] + A[j] 21 | if indexMap[sum] > j { 22 | currentLen++ 23 | if currentLen > maxLen { 24 | maxLen = currentLen 25 | } 26 | i = j 27 | j = indexMap[sum] 28 | } else { 29 | break 30 | } 31 | } 32 | } 33 | } 34 | 35 | if maxLen == 2 { 36 | return 0 37 | } 38 | return maxLen 39 | } 40 | -------------------------------------------------------------------------------- /0873-length-of-longest-fibonacci-subsequence/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type TestCase struct { 11 | nums []int 12 | expected int 13 | } 14 | 15 | func TestLenLongestFibSubseq(t *testing.T) { 16 | cases := []TestCase{ 17 | TestCase{nums: []int{1, 2, 3, 4, 5, 6, 7, 8}, expected: 5}, 18 | TestCase{nums: []int{1, 3, 7, 11, 12, 14, 18}, expected: 3}, 19 | } 20 | 21 | for _, cas := range cases { 22 | res := lenLongestFibSubseq(cas.nums) 23 | assert.Equal(t, cas.expected, res, "input: "+fmt.Sprint(cas.nums)) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0873-length-of-longest-fibonacci-subsequence/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence/description/ 4 | 5 | # desc 6 | 7 | 如果序列 X_1, X_2, ..., X_n 满足下列条件,就说它是 斐波那契式 的: 8 | 9 | n >= 3 10 | 对于所有 i + 2 <= n,都有 X_i + X_{i+1} = X_{i+2} 11 | 给定一个严格递增的正整数数组形成序列,找到 A 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。 12 | 13 | (回想一下,子序列是从原序列 A 中派生出来的,它从 A 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8] 是 [3, 4, 5, 6, 7, 8] 的一个子序列) 14 | 15 | 16 | 17 | 示例 1: 18 | 19 | ``` 20 | 输入: [1,2,3,4,5,6,7,8] 21 | 输出: 5 22 | 解释: 23 | 最长的斐波那契式子序列为:[1,2,3,5,8] 。 24 | ``` 25 | 26 | 示例 2: 27 | 28 | ``` 29 | 输入: [1,3,7,11,12,14,18] 30 | 输出: 3 31 | 解释: 32 | 最长的斐波那契式子序列有: 33 | [1,11,12],[3,11,14] 以及 [7,11,18] 。 34 | ``` 35 | 36 | 提示: 37 | 38 | 3 <= A.length <= 1000 39 | 1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9 40 | (对于以 Java,C,C++,以及 C# 的提交,时间限制被减少了 50%) -------------------------------------------------------------------------------- /0875-koko-eating-bananas/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func sumAndMax(nums []int) (int, int) { 4 | var sum, max = 0, 0 5 | for _, num := range nums { 6 | sum += num 7 | if num > max { 8 | max = num 9 | } 10 | } 11 | return sum, max 12 | } 13 | 14 | func calcTimes(piles []int, K int) int { 15 | times := 0 16 | for _, pile := range piles { 17 | if pile%K == 0 { 18 | times += pile / K 19 | } else { 20 | times += pile/K + 1 21 | } 22 | } 23 | return times 24 | } 25 | 26 | func minEatingSpeed(piles []int, H int) int { 27 | sum, max := sumAndMax(piles) 28 | if H >= sum { 29 | return 1 30 | } 31 | 32 | lowerBound := sum / H 33 | upperBound := max 34 | minK := 99999999999 35 | 36 | for lowerBound <= upperBound { 37 | k := lowerBound + (upperBound-lowerBound)/2 38 | // > H 向右走 39 | // <=H 向左走 40 | times := calcTimes(piles, k) 41 | if times > H { 42 | lowerBound = k + 1 43 | continue 44 | } 45 | 46 | // calctimes <= H,记录当前的 K 47 | // 然后向左走 48 | if times <= H { 49 | upperBound = k - 1 50 | if k < minK { 51 | minK = k 52 | } 53 | } 54 | } 55 | 56 | return minK 57 | } 58 | -------------------------------------------------------------------------------- /0875-koko-eating-bananas/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type TestCase struct { 10 | piles []int 11 | H int 12 | expected int 13 | } 14 | 15 | func TestMinEatingSpeed(t *testing.T) { 16 | cases := []TestCase{ 17 | TestCase{piles: []int{312884470}, H: 968709470, expected: 1}, 18 | TestCase{piles: []int{3, 6, 7, 11}, H: 8, expected: 4}, 19 | TestCase{piles: []int{30, 11, 23, 4, 20}, H: 5, expected: 30}, 20 | TestCase{piles: []int{30, 11, 23, 4, 20}, H: 6, expected: 23}, 21 | TestCase{piles: []int{332484035, 524908576, 855865114, 632922376, 222257295, 690155293, 112677673, 679580077, 337406589, 290818316, 877337160, 901728858, 679284947, 688210097, 692137887, 718203285, 629455728, 941802184}, H: 823855818, expected: 14}, 22 | } 23 | 24 | for _, cas := range cases { 25 | res := minEatingSpeed(cas.piles, cas.H) 26 | assert.Equal(t, cas.expected, res) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /0875-koko-eating-bananas/readme.md: -------------------------------------------------------------------------------- 1 | # link 2 | 3 | https://leetcode-cn.com/problems/koko-eating-bananas/description/ 4 | 5 | # desc 6 | 7 | 8 | 珂珂喜欢吃香蕉。这里有 N 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 H 小时后回来。 9 | 10 | 珂珂可以决定她吃香蕉的速度 K (单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 K 根。如果这堆香蕉少于 K 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。 11 | 12 | 珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。 13 | 14 | 返回她可以在 H 小时内吃掉所有香蕉的最小速度 K(K 为整数)。 15 | 16 | 示例 1: 17 | 18 | ``` 19 | 输入: piles = [3,6,7,11], H = 8 20 | 输出: 4 21 | ``` 22 | 23 | 示例 2: 24 | 25 | ``` 26 | 输入: piles = [30,11,23,4,20], H = 5 27 | 输出: 30 28 | ``` 29 | 30 | 示例 3: 31 | 32 | ``` 33 | 输入: piles = [30,11,23,4,20], H = 6 34 | 输出: 23 35 | ``` 36 | 37 | 38 | 提示: 39 | 40 | ``` 41 | 1 <= piles.length <= 10^4 42 | piles.length <= H <= 10^9 43 | 1 <= piles[i] <= 10^9 44 | ``` -------------------------------------------------------------------------------- /0876-middle-of-the-linked-list/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // ListNode ... 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * type ListNode struct { 12 | * Val int 13 | * Next *ListNode 14 | * } 15 | */ 16 | func middleNode(head *ListNode) *ListNode { 17 | if head == nil { 18 | return nil 19 | } 20 | 21 | l := countLength(head) 22 | midIdx := l / 2 23 | currentIdx := 0 24 | for { 25 | if currentIdx == midIdx { 26 | return head 27 | } 28 | head = head.Next 29 | currentIdx++ 30 | } 31 | } 32 | 33 | func countLength(head *ListNode) int { 34 | counter := 0 35 | for head != nil { 36 | head = head.Next 37 | counter++ 38 | } 39 | return counter 40 | } 41 | -------------------------------------------------------------------------------- /0877-stone-game/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type record struct { 4 | idx int 5 | sum int 6 | left int 7 | } 8 | 9 | func stoneGame(piles []int) bool { 10 | // init 11 | var f = make([][]record, len(piles)) 12 | for i := 0; i < len(piles); i++ { 13 | f[i] = make([]record, len(piles)) 14 | f[i][i] = record{ 15 | idx: i, 16 | sum: piles[i], 17 | left: 0, 18 | } 19 | } 20 | 21 | for gap := 1; gap <= len(piles)-1; gap++ { 22 | // i left index 23 | // j right index 24 | for i := 0; i < len(piles); i++ { 25 | j := i + gap 26 | if j >= len(piles) { 27 | break 28 | } 29 | 30 | if f[i+1][j].left+piles[i] < f[i][j-1].left+piles[j] { 31 | // 说明应该取右边的 32 | f[i][j] = record{idx: j, 33 | sum: f[i][j-1].left + piles[j], 34 | left: f[i][j-1].sum, 35 | } 36 | } else { 37 | f[i][j] = record{idx: i, 38 | sum: f[i+1][j].left + piles[i], 39 | left: f[i+1][j].sum, 40 | } 41 | } 42 | } 43 | } 44 | 45 | resultRec := f[0][len(piles)-1] 46 | if resultRec.sum > resultRec.left { 47 | return true 48 | } 49 | 50 | return false 51 | } 52 | -------------------------------------------------------------------------------- /0877-stone-game/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type TestCase struct { 11 | piles []int 12 | expected bool 13 | } 14 | 15 | func TestStoneGame(t *testing.T) { 16 | cases := []TestCase{ 17 | TestCase{piles: []int{5, 3, 4, 5}, expected: true}, 18 | TestCase{piles: []int{5}, expected: true}, 19 | TestCase{piles: []int{5, 2}, expected: true}, 20 | TestCase{piles: []int{5, 6, 5}, expected: true}, 21 | } 22 | 23 | for _, cas := range cases { 24 | res := stoneGame(cas.piles) 25 | assert.Equal(t, cas.expected, res, "input: "+fmt.Sprint(cas.piles)) 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /0878-nth-magical-number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func gcd(A, B int) int { 6 | if A > B { 7 | A, B = B, A 8 | } 9 | 10 | if B%A == 0 { 11 | return A 12 | } 13 | 14 | return gcd(B-A, A) 15 | } 16 | 17 | func nthMagicalNumber(N int, A int, B int) int { 18 | // ensure a <= b 19 | if A > B { 20 | A, B = B, A 21 | } 22 | 23 | if A == B || B%A == 0 { 24 | return int(int64(N*A) % 1000000007) 25 | } 26 | 27 | // two array 28 | // first: A, A*2, A*3, A*4 29 | // secon: B, B*2, ... --B * A/ gcd(B, A)-del- 30 | zxgbs := int64(A) * int64(B) / int64(gcd(A, B)) 31 | // startPosVal := A * N 32 | i := int64(N) 33 | j := int64(A*N/B) - int64(A*N)/(zxgbs) 34 | high := N 35 | low := 0 36 | for low <= high { 37 | mid := low + (high-low)/2 38 | i = int64(mid) 39 | j = int64(A)*int64(i)/int64(B) - int64(A)*int64(i)/(zxgbs) 40 | if i+j > int64(N) { 41 | high = mid - 1 42 | continue 43 | } 44 | if i+j < int64(N) { 45 | low = mid + 1 46 | continue 47 | } 48 | if i+j == int64(N) { 49 | return int(int64(A) * i % int64(1000000007)) 50 | } 51 | } 52 | 53 | j = int64(N) 54 | i = j * int64(B) / int64(A) 55 | high = int(j) 56 | low = 0 57 | for low <= high { 58 | mid := low + (high-low)/2 59 | j = int64(mid) 60 | i = int64(B) * int64(j) / int64(A) 61 | beforeJ := j * int64(B) / zxgbs 62 | if i+j-beforeJ > int64(N) { 63 | high = mid - 1 64 | continue 65 | } 66 | if i+j-beforeJ < int64(N) { 67 | low = mid + 1 68 | continue 69 | } 70 | if i+j-beforeJ == int64(N) { 71 | if j*int64(B) == zxgbs { 72 | return int(j + int64(1)%int64(1000000007)) 73 | } 74 | return int(j * int64(B) % int64(1000000007)) 75 | } 76 | } 77 | return 0 78 | } 79 | 80 | func main() { 81 | fmt.Println(nthMagicalNumber(1, 2, 3)) 82 | fmt.Println(nthMagicalNumber(4, 2, 3)) 83 | fmt.Println(nthMagicalNumber(5, 2, 4)) 84 | fmt.Println(nthMagicalNumber(3, 6, 4)) 85 | fmt.Println(nthMagicalNumber(10, 10, 8)) 86 | } 87 | -------------------------------------------------------------------------------- /0880-decoded-string-at-index/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func decodeAtIndex(S string, K int) string { 6 | var base = 0 7 | var exp = 1 8 | var lastChar byte 9 | for i := 0; i < len(S); i++ { 10 | if S[i] >= 'a' && S[i] <= 'z' { 11 | base = base*exp + 1 12 | exp = 1 13 | lastChar = S[i] 14 | } 15 | if S[i] >= '0' && S[i] <= '9' { 16 | exp = (int(S[i]) - int('0')) * exp 17 | } 18 | //println(base, exp, S, K) 19 | if base*exp == K || (base*exp > K && K%base == 0) { 20 | return string([]byte{lastChar}) 21 | } 22 | 23 | if base*exp > K { 24 | return decodeAtIndex(S, K%(base)) 25 | } 26 | } 27 | return "" 28 | } 29 | 30 | func main() { 31 | fmt.Println(decodeAtIndex("leet2code3", 10)) 32 | 33 | fmt.Println(decodeAtIndex("ha22", 5)) 34 | fmt.Println(decodeAtIndex("a2345678999999999999999", 1)) 35 | fmt.Println(decodeAtIndex("a23", 6)) 36 | fmt.Println(decodeAtIndex("vk6u5xhq9v", 554)) 37 | } 38 | -------------------------------------------------------------------------------- /0881-boats-to-save-people/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func numRescueBoats(people []int, limit int) int { 9 | 10 | sort.Slice(people, func(i, j int) bool { 11 | return people[i] > people[j] 12 | }) 13 | 14 | // 从胖子开始,如果可以搭配当前最瘦的 15 | // 那就搭,搭不了就滚 16 | var totalBoat = 0 17 | var maxIdx = len(people) - 1 18 | var minIdx = 0 19 | for minIdx < maxIdx { 20 | totalBoat++ 21 | if people[maxIdx]+people[minIdx] <= limit { 22 | minIdx++ 23 | maxIdx-- 24 | continue 25 | } 26 | minIdx++ 27 | } 28 | // 说明还有一个哥们儿没带走 29 | if minIdx == maxIdx { 30 | totalBoat++ 31 | } 32 | 33 | return totalBoat 34 | } 35 | 36 | func main() { 37 | fmt.Println(numRescueBoats([]int{1, 2}, 3)) 38 | fmt.Println(numRescueBoats([]int{3, 2, 2, 1}, 3)) 39 | fmt.Println(numRescueBoats([]int{3, 5, 3, 4}, 5)) 40 | } 41 | -------------------------------------------------------------------------------- /0883-projection-area-of-3d-shapes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func projectionArea(grid [][]int) int { 6 | if len(grid) == 0 { 7 | return 0 8 | } 9 | 10 | elemCnt := len(grid) * len(grid[0]) 11 | colMaxSum := 0 12 | rowMaxSum := 0 13 | for i := 0; i < len(grid); i++ { 14 | rowIMax := 0 15 | for j := 0; j < len(grid[0]); j++ { 16 | if grid[i][j] > rowIMax { 17 | rowIMax = grid[i][j] 18 | } 19 | if grid[i][j] == 0 { 20 | elemCnt-- 21 | } 22 | } 23 | rowMaxSum += rowIMax 24 | } 25 | for i := 0; i < len(grid[0]); i++ { 26 | colIMax := 0 27 | for j := 0; j < len(grid); j++ { 28 | if grid[j][i] > colIMax { 29 | colIMax = grid[j][i] 30 | } 31 | } 32 | colMaxSum += colIMax 33 | } 34 | return elemCnt + colMaxSum + rowMaxSum 35 | 36 | } 37 | 38 | func main() { 39 | fmt.Println(projectionArea([][]int{[]int{1, 0}, []int{0, 2}})) 40 | } 41 | -------------------------------------------------------------------------------- /0884-uncommon-words-from-two-sentences/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(uncommonFromSentences("this apple is sweet", "this apple is sour")) 7 | } 8 | 9 | func getWordMap(A string) map[string]int { 10 | mapA := map[string]int{} 11 | currentWord := []byte{} 12 | for i := 0; i < len(A); i++ { 13 | if A[i] >= 'a' && A[i] <= 'z' { 14 | currentWord = append(currentWord, A[i]) 15 | } else { 16 | mapA[string(currentWord)]++ 17 | currentWord = currentWord[:0] 18 | } 19 | } 20 | println(string(currentWord)) 21 | if len(currentWord) > 0 { 22 | mapA[string(currentWord)]++ 23 | } 24 | return mapA 25 | } 26 | 27 | func uncommonFromSentences(A string, B string) []string { 28 | var mapA = getWordMap(A) 29 | var mapB = getWordMap(B) 30 | fmt.Println(mapA, mapB) 31 | res := []string{} 32 | for k, cnt := range mapA { 33 | if mapB[k] == 0 && cnt == 1 { 34 | res = append(res, k) 35 | } 36 | } 37 | for k, cnt := range mapB { 38 | if mapA[k] == 0 && cnt == 1 { 39 | res = append(res, k) 40 | } 41 | } 42 | return res 43 | } 44 | -------------------------------------------------------------------------------- /0885-spiral-matrix-iii/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | func spiralMatrixIII(R int, C int, r0 int, c0 int) [][]int { 6 | traverseCnt := 1 7 | res := [][]int{} 8 | res = append(res, []int{r0, c0}) 9 | stepLen := 0 10 | matrixSize := R * C 11 | for { 12 | if traverseCnt == matrixSize { 13 | break 14 | } 15 | stepLen++ 16 | // 右, c0++, r0 不变 17 | for i := 0; i < stepLen; i++ { 18 | c0++ 19 | if r0 >= 0 && r0 < R && c0 >= 0 && c0 < C { 20 | res = append(res, []int{r0, c0}) 21 | traverseCnt++ 22 | } 23 | } 24 | // 下,r0++, c0 不变 25 | for i := 0; i < stepLen; i++ { 26 | r0++ 27 | if r0 >= 0 && r0 < R && c0 >= 0 && c0 < C { 28 | res = append(res, []int{r0, c0}) 29 | traverseCnt++ 30 | } 31 | } 32 | stepLen++ 33 | // 左,c0--, r0 不变 34 | for i := 0; i < stepLen; i++ { 35 | c0-- 36 | if r0 >= 0 && r0 < R && c0 >= 0 && c0 < C { 37 | res = append(res, []int{r0, c0}) 38 | traverseCnt++ 39 | } 40 | } 41 | // 上,r0--, c0 不变 42 | for i := 0; i < stepLen; i++ { 43 | r0-- 44 | if r0 >= 0 && r0 < R && c0 >= 0 && c0 < C { 45 | res = append(res, []int{r0, c0}) 46 | traverseCnt++ 47 | } 48 | } 49 | } 50 | return res 51 | } 52 | -------------------------------------------------------------------------------- /0886-possible-bipartition/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(possibleBipartition(4, [][]int{[]int{1, 2}, []int{1, 3}, []int{2, 4}})) 7 | } 8 | 9 | func getNextLevel(dislikeMap map[int]map[int]bool, current map[int]bool) map[int]bool { 10 | nextLevel := map[int]bool{} 11 | // needToGoDeeper := false 12 | for elem := range current { 13 | dislikeForI := dislikeMap[elem] 14 | for k := range dislikeForI { 15 | nextLevel[k] = true 16 | } 17 | } 18 | return nextLevel 19 | } 20 | 21 | func hasElemWhichNotInMap(elems map[int]bool, valMap map[int]bool) bool { 22 | for elem := range elems { 23 | if valMap[elem] == false { 24 | return true 25 | } 26 | } 27 | 28 | return false 29 | } 30 | 31 | func possibleBipartition(N int, dislikes [][]int) bool { 32 | if len(dislikes) == 0 { 33 | return true 34 | } 35 | 36 | var dislikeMap = map[int]map[int]bool{} 37 | for i := 0; i < len(dislikes); i++ { 38 | x, y := dislikes[i][0], dislikes[i][1] 39 | if dislikeMap[x] == nil { 40 | dislikeMap[x] = make(map[int]bool) 41 | } 42 | if dislikeMap[y] == nil { 43 | dislikeMap[y] = make(map[int]bool) 44 | } 45 | dislikeMap[x][y] = true 46 | dislikeMap[y][x] = true 47 | } 48 | // fmt.Println(dislikeMap) 49 | 50 | mapA := map[int]bool{} 51 | mapB := map[int]bool{} 52 | for i := 1; i <= N; i++ { 53 | if mapA[i] == true || mapB[i] == true { 54 | continue 55 | } 56 | 57 | // 从 i 开始广度优先搜索 58 | currentLevel := map[int]bool{i: true} 59 | mapA[i] = true 60 | cnt := 1 61 | for { 62 | nextLevel := getNextLevel(dislikeMap, currentLevel) 63 | //fmt.Println("next level", nextLevel) 64 | var m map[int]bool 65 | var n map[int]bool 66 | if cnt == 0 { 67 | // 放 mapA 68 | if !hasElemWhichNotInMap(nextLevel, mapA) { 69 | break 70 | } 71 | m, n, cnt = mapA, mapB, 1 72 | } else { 73 | // 放 mapB 74 | if !hasElemWhichNotInMap(nextLevel, mapB) { 75 | break 76 | } 77 | m, n, cnt = mapB, mapA, 0 78 | } 79 | 80 | for elem := range nextLevel { 81 | m[elem] = true 82 | 83 | if n[elem] == true { 84 | return false 85 | } 86 | } 87 | currentLevel = nextLevel 88 | //fmt.Println(m, n) 89 | } 90 | } 91 | 92 | // fmt.Println(mapA, mapB) 93 | 94 | return true 95 | } 96 | -------------------------------------------------------------------------------- /0887-super-egg-drop/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | f[step][k] 3 | step 表示步数 4 | k 表示鸡蛋数 5 | 这道题的关键点在于,不是用两个输入维度来做动态规划 6 | 而是用一个输入维度和一个输出维度来做, 7 | 其结果 >= 其中的另一个输入维度时,即满足输出条件, 8 | 但因为可能存在多条结果,所以要把所有结果都走完 9 | 只要用来 DP 的两个维度能有确定的上界就可以 10 | */ 11 | package main 12 | 13 | import "fmt" 14 | 15 | func main() { 16 | fmt.Println(superEggDrop(1, 2)) 17 | fmt.Println(superEggDrop(2, 6)) 18 | fmt.Println(superEggDrop(2, 4)) 19 | } 20 | 21 | func superEggDrop(K int, N int) int { 22 | var f = [][]int{} 23 | emptyLine := make([]int, K+1) 24 | f = append(f, emptyLine) 25 | result := N + 1 26 | for steps := 1; steps <= N; steps++ { 27 | line := make([]int, K+1) 28 | f = append(f, line) 29 | for k := 1; k <= K; k++ { 30 | if steps == 1 { 31 | f[steps][k] = 1 32 | } else if k == 1 { 33 | f[steps][k] = steps 34 | } else { 35 | // steps > 1 36 | // k > 1 37 | f[steps][k] = 1 + f[steps-1][k-1] + f[steps-1][k] 38 | } 39 | //fmt.Println(f) 40 | 41 | if f[steps][k] >= N && steps < result { 42 | //fmt.Println(steps, k, f[steps]) 43 | result = steps 44 | } 45 | } 46 | } 47 | return result 48 | } 49 | -------------------------------------------------------------------------------- /0888-fair-candy-swap/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(fairCandySwap([]int{1, 1}, []int{2, 2})) 7 | } 8 | 9 | func fairCandySwap(A []int, B []int) []int { 10 | var diff int 11 | var aMap, bMap = map[int]bool{}, map[int]bool{} 12 | var sumA, sumB int 13 | for i := 0; i < len(A); i++ { 14 | aMap[A[i]] = true 15 | sumA += A[i] 16 | } 17 | for i := 0; i < len(B); i++ { 18 | bMap[B[i]] = true 19 | sumB += B[i] 20 | } 21 | diff = sumA - sumB 22 | 23 | if diff%2 != 0 { 24 | return []int{} 25 | } 26 | 27 | for i := 0; i < len(A); i++ { 28 | if bMap[A[i]-diff/2] == true { 29 | return []int{A[i], A[i] - diff/2} 30 | } 31 | } 32 | return []int{} 33 | } 34 | -------------------------------------------------------------------------------- /0890-find-and-replace-pattern/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(findAndReplacePattern([]string{"abc", "deq", "mee", "aqq", "dkd", "ccc"}, "abb")) 7 | } 8 | 9 | func findAndReplacePattern(words []string, pattern string) []string { 10 | res := []string{} 11 | outer: 12 | for i := 0; i < len(words); i++ { 13 | if len(words[i]) != len(pattern) { 14 | continue 15 | } 16 | m := map[byte]byte{} 17 | m2 := map[byte]byte{} 18 | word := words[i] 19 | for j := 0; j < len(word); j++ { 20 | if m[word[j]] == 0 && m2[pattern[j]] == 0 { 21 | m[word[j]] = pattern[j] 22 | m2[pattern[j]] = word[j] 23 | } 24 | if m[word[j]] == 0 && m2[pattern[j]] != 0 { 25 | continue outer 26 | } 27 | if m[word[j]] != 0 && m2[pattern[j]] == 0 { 28 | continue outer 29 | } 30 | if m[word[j]] != 0 && m2[pattern[j]] != 0 { 31 | if m[word[j]] != pattern[j] || m2[pattern[j]] != word[j] { 32 | continue outer 33 | } 34 | } 35 | } 36 | res = append(res, word) 37 | } 38 | return res 39 | } 40 | -------------------------------------------------------------------------------- /0890-find-and-replace-pattern/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 在 go 的 map 判断中,m[byte] = 0 要比 _, ok 判断方便一些~ 4 | -------------------------------------------------------------------------------- /0891-sum-of-subsequence-widths/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(sumSubseqWidths([]int{2, 1, 3})) 10 | } 11 | 12 | func pow(n int) int { 13 | if n == 0 { 14 | return 1 15 | } 16 | if n == 1 { 17 | return 2 18 | } 19 | 20 | if n%2 == 0 { 21 | mid := pow(n/2) % 1000000007 22 | return (mid * mid) % 1000000007 23 | } 24 | mid := pow(n/2) % 1000000007 25 | return (2 * mid * mid) % 1000000007 26 | } 27 | 28 | func sumSubseqWidths(A []int) int { 29 | res := 0 30 | sort.Ints(A) 31 | for i := 0; i < len(A); i++ { 32 | res = res + (pow(i)-pow(len(A)-i-1))*A[i] 33 | res = res % 1000000007 34 | //println(i, A[i], res, pow(i), pow(len(A)-i-1)) 35 | } 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /0891-sum-of-subsequence-widths/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 1. 二分快速求 2 的幂 4 | 5 | 2. 用数学方法推导每个值在被减数和减数上出现的次数: 6 | 7 | ```shell 8 | vali := A[i] * (2^(i-1)-1) - A[i] * (2^(n-i-1)-1) 9 | ``` 10 | -------------------------------------------------------------------------------- /0892-surface-area-of-3d-shapes/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(surfaceArea([][]int{[]int{2}})) 7 | fmt.Println(surfaceArea([][]int{[]int{1, 2}, []int{3, 4}})) 8 | } 9 | 10 | func abs(a int) int { 11 | if a < 0 { 12 | return -a 13 | } 14 | return a 15 | } 16 | 17 | func surfaceArea(grid [][]int) int { 18 | res := 0 19 | // 横着扫一遍 20 | for i := 0; i < len(grid); i++ { 21 | for j := 0; j < len(grid[0]); j++ { 22 | // 第一行 23 | if i == 0 { 24 | res += grid[i][j] 25 | continue 26 | } 27 | 28 | // 中间 29 | res += abs(grid[i][j] - grid[i-1][j]) 30 | } 31 | // 最后一行 32 | if i == len(grid)-1 { 33 | for j := 0; j < len(grid[0]); j++ { 34 | res += grid[i][j] 35 | } 36 | } 37 | } 38 | 39 | // 竖着扫一遍 40 | for i := 0; i < len(grid[0]); i++ { 41 | for j := 0; j < len(grid); j++ { 42 | // grid[j][i] 43 | // 第一列 44 | if i == 0 { 45 | res += grid[j][i] 46 | continue 47 | } 48 | // 中间 49 | res += abs(grid[j][i] - grid[j][i-1]) 50 | } 51 | // 最后一列 52 | if i == len(grid[0])-1 { 53 | for j := 0; j < len(grid); j++ { 54 | res += grid[j][i] 55 | } 56 | } 57 | } 58 | 59 | // 天花板 && 地下室 60 | for i := 0; i < len(grid); i++ { 61 | for j := 0; j < len(grid[0]); j++ { 62 | if grid[i][j] != 0 { 63 | res += 2 64 | } 65 | } 66 | } 67 | return res 68 | } 69 | -------------------------------------------------------------------------------- /0893-groups-of-special-equivalent-strings/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(numSpecialEquivGroups([]string{"abcd", "cdab", "adcb", "cbad"})) 7 | fmt.Println(numSpecialEquivGroups([]string{"abc", "acb", "bac", "bca", "cab", "cba"})) 8 | } 9 | 10 | func isInSameGroup(a, b string) bool { 11 | if len(a) != len(b) { 12 | return false 13 | } 14 | 15 | oddMapForA := map[byte]int{} 16 | evenMapForA := map[byte]int{} 17 | oddMapForB := map[byte]int{} 18 | evenMapForB := map[byte]int{} 19 | for i := 0; i < len(a); i++ { 20 | if i%2 == 0 { 21 | oddMapForA[a[i]]++ 22 | oddMapForB[b[i]]++ 23 | continue 24 | } 25 | evenMapForA[a[i]]++ 26 | evenMapForB[b[i]]++ 27 | } 28 | for b, cnt := range oddMapForA { 29 | if cnt != oddMapForB[b] { 30 | return false 31 | } 32 | } 33 | for b, cnt := range evenMapForA { 34 | if cnt != evenMapForB[b] { 35 | return false 36 | } 37 | } 38 | return true 39 | } 40 | 41 | func numSpecialEquivGroups(A []string) int { 42 | used := make([]bool, len(A)) 43 | cnt := 0 44 | for i := 0; i < len(A); i++ { 45 | if used[i] == true { 46 | continue 47 | } 48 | used[i] = true 49 | cnt++ 50 | 51 | group := []string{A[i]} 52 | for j := i + 1; j < len(A); j++ { 53 | if isInSameGroup(A[j], A[i]) { 54 | used[j] = true 55 | group = append(group, A[j]) 56 | } 57 | } 58 | } 59 | return cnt 60 | } 61 | -------------------------------------------------------------------------------- /0894-all-possible-full-binary-trees/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() {} 4 | 5 | // TreeNode ... 6 | type TreeNode struct { 7 | Val int 8 | Left *TreeNode 9 | Right *TreeNode 10 | } 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * type TreeNode struct { 15 | * Val int 16 | * Left *TreeNode 17 | * Right *TreeNode 18 | * } 19 | */ 20 | func allPossibleFBT(N int) []*TreeNode { 21 | if N%2 == 0 { 22 | return []*TreeNode{} 23 | } 24 | 25 | if N == 1 { 26 | return []*TreeNode{ 27 | &TreeNode{}, 28 | } 29 | } 30 | 31 | if N == 3 { 32 | return []*TreeNode{ 33 | &TreeNode{Left: &TreeNode{}, Right: &TreeNode{}}, 34 | } 35 | } 36 | 37 | res := []*TreeNode{} 38 | for i := 1; i < N-1; i += 2 { 39 | lPossible := allPossibleFBT(i) 40 | rPossible := allPossibleFBT(N - 1 - i) 41 | for j := 0; j < len(lPossible); j++ { 42 | for k := 0; k < len(rPossible); k++ { 43 | cur := &TreeNode{ 44 | Left: lPossible[j], 45 | Right: rPossible[k], 46 | } 47 | res = append(res, cur) 48 | } 49 | } 50 | } 51 | return res 52 | } 53 | -------------------------------------------------------------------------------- /0895-maximum-frequency-stack/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | obj := Constructor() 5 | obj.Push(4) 6 | obj.Push(0) 7 | obj.Push(9) 8 | obj.Push(3) 9 | obj.Push(4) 10 | obj.Push(2) 11 | obj.Pop() 12 | obj.Push(6) 13 | obj.Pop() 14 | obj.Push(1) 15 | obj.Pop() 16 | obj.Push(1) 17 | obj.Pop() 18 | obj.Push(4) 19 | obj.Pop() 20 | obj.Pop() 21 | obj.Pop() 22 | obj.Pop() 23 | obj.Pop() 24 | obj.Pop() 25 | } 26 | 27 | type FreqStack struct { 28 | freq map[int]int 29 | freq2stack map[int][]int 30 | maxFreq int 31 | } 32 | 33 | func Constructor() FreqStack { 34 | return FreqStack{ 35 | freq: make(map[int]int), 36 | freq2stack: map[int][]int{}, 37 | maxFreq: 0, 38 | } 39 | } 40 | 41 | func (this *FreqStack) Push(x int) { 42 | this.freq[x]++ 43 | if this.freq[x] > this.maxFreq { 44 | this.maxFreq = this.freq[x] 45 | } 46 | this.freq2stack[this.freq[x]] = append(this.freq2stack[this.freq[x]], x) 47 | } 48 | 49 | func (this *FreqStack) Pop() int { 50 | lastIdx := len(this.freq2stack[this.maxFreq]) - 1 51 | res := this.freq2stack[this.maxFreq][lastIdx] 52 | this.freq2stack[this.maxFreq] = this.freq2stack[this.maxFreq][:lastIdx] // pop 53 | this.freq[res]-- 54 | 55 | if len(this.freq2stack[this.maxFreq]) == 0 { 56 | delete(this.freq2stack, this.maxFreq) 57 | this.maxFreq-- 58 | } 59 | return res 60 | } 61 | 62 | /** 63 | * Your FreqStack object will be instantiated and called as such: 64 | * obj := Constructor(); 65 | * obj.Push(x); 66 | * param_2 := obj.Pop(); 67 | */ 68 | -------------------------------------------------------------------------------- /0896-monotonic-array/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | } 5 | 6 | func isMonotonic(A []int) bool { 7 | if len(A) == 1 || len(A) == 0 { 8 | return true 9 | } 10 | monoFlag := 0 11 | 12 | for i := 1; i < len(A); i++ { 13 | if monoFlag == 0 { 14 | if A[i] > A[i-1] { 15 | monoFlag = 1 // 增 16 | } 17 | if A[i] < A[i-1] { 18 | monoFlag = 2 19 | } 20 | continue 21 | } 22 | if monoFlag == 2 && A[i] > A[i-1] { 23 | return false 24 | } 25 | if monoFlag == 1 && A[i] < A[i-1] { 26 | return false 27 | } 28 | } 29 | return true 30 | } 31 | -------------------------------------------------------------------------------- /0898-bitwise-ors-of-subarrays/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(subarrayBitwiseORs([]int{0})) 7 | fmt.Println(subarrayBitwiseORs([]int{1, 1, 2})) 8 | fmt.Println(subarrayBitwiseORs([]int{1, 2, 4})) 9 | } 10 | 11 | func subarrayBitwiseORs(A []int) int { 12 | resMap := map[int]bool{} 13 | curMap := map[int]bool{} 14 | 15 | // 起始位置 16 | for i := 0; i < len(A); i++ { 17 | curNew := map[int]bool{} 18 | for v := range curMap { 19 | newV := v | A[i] 20 | if resMap[newV] == false { 21 | resMap[newV] = true 22 | } 23 | curNew[newV] = true 24 | } 25 | curNew[A[i]] = true 26 | if resMap[A[i]] == false { 27 | resMap[A[i]] = true 28 | } 29 | curMap = curNew 30 | } 31 | return len(resMap) 32 | } 33 | -------------------------------------------------------------------------------- /0898-bitwise-ors-of-subarrays/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 4 | 80 / 83 个通过测试用例 5 | 状态:超出时间限制 6 | -------------------------------------------------------------------------------- /0898-bitwise-ors-of-subarrays/time_exceed.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(subarrayBitwiseORs([]int{0})) 7 | fmt.Println(subarrayBitwiseORs([]int{1, 1, 2})) 8 | fmt.Println(subarrayBitwiseORs([]int{1, 2, 4})) 9 | } 10 | 11 | func subarrayBitwiseORs(A []int) int { 12 | bitwiseArr := make([]int, len(A)) 13 | resMap := map[int]bool{} 14 | 15 | // 起始位置 16 | for i := 0; i < len(A); i++ { 17 | // 起始位置 18 | for j := i; j < len(A); j++ { 19 | if j-i == 0 { 20 | bitwiseArr[j] = A[j] 21 | } else { 22 | bitwiseArr[j] = bitwiseArr[j-1] | A[j] 23 | } 24 | if resMap[bitwiseArr[j]] == false { 25 | resMap[bitwiseArr[j]] = true 26 | } 27 | } 28 | } 29 | return len(resMap) 30 | } 31 | -------------------------------------------------------------------------------- /0899-orderly-queue/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | fmt.Println(orderlyQueue("cba", 1)) 10 | fmt.Println(orderlyQueue("baaca", 3)) 11 | } 12 | 13 | func orderlyQueue(S string, K int) string { 14 | if K >= 2 { 15 | sBytes := []byte(S) 16 | sort.Slice(sBytes, func(i, j int) bool { 17 | return sBytes[i] < sBytes[j] 18 | }) 19 | return string(sBytes) 20 | } 21 | minStr := S 22 | for i := 1; i < len(S); i++ { 23 | curStr := S[i:] + S[0:i] 24 | if curStr < minStr { 25 | minStr = curStr 26 | } 27 | } 28 | return minStr 29 | } 30 | -------------------------------------------------------------------------------- /0900-rle-iterator/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | rie := Constructor([]int{811, 903, 310, 730, 899, 684, 472, 100, 434, 611}) 7 | fmt.Println(rie.Next(358)) 8 | fmt.Println(rie.seq) 9 | fmt.Println(rie.Next(345)) 10 | fmt.Println(rie.seq) 11 | fmt.Println(rie.Next(154)) 12 | fmt.Println(rie.seq) 13 | fmt.Println(rie.Next(265)) 14 | fmt.Println(rie.seq) 15 | fmt.Println(rie.Next(73)) 16 | fmt.Println(rie.seq) 17 | fmt.Println(rie.Next(220)) 18 | fmt.Println(rie.seq) 19 | fmt.Println(rie.Next(138)) 20 | fmt.Println(rie.seq) 21 | fmt.Println(rie.Next(4)) 22 | fmt.Println(rie.seq) 23 | fmt.Println(rie.Next(170)) 24 | fmt.Println(rie.seq) 25 | fmt.Println(rie.Next(88)) 26 | fmt.Println(rie.seq) 27 | } 28 | 29 | type RLEIterator struct { 30 | seq []int 31 | currentPos int 32 | } 33 | 34 | func Constructor(A []int) RLEIterator { 35 | rieIter := RLEIterator{ 36 | seq: A, 37 | currentPos: 0, 38 | } 39 | 40 | return rieIter 41 | } 42 | 43 | func (this *RLEIterator) Next(n int) int { 44 | if len(this.seq) == 0 { 45 | return -1 46 | } 47 | 48 | pos := this.currentPos 49 | for { 50 | if pos >= len(this.seq) { 51 | break 52 | } 53 | 54 | if this.seq[pos] >= n { 55 | this.seq[pos] -= n 56 | return this.seq[pos+1] 57 | } 58 | 59 | n = n - this.seq[pos] 60 | this.seq[pos] = 0 61 | pos += 2 62 | } 63 | return -1 64 | } 65 | 66 | /** 67 | * Your RLEIterator object will be instantiated and called as such: 68 | * obj := Constructor(A); 69 | * param_1 := obj.Next(n); 70 | */ 71 | -------------------------------------------------------------------------------- /0901-online-stock-span/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type StockSpanner struct { 4 | elemList []int 5 | } 6 | 7 | func Constructor() StockSpanner { 8 | return StockSpanner{} 9 | } 10 | 11 | func (this *StockSpanner) Next(price int) int { 12 | if len(this.elemList) == 0 { 13 | this.elemList = append(this.elemList, price) 14 | return 1 15 | } 16 | var res = 1 17 | for i := len(this.elemList) - 1; i >= 0; i-- { 18 | if this.elemList[i] <= price { 19 | res++ 20 | } else { 21 | break 22 | } 23 | } 24 | this.elemList = append(this.elemList, price) 25 | return res 26 | } 27 | 28 | /** 29 | * Your StockSpanner object will be instantiated and called as such: 30 | * obj := Constructor(); 31 | * param_1 := obj.Next(price); 32 | */ 33 | 34 | func main() { 35 | var s = Constructor() 36 | println(s.Next(100)) 37 | println(s.Next(80)) 38 | println(s.Next(60)) 39 | println(s.Next(70)) 40 | println(s.Next(60)) 41 | println(s.Next(75)) 42 | println(s.Next(85)) 43 | } 44 | -------------------------------------------------------------------------------- /0904-fruit-into-baskets/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(totalFruit([]int{1})) 7 | fmt.Println(totalFruit([]int{1, 2, 1})) 8 | fmt.Println(totalFruit([]int{0, 1, 2, 2})) 9 | fmt.Println(totalFruit([]int{1, 2, 3, 2, 2})) 10 | fmt.Println(totalFruit([]int{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4})) 11 | } 12 | 13 | func totalFruit(tree []int) int { 14 | if len(tree) <= 2 { 15 | return len(tree) 16 | } 17 | 18 | lastPosA, lastPosB := -1, -1 19 | curA, curB := -1, -1 20 | currentCnt, maxCnt := 0, 0 21 | for i := 0; i < len(tree); i++ { 22 | if tree[i] != curA && tree[i] != curB { 23 | // 选那个离当前位置最选的扔掉 24 | // 1, 2, 1, 1, 3 => 扔掉 2 25 | if lastPosA < lastPosB { 26 | currentCnt = i - lastPosA 27 | lastPosA = i 28 | curA = tree[i] 29 | } else { 30 | currentCnt = i - lastPosB 31 | lastPosB = i 32 | curB = tree[i] 33 | } 34 | } else if tree[i] == curA { 35 | lastPosA = i 36 | currentCnt++ 37 | } else { // tree[i] == curB 38 | lastPosB = i 39 | currentCnt++ 40 | } 41 | 42 | if currentCnt > maxCnt { 43 | maxCnt = currentCnt 44 | } 45 | } 46 | 47 | return maxCnt 48 | } 49 | -------------------------------------------------------------------------------- /0905-sort-array-by-parity/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | arr := []int{3, 1, 2, 4} 7 | fmt.Println(sortArrayByParity(arr)) 8 | } 9 | 10 | func sortArrayByParity(A []int) []int { 11 | pos := 0 12 | for i := 0; i < len(A); i++ { 13 | if A[i]%2 == 0 { 14 | A[pos], A[i] = A[i], A[pos] 15 | pos++ 16 | } 17 | } 18 | return A 19 | } 20 | -------------------------------------------------------------------------------- /A_N_K/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func nextPermutation(arr []int, max int) []int { 6 | return nil 7 | } 8 | 9 | func main() { 10 | var arr = []int{0, 1, 2, 3} 11 | for nextPermutation(arr, 3) != nil { 12 | fmt.Println(arr) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /A_N_K/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | type TestCase struct { 8 | nums int 9 | K int 10 | expectedLength int 11 | } 12 | 13 | func TestAnk(t *testing.T) { 14 | } 15 | -------------------------------------------------------------------------------- /A_N_K/readme.md: -------------------------------------------------------------------------------- 1 | # desc 2 | 3 | 从 N 个里选 K 个元素的全排列的模板代码。 4 | -------------------------------------------------------------------------------- /A_N_K/recursive.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func pickOutIthElem(arr []int, i int) []int { 6 | if len(arr) == 0 { 7 | return arr 8 | } 9 | 10 | // copy arr to another slice 11 | res := make([]int, 0, len(arr)-1) 12 | for j := 0; j < len(arr); j++ { 13 | if j == i { 14 | continue 15 | } 16 | res = append(res, arr[j]) 17 | } 18 | 19 | return res 20 | } 21 | 22 | func appendToEveryArr(arr [][]int, elem int) [][]int { 23 | var res [][]int 24 | for i := 0; i < len(arr); i++ { 25 | arr[i] = append(arr[i], elem) 26 | res = append(res, arr[i]) 27 | } 28 | return res 29 | } 30 | 31 | func getPermutation(arr []int) [][]int { 32 | 33 | // 递归终止 34 | if len(arr) == 1 || len(arr) == 0 { 35 | return [][]int{arr} 36 | } 37 | 38 | var result = [][]int{} 39 | 40 | for i := 0; i < len(arr); i++ { 41 | // 去除 arr[i] 42 | arrWithOutIthElem := pickOutIthElem(arr, i) 43 | 44 | midResult := getPermutation(arrWithOutIthElem) 45 | 46 | // 给每一个子数组,都 append 上当前挑出的元素 47 | result = append(result, appendToEveryArr(midResult, arr[i])...) 48 | } 49 | return result 50 | } 51 | 52 | func main() { 53 | var arr = []int{0, 1, 2, 3} 54 | var res = getPermutation(arr) 55 | fmt.Println(res) 56 | } 57 | -------------------------------------------------------------------------------- /BINARY_SEARCH/bs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func bs(arr []int, target int) int { 6 | low, high := 0, len(arr)-1 7 | for low <= high { 8 | mid := low + (high-low)/2 9 | if arr[mid] < target { 10 | low = mid + 1 11 | continue 12 | } 13 | 14 | if arr[mid] > target { 15 | high = mid - 1 16 | continue 17 | } 18 | return mid 19 | } 20 | return -1 21 | } 22 | 23 | func main() { 24 | arr := []int{1, 2, 3, 4, 5} 25 | fmt.Println(bs(arr, 3)) 26 | fmt.Println(bs(arr, 1)) 27 | } 28 | -------------------------------------------------------------------------------- /BITMAP/readme.md: -------------------------------------------------------------------------------- 1 | # desc 2 | 3 | implement a bitmap in golang -------------------------------------------------------------------------------- /C_N_K/readme.md: -------------------------------------------------------------------------------- 1 | # desc 2 | 3 | K 数之和,即从 N 个数中挑选 K 个求和枚举,应该是比较通用的算法。 4 | -------------------------------------------------------------------------------- /DFS_BFS/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | dfs bfs 模板代码 4 | -------------------------------------------------------------------------------- /HIGH_PRECISION/readme.md: -------------------------------------------------------------------------------- 1 | # desc 2 | 3 | 实现高精度加、减、乘、除 4 | -------------------------------------------------------------------------------- /NEXT_PERMUTATION/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | /* 9 | @1 : 从右向左搜索,找到第一个 i,满足 nums[i] > nums[i-1] 10 | @2 : 从 i 向右(包括i)搜索,找出满足 > nums[i-1] 条件的最小的 nums[j] 11 | @3 : swap(nums[i-1], nums[j]) 12 | @4 : sort(nums[i:]) 13 | */ 14 | func nextPermutation(nums []int) []int { 15 | // @1 16 | for i := len(nums) - 1; i >= 1; i-- { 17 | if nums[i] > nums[i-1] { 18 | // @2 19 | minMax, minMaxIdx := nums[i], i 20 | for j := i; j < len(nums); j++ { 21 | if nums[j] < minMax && nums[j] > nums[i-1] { 22 | minMax, minMaxIdx = nums[j], j 23 | } 24 | } 25 | 26 | // @3 27 | nums[i-1], nums[minMaxIdx] = nums[minMaxIdx], nums[i-1] 28 | // @4 29 | subSlice := nums[i:] 30 | sort.Slice(subSlice, func(x, y int) bool { 31 | return subSlice[x] < subSlice[y] 32 | }) 33 | break 34 | } 35 | } 36 | return nums 37 | } 38 | 39 | func main() { 40 | fmt.Println(nextPermutation([]int{1, 2, 3, 4, 5})) 41 | fmt.Println(nextPermutation([]int{1, 2, 5, 4, 3})) 42 | } 43 | -------------------------------------------------------------------------------- /SEGMENT_TREE/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | 线段树模板代码 4 | 5 | -------------------------------------------------------------------------------- /SORT/heapsort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { arr := []int{9,8,7,6,5,5, 4, 3, 2, 1}; hs(arr); fmt.Println(arr) } 6 | 7 | func hs(arr []int) { 8 | buildHeap(arr) 9 | 10 | for i := len(arr)-1; i >= 0; i-- { 11 | arr[0], arr[i] = arr[i], arr[0] 12 | adjustHeap(arr, 0, i-1) 13 | } 14 | } 15 | 16 | func buildHeap(arr []int) { 17 | for i := len(arr) / 2; i >= 0; i-- { 18 | // 调整以 arr[i] 为堆顶的堆 19 | // left = 2*i+1, right = 2*i+2 20 | // biggest := arr[i] 21 | adjustHeap(arr, i, len(arr)-1) 22 | } 23 | } 24 | 25 | func adjustHeap(arr []int, minIdx int, maxIdx int) { 26 | i := minIdx 27 | for { 28 | lIdx, rIdx, idx, max := 2*i+1, 2*i+2, i, arr[i] 29 | if lIdx <= maxIdx && arr[lIdx] > max { 30 | idx, max = lIdx, arr[lIdx] 31 | } 32 | if rIdx <= maxIdx && arr[rIdx] > max { 33 | idx, max = rIdx, arr[rIdx] 34 | } 35 | if idx == i {break} 36 | arr[idx], arr[i] = arr[i], arr[idx] 37 | i = idx 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /SORT/mergesort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | arr := []int{4,3,2,1} 7 | ms(arr) 8 | fmt.Println(arr) 9 | } 10 | 11 | func ms(arr[]int) { 12 | if len(arr) == 0 || len(arr) == 1 { return } 13 | 14 | left,right := arr[:len(arr)/2], arr[len(arr)/2:] 15 | 16 | ms(left); ms(right) 17 | 18 | // merge 19 | x, y, idx, merged := 0,0,0, make([]int,len(arr)) 20 | for x < len(left) && y < len(right) { 21 | if left[x] < right[y] {merged[idx] = left[x]; x++;idx++;continue;} 22 | if left[x] >= right[y] {merged[idx] = right[y]; y++;idx++;continue;} 23 | } 24 | for x < len(left) { merged[idx] = left[x]; idx++; x++ } 25 | for y < len(right) { merged[idx] = right[y]; idx++; y++ } 26 | copy(arr, merged) 27 | } 28 | 29 | -------------------------------------------------------------------------------- /SORT/quicksort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func qs(arr []int) { 6 | if len(arr) == 0 || len(arr) == 1 { 7 | return 8 | } 9 | axis, pos := arr[0], len(arr)-1 10 | for i := pos; i >= 1; i-- { 11 | if arr[i] > axis { 12 | arr[i], arr[pos] = arr[pos], arr[i] 13 | pos-- 14 | } 15 | } 16 | arr[0], arr[pos] = arr[pos], arr[0] 17 | qs(arr[:pos]) 18 | qs(arr[pos+1:]) 19 | } 20 | 21 | func main() { 22 | arr := []int{4, 3, 2, 1} 23 | qs(arr) 24 | fmt.Println(arr) 25 | } 26 | -------------------------------------------------------------------------------- /SORT/readme.md: -------------------------------------------------------------------------------- 1 | # desc 2 | 3 | 各种常见排序方法的模板代码。 4 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # profile 2 | 3 | > https://leetcode-cn.com/xargin/ 4 | 5 | --------------------------------------------------------------------------------