├── .gitignore ├── .travis.yml ├── Algorithms ├── 0001.two-sum │ ├── README.md │ ├── two-sum.go │ └── two-sum_test.go ├── 0002.add-two-numbers │ ├── README.md │ ├── add-two-numbers.go │ └── add-two-numbers_test.go ├── 0003.longest-substring-without-repeating-characters │ ├── README.md │ ├── longest-substring-without-repeating-characters.go │ └── longest-substring-without-repeating-characters_test.go ├── 0004.median-of-two-sorted-arrays │ ├── README.md │ ├── median-of-two-sorted-arrays.go │ └── median-of-two-sorted-arrays_test.go ├── 0005.longest-palindromic-substring │ ├── README.md │ ├── longest-palindromic-substring.go │ └── longest-palindromic-substring_test.go ├── 0006.zigzag-conversion │ ├── README.md │ ├── zigzag-conversion.go │ └── zigzag-conversion_test.go ├── 0007.reverse-integer │ ├── README.md │ ├── reverse-integer.go │ └── reverse-integer_test.go ├── 0008.string-to-integer-atoi │ ├── README.md │ ├── string-to-integer-atoi.go │ └── string-to-integer-atoi_test.go ├── 0009.palindrome-number │ ├── README.md │ ├── palindrome-number.go │ └── palindrome-number_test.go ├── 0010.regular-expression-matching │ ├── README.md │ ├── regular-expression-matching.go │ └── regular-expression-matching_test.go ├── 0011.container-with-most-water │ ├── README.md │ ├── container-with-most-water.go │ └── container-with-most-water_test.go ├── 0012.integer-to-roman │ ├── README.md │ ├── integer-to-roman.go │ └── integer-to-roman_test.go ├── 0013.roman-to-integer │ ├── README.md │ ├── roman-to-integer.go │ └── roman-to-integer_test.go ├── 0014.longest-common-prefix │ ├── README.md │ ├── longest-common-prefix.go │ └── longest-common-prefix_test.go ├── 0015.3sum │ ├── 3sum.go │ ├── 3sum_test.go │ └── README.md ├── 0016.3sum-closest │ ├── 3sum-closest.go │ ├── 3sum-closest_test.go │ └── README.md ├── 0017.letter-combinations-of-a-phone-number │ ├── README.md │ ├── letter-combinations-of-a-phone-number.go │ ├── letter-combinations-of-a-phone-number_test.go │ └── phone.png ├── 0018.4sum │ ├── 4sum.go │ ├── 4sum_test.go │ └── README.md ├── 0019.remove-nth-node-from-end-of-list │ ├── README.md │ ├── remove-nth-node-from-end-of-list.go │ └── remove-nth-node-from-end-of-list_test.go ├── 0020.valid-parentheses │ ├── README.md │ ├── valid-parentheses.go │ └── valid-parentheses_test.go ├── 0021.merge-two-sorted-lists │ ├── README.md │ ├── merge-two-sorted-lists.go │ └── merge-two-sorted-lists_test.go ├── 0022.generate-parentheses │ ├── README.md │ ├── generate-parentheses.go │ └── generate-parentheses_test.go ├── 0023.merge-k-sorted-lists │ ├── README.md │ ├── merge-k-sorted-lists.go │ └── merge-k-sorted-lists_test.go ├── 0024.swap-nodes-in-pairs │ ├── README.md │ ├── swap-nodes-in-pairs.go │ └── swap-nodes-in-pairs_test.go ├── 0025.reverse-nodes-in-k-group │ ├── README.md │ ├── reverse-nodes-in-k-group.go │ └── reverse-nodes-in-k-group_test.go ├── 0026.remove-duplicates-from-sorted-array │ ├── README.md │ ├── remove-duplicates-from-sorted-array.go │ └── remove-duplicates-from-sorted-array_test.go ├── 0027.remove-element │ ├── README.md │ ├── remove-element.go │ └── remove-element_test.go ├── 0028.implement-strstr │ ├── README.md │ ├── implement-strstr.go │ └── implement-strstr_test.go ├── 0029.divide-two-integers │ ├── README.md │ ├── divide-two-integers.go │ └── divide-two-integers_test.go ├── 0030.substring-with-concatenation-of-all-words │ ├── README.md │ ├── substring-with-concatenation-of-all-words.go │ └── substring-with-concatenation-of-all-words_test.go ├── 0031.next-permutation │ ├── README.md │ ├── next-permutation.go │ └── next-permutation_test.go ├── 0032.longest-valid-parentheses │ ├── README.md │ ├── longest-valid-parentheses.go │ └── longest-valid-parentheses_test.go ├── 0033.search-in-rotated-sorted-array │ ├── README.md │ ├── search-in-rotated-sorted-array.go │ └── search-in-rotated-sorted-array_test.go ├── 0034.search-for-a-range │ ├── README.md │ ├── search-for-a-range.go │ └── search-for-a-range_test.go ├── 0035.search-insert-position │ ├── README.md │ ├── search-insert-position.go │ └── search-insert-position_test.go ├── 0036.valid-sudoku │ ├── README.md │ ├── sudoku.png │ ├── valid-sudoku.go │ └── valid-sudoku_test.go ├── 0037.sudoku-solver │ ├── 1.png │ ├── 2.png │ ├── README.md │ ├── sudoku-solver.go │ └── sudoku-solver_test.go ├── 0038.count-and-say │ ├── README.md │ ├── count-and-say.go │ └── count-and-say_test.go ├── 0039.combination-sum │ ├── README.md │ ├── combination-sum.go │ └── combination-sum_test.go ├── 0040.combination-sum-ii │ ├── 100.png │ ├── README.md │ ├── combination-sum-ii.go │ └── combination-sum-ii_test.go ├── 0041.first-missing-positive │ ├── README.md │ ├── first-missing-positive.go │ └── first-missing-positive_test.go ├── 0042.trapping-rain-water │ ├── README.md │ ├── rainwatertrap.png │ ├── trapping-rain-water.go │ └── trapping-rain-water_test.go ├── 0043.multiply-strings │ ├── README.md │ ├── multiply-strings.go │ └── multiply-strings_test.go ├── 0044.wildcard-matching │ ├── README.md │ ├── wildcard-matching.go │ └── wildcard-matching_test.go ├── 0045.jump-game-ii │ ├── README.md │ ├── jump-game-ii.go │ └── jump-game-ii_test.go ├── 0046.permutations │ ├── README.md │ ├── permutations.go │ └── permutations_test.go ├── 0047.permutations-ii │ ├── README.md │ ├── permutations-ii.go │ └── permutations-ii_test.go ├── 0048.rotate-image │ ├── README.md │ ├── rotate-image.go │ └── rotate-image_test.go ├── 0049.group-anagrams │ ├── README.md │ ├── group-anagrams.go │ └── group-anagrams_test.go ├── 0050.powx-n │ ├── README.md │ ├── powx-n.go │ └── powx-n_test.go ├── 0051.n-queens │ ├── 8-queens.png │ ├── README.md │ ├── n-queens.go │ └── n-queens_test.go ├── 0052.n-queens-ii │ ├── 8-queens.png │ ├── README.md │ ├── n-queens-ii.go │ └── n-queens-ii_test.go ├── 0053.maximum-subarray │ ├── README.md │ ├── maximum-subarray.go │ └── maximum-subarray_test.go ├── 0054.spiral-matrix │ ├── README.md │ ├── spiral-matrix.go │ └── spiral-matrix_test.go ├── 0055.jump-game │ ├── README.md │ ├── jump-game.go │ └── jump-game_test.go ├── 0056.merge-intervals │ ├── README.md │ ├── merge-intervals.go │ └── merge-intervals_test.go ├── 0057.insert-interval │ ├── README.md │ ├── insert-interval.go │ └── insert-interval_test.go ├── 0058.length-of-last-word │ ├── README.md │ ├── length-of-last-word.go │ └── length-of-last-word_test.go ├── 0059.spiral-matrix-ii │ ├── README.md │ ├── spiral-matrix-ii.go │ └── spiral-matrix-ii_test.go ├── 0060.permutation-sequence │ ├── README.md │ ├── permutation-sequence.go │ └── permutation-sequence_test.go ├── 0061.rotate-list │ ├── README.md │ ├── rotate-list.go │ └── rotate-list_test.go ├── 0062.unique-paths │ ├── README.md │ ├── robot_maze.png │ ├── unique-paths.go │ └── unique-paths_test.go ├── 0063.unique-paths-ii │ ├── README.md │ ├── unique-paths-ii.go │ └── unique-paths-ii_test.go ├── 0064.minimum-path-sum │ ├── README.md │ ├── minimum-path-sum.go │ └── minimum-path-sum_test.go ├── 0065.valid-number │ ├── README.md │ ├── valid-number.go │ └── valid-number_test.go ├── 0066.plus-one │ ├── README.md │ ├── plus-one.go │ └── plus-one_test.go ├── 0067.add-binary │ ├── README.md │ ├── add-binary.go │ └── add-binary_test.go ├── 0068.text-justification │ ├── README.md │ ├── text-justification.go │ └── text-justification_test.go ├── 0069.sqrtx │ ├── README.md │ ├── sqrtx.go │ └── sqrtx_test.go ├── 0070.climbing-stairs │ ├── README.md │ ├── climbing-stairs.go │ └── climbing-stairs_test.go ├── 0071.simplify-path │ ├── README.md │ ├── simplify-path.go │ └── simplify-path_test.go ├── 0072.edit-distance │ ├── README.md │ ├── edit-distance.go │ └── edit-distance_test.go ├── 0073.set-matrix-zeroes │ ├── README.md │ ├── set-matrix-zeroes.go │ └── set-matrix-zeroes_test.go ├── 0074.search-a-2d-matrix │ ├── README.md │ ├── search-a-2d-matrix.go │ └── search-a-2d-matrix_test.go ├── 0075.sort-colors │ ├── README.md │ ├── sort-colors.go │ └── sort-colors_test.go ├── 0076.minimum-window-substring │ ├── README.md │ ├── minimum-window-substring.go │ └── minimum-window-substring_test.go ├── 0077.combinations │ ├── README.md │ ├── combinations.go │ └── combinations_test.go ├── 0078.subsets │ ├── README.md │ ├── subsets.go │ └── subsets_test.go ├── 0079.word-search │ ├── README.md │ ├── word-search.go │ └── word-search_test.go ├── 0080.remove-duplicates-from-sorted-array-ii │ ├── README.md │ ├── remove-duplicates-from-sorted-array-ii.go │ └── remove-duplicates-from-sorted-array-ii_test.go ├── 0081.search-in-rotated-sorted-array-ii │ ├── README.md │ ├── search-in-rotated-sorted-array-ii.go │ └── search-in-rotated-sorted-array-ii_test.go ├── 0082.remove-duplicates-from-sorted-list-ii │ ├── README.md │ ├── remove-duplicates-from-sorted-list-ii.go │ └── remove-duplicates-from-sorted-list-ii_test.go ├── 0083.remove-duplicates-from-sorted-list │ ├── README.md │ ├── remove-duplicates-from-sorted-list.go │ └── remove-duplicates-from-sorted-list_test.go ├── 0084.largest-rectangle-in-histogram │ ├── README.md │ ├── histogram.png │ ├── histogram_area.png │ ├── largest-rectangle-in-histogram.go │ └── largest-rectangle-in-histogram_test.go ├── 0085.maximal-rectangle │ ├── README.md │ ├── maximal-rectangle.go │ └── maximal-rectangle_test.go ├── 0086.partition-list │ ├── README.md │ ├── partition-list.go │ └── partition-list_test.go ├── 0087.scramble-string │ ├── README.md │ ├── scramble-string.go │ └── scramble-string_test.go ├── 0088.merge-sorted-array │ ├── README.md │ ├── merge-sorted-array.go │ └── merge-sorted-array_test.go ├── 0089.gray-code │ ├── README.md │ ├── gray-code.go │ └── gray-code_test.go ├── 0090.subsets-ii │ ├── README.md │ ├── subsets-ii.go │ └── subsets-ii_test.go ├── 0091.decode-ways │ ├── README.md │ ├── decode-ways.go │ └── decode-ways_test.go ├── 0092.reverse-linked-list-ii │ ├── README.md │ ├── reverse-linked-list-ii.go │ └── reverse-linked-list-ii_test.go ├── 0093.restore-ip-addresses │ ├── README.md │ ├── restore-ip-addresses.go │ └── restore-ip-addresses_test.go ├── 0094.binary-tree-inorder-traversal │ ├── README.md │ ├── binary-tree-inorder-traversal.go │ └── binary-tree-inorder-traversal_test.go ├── 0095.unique-binary-search-trees-ii │ ├── README.md │ ├── unique-binary-search-trees-ii.go │ └── unique-binary-search-trees-ii_test.go ├── 0096.unique-binary-search-trees │ ├── README.md │ ├── unique-binary-search-trees.go │ └── unique-binary-search-trees_test.go ├── 0097.interleaving-string │ ├── README.md │ ├── interleaving-string.go │ └── interleaving-string_test.go ├── 0098.validate-binary-search-tree │ ├── README.md │ ├── validate-binary-search-tree.go │ └── validate-binary-search-tree_test.go ├── 0099.recover-binary-search-tree │ ├── README.md │ ├── recover-binary-search-tree.go │ └── recover-binary-search-tree_test.go ├── 0100.same-tree │ ├── README.md │ ├── same-tree.go │ └── same-tree_test.go ├── 0101.symmetric-tree │ ├── README.md │ ├── symmetric-tree.go │ └── symmetric-tree_test.go ├── 0102.binary-tree-level-order-traversal │ ├── README.md │ ├── binary-tree-level-order-traversal.go │ └── binary-tree-level-order-traversal_test.go ├── 0103.binary-tree-zigzag-level-order-traversal │ ├── README.md │ ├── binary-tree-zigzag-level-order-traversal.go │ └── binary-tree-zigzag-level-order-traversal_test.go ├── 0104.maximum-depth-of-binary-tree │ ├── README.md │ ├── maximum-depth-of-binary-tree.go │ └── maximum-depth-of-binary-tree_test.go ├── 0105.construct-binary-tree-from-preorder-and-inorder-traversal │ ├── README.md │ ├── construct-binary-tree-from-preorder-and-inorder-traversal.go │ └── construct-binary-tree-from-preorder-and-inorder-traversal_test.go ├── 0106.construct-binary-tree-from-inorder-and-postorder-traversal │ ├── README.md │ ├── construct-binary-tree-from-inorder-and-postorder-traversal.go │ └── construct-binary-tree-from-inorder-and-postorder-traversal_test.go ├── 0107.binary-tree-level-order-traversal-ii │ ├── README.md │ ├── binary-tree-level-order-traversal-ii.go │ └── binary-tree-level-order-traversal-ii_test.go ├── 0108.convert-sorted-array-to-binary-search-tree │ ├── README.md │ ├── convert-sorted-array-to-binary-search-tree.go │ └── convert-sorted-array-to-binary-search-tree_test.go ├── 0109.convert-sorted-list-to-binary-search-tree │ ├── 109.png │ ├── README.md │ ├── convert-sorted-list-to-binary-search-tree.go │ └── convert-sorted-list-to-binary-search-tree_test.go ├── 0110.balanced-binary-tree │ ├── README.md │ ├── balanced-binary-tree.go │ └── balanced-binary-tree_test.go ├── 0111.minimum-depth-of-binary-tree │ ├── README.md │ ├── minimum-depth-of-binary-tree.go │ └── minimum-depth-of-binary-tree_test.go ├── 0112.path-sum │ ├── README.md │ ├── path-sum.go │ └── path-sum_test.go ├── 0113.path-sum-ii │ ├── README.md │ ├── path-sum-ii.go │ └── path-sum-ii_test.go ├── 0114.flatten-binary-tree-to-linked-list │ ├── README.md │ ├── flatten-binary-tree-to-linked-list.go │ └── flatten-binary-tree-to-linked-list_test.go ├── 0115.distinct-subsequences │ ├── README.md │ ├── distinct-subsequences.go │ └── distinct-subsequences_test.go ├── 0118.pascals-triangle │ ├── README.md │ ├── pascals-triangle.go │ └── pascals-triangle_test.go ├── 0119.pascals-triangle-ii │ ├── README.md │ ├── pascals-triangle-ii.go │ └── pascals-triangle-ii_test.go ├── 0120.triangle │ ├── README.md │ ├── triangle.go │ └── triangle_test.go ├── 0121.best-time-to-buy-and-sell-stock │ ├── README.md │ ├── best-time-to-buy-and-sell-stock.go │ └── best-time-to-buy-and-sell-stock_test.go ├── 0122.best-time-to-buy-and-sell-stock-ii │ ├── README.md │ ├── best-time-to-buy-and-sell-stock-ii.go │ └── best-time-to-buy-and-sell-stock-ii_test.go ├── 0123.best-time-to-buy-and-sell-stock-iii │ ├── README.md │ ├── best-time-to-buy-and-sell-stock-iii.go │ └── best-time-to-buy-and-sell-stock-iii_test.go ├── 0124.binary-tree-maximum-path-sum │ ├── README.md │ ├── binary-tree-maximum-path-sum.go │ └── binary-tree-maximum-path-sum_test.go ├── 0125.valid-palindrome │ ├── README.md │ ├── valid-palindrome.go │ └── valid-palindrome_test.go ├── 0126.word-ladder-ii │ ├── 126.png │ ├── README.md │ ├── word-ladder-ii.go │ └── word-ladder-ii_test.go ├── 0127.word-ladder │ ├── README.md │ ├── word-ladder.go │ └── word-ladder_test.go ├── 0152.maximum-product-subarray │ ├── README.md │ ├── maximum-product-subarray.go │ └── maximum-product-subarray_test.go ├── 0153.find-minimum-in-rotated-sorted-array │ ├── README.md │ ├── find-minimum-in-rotated-sorted-array.go │ └── find-minimum-in-rotated-sorted-array_test.go ├── 0154.find-minimum-in-rotated-sorted-array-ii │ ├── README.md │ ├── find-minimum-in-rotated-sorted-array-ii.go │ └── find-minimum-in-rotated-sorted-array-ii_test.go ├── 0162.find-peak-element │ ├── README.md │ ├── find-peak-element.go │ └── find-peak-element_test.go ├── 0167.two-sum-ii-input-array-is-sorted │ ├── README.md │ ├── two-sum-ii-input-array-is-sorted.go │ └── two-sum-ii-input-array-is-sorted_test.go ├── 0169.majority-element │ ├── README.md │ ├── majority-element.go │ └── majority-element_test.go ├── 0188.best-time-to-buy-and-sell-stock-iv │ ├── README.md │ ├── best-time-to-buy-and-sell-stock-iv.go │ └── best-time-to-buy-and-sell-stock-iv_test.go ├── 0189.rotate-array │ ├── README.md │ ├── rotate-array.go │ └── rotate-array_test.go ├── 0206.reverse-linked-list │ ├── README.md │ ├── reverse-linked-list.go │ └── reverse-linked-list_test.go ├── 0209.minimum-size-subarray-sum │ ├── README.md │ ├── minimum-size-subarray-sum.go │ └── minimum-size-subarray-sum_test.go ├── 0216.combination-sum-iii │ ├── README.md │ ├── combination-sum-iii.go │ └── combination-sum-iii_test.go ├── 0217.contains-duplicate │ ├── README.md │ ├── contains-duplicate.go │ └── contains-duplicate_test.go ├── 0219.contains-duplicate-ii │ ├── README.md │ ├── contains-duplicate-ii.go │ └── contains-duplicate-ii_test.go ├── 0228.summary-ranges │ ├── README.md │ ├── summary-ranges.go │ └── summary-ranges_test.go ├── 0229.majority-element-ii │ ├── README.md │ ├── majority-element-ii.go │ └── majority-element-ii_test.go ├── 0238.product-of-array-except-self │ ├── 238.png │ ├── README.md │ ├── product-of-array-except-self.go │ └── product-of-array-except-self_test.go ├── 0268.missing-number │ ├── README.md │ ├── missing-number.go │ └── missing-number_test.go ├── 0283.move-zeroes │ ├── README.md │ ├── move-zeroes.go │ └── move-zeroes_test.go ├── 0287.find-the-duplicate-number │ ├── README.md │ ├── find-the-duplicate-number.go │ └── find-the-duplicate-number_test.go ├── 0289.game-of-life │ ├── README.md │ ├── game-of-life.go │ └── game-of-life_test.go ├── 0380.insert-delete-getrandom-o1 │ ├── README.md │ ├── insert-delete-getrandom-o1.go │ └── insert-delete-getrandom-o1_test.go ├── 0381.insert-delete-getrandom-o1-duplicates-allowed │ ├── 381.png │ ├── README.md │ ├── insert-delete-getrandom-o1-duplicates-allowed.go │ └── insert-delete-getrandom-o1-duplicates-allowed_test.go ├── 0414.third-maximum-number │ ├── README.md │ ├── third-maximum-number.go │ └── third-maximum-number_test.go ├── 0437.path-sum-iii │ ├── README.md │ ├── path-sum-iii.go │ └── path-sum-iii_test.go ├── 0442.find-all-duplicates-in-an-array │ ├── README.md │ ├── find-all-duplicates-in-an-array.go │ └── find-all-duplicates-in-an-array_test.go ├── 0448.find-all-numbers-disappeared-in-an-array │ ├── README.md │ ├── find-all-numbers-disappeared-in-an-array.go │ └── find-all-numbers-disappeared-in-an-array_test.go ├── 0485.max-consecutive-ones │ ├── README.md │ ├── max-consecutive-ones.go │ └── max-consecutive-ones_test.go ├── 0495.teemo-attacking │ ├── README.md │ ├── teemo-attacking.go │ └── teemo-attacking_test.go ├── 0526.beautiful-arrangement │ ├── README.md │ ├── beautiful-arrangement.go │ └── beautiful-arrangement_test.go ├── 0532.k-diff-pairs-in-an-array │ ├── README.md │ ├── k-diff-pairs-in-an-array.go │ └── k-diff-pairs-in-an-array_test.go ├── 0560.subarray-sum-equals-k │ ├── README.md │ ├── subarray-sum-equals-k.go │ └── subarray-sum-equals-k_test.go ├── 0561.array-partition-i │ ├── README.md │ ├── array-partition-i.go │ └── array-partition-i_test.go ├── 0565.array-nesting │ ├── README.md │ ├── array-nesting.go │ └── array-nesting_test.go ├── 0566.reshape-the-matrix │ ├── README.md │ ├── reshape-the-matrix.go │ └── reshape-the-matrix_test.go ├── 0581.shortest-unsorted-continuous-subarray │ ├── README.md │ ├── shortest-unsorted-continuous-subarray.go │ └── shortest-unsorted-continuous-subarray_test.go ├── 0605.can-place-flowers │ ├── README.md │ ├── can-place-flowers.go │ └── can-place-flowers_test.go ├── 0611.valid-triangle-number │ ├── README.md │ ├── valid-triangle-number.go │ └── valid-triangle-number_test.go ├── 0621.task-scheduler │ ├── README.md │ ├── task-scheduler.go │ └── task-scheduler_test.go ├── 0628.maximum-product-of-three-numbers │ ├── README.md │ ├── maximum-product-of-three-numbers.go │ └── maximum-product-of-three-numbers_test.go ├── 0639.decode-ways-ii │ ├── README.md │ ├── decode-ways-ii.go │ └── decode-ways-ii_test.go ├── 0643.maximum-average-subarray-i │ ├── README.md │ ├── maximum-average-subarray-i.go │ └── maximum-average-subarray-i_test.go ├── 0660.remove-9 │ ├── README.md │ ├── remove-9.go │ └── remove-9_test.go ├── 0661.image-smoother │ ├── README.md │ ├── image-smoother.go │ └── image-smoother_test.go └── 0667.beautiful-arrangement-ii │ ├── README.md │ ├── beautiful-arrangement-ii.go │ └── beautiful-arrangement-ii_test.go ├── LICENSE ├── Makefile ├── README.md ├── README_HEAD.md ├── README_TAIL.md ├── helper.v4 ├── Makefile ├── README.md ├── data.go ├── leetcode.go ├── main.go ├── net.go ├── problem.go ├── readme.go └── util.go ├── kit ├── ListNode.go ├── ListNode_test.go ├── TreeNode.go └── TreeNode_test.go ├── leetcode.json ├── notes ├── DynamicProgramming │ └── README.md ├── README.md └── Tree │ └── README.md └── test.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | *.cookie 16 | .vscode/ 17 | *.toml 18 | helper -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.9.x 5 | 6 | # whitelist 7 | branches: 8 | only: 9 | - master 10 | - stable 11 | 12 | script: 13 | - go get -t -v ./... 14 | - go vet ./... 15 | - bash ./test.sh 16 | 17 | after_success: 18 | - bash <(curl -s https://codecov.io/bash) 19 | 20 | notifications: 21 | webhooks: https://hooks.pubu.im/services/3wp9q4yqlzm8fxr -------------------------------------------------------------------------------- /Algorithms/0001.two-sum/README.md: -------------------------------------------------------------------------------- 1 | # [1. Two Sum](https://leetcode.com/problems/two-sum/) 2 | 3 | ## 题目 4 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 5 | 6 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 7 | 8 | Example: 9 | ``` 10 | Given nums = [2, 7, 11, 15], target = 9, 11 | 12 | Because nums[0] + nums[1] = 2 + 7 = 9, 13 | return [0, 1]. 14 | ``` 15 | ## 解题思路 16 | ``` 17 | a + b = target 18 | ``` 19 | 也可以看成是 20 | ``` 21 | a = target - b 22 | ``` 23 | 24 | 在`map[整数]整数的序号`中,可以查询到a的序号。这样就不用嵌套两个for循环了。 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algorithms/0001.two-sum/two-sum.go: -------------------------------------------------------------------------------- 1 | package Problem0001 2 | 3 | func twoSum(nums []int, target int) []int { 4 | // m 负责保存map[整数]整数的序列号 5 | m := make(map[int]int, len(nums)) 6 | 7 | // 通过 for 循环,获取b的序列号 8 | for i, b := range nums { 9 | // 通过查询map,获取a = target - b的序列号 10 | if j, ok := m[target-b]; ok { 11 | // ok 为 true 12 | // 说明在i之前,存在nums[j] == a 13 | return []int{j, i} 14 | // 注意,顺序是j,i,因为j 4 -> 3) + (5 -> 6 -> 4) 9 | Output: 7 -> 0 -> 8 10 | 11 | ## 解题思路 12 | (2 -> 4 -> 3)是 342 13 | 14 | (5 -> 6 -> 4)是 465 15 | 16 | (7 -> 0 -> 8)是 807 17 | 18 | 342 + 465 = 807 19 | 20 | 所以,题目的本意是,把整数换了一种表达方式后,实现其加法。 21 | 22 | 设计程序时候,需要处理的点有 23 | 1. 位上的加法,需要处理进位问题 24 | 1. 如何进入下一位运算 25 | 1. 按位相加结束后,也还需要处理进位问题。 26 | 27 | ## 总结 28 | 读懂题意后,按步骤实现题目要求。 -------------------------------------------------------------------------------- /Algorithms/0003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.go: -------------------------------------------------------------------------------- 1 | package Problem0003 2 | 3 | func lengthOfLongestSubstring(s string) int { 4 | // location[s[i]] == j 表示: 5 | // s中第i个字符串,上次出现在s的j位置,所以,在s[j+1:i]中没有s[i] 6 | // location[s[i]] == -1 表示: s[i] 在s中第一次出现 7 | location := [256]int{} // 只有256长是因为,假定输入的字符串只有ASCII字符 8 | for i := range location { 9 | location[i] = -1 // 先设置所有的字符都没有见过 10 | } 11 | 12 | maxLen, left := 0, 0 13 | 14 | for i := 0; i < len(s); i++ { 15 | // 说明s[i]已经在s[left:i+1]中重复了 16 | // 并且s[i]上次出现的位置在location[s[i]] 17 | if location[s[i]] >= left { 18 | left = location[s[i]] + 1 // 在s[left:i+1]中去除s[i]字符及其之前的部分 19 | } else if i+1-left > maxLen { 20 | // fmt.Println(s[left:i+1]) 21 | maxLen = i + 1 - left 22 | } 23 | location[s[i]] = i 24 | } 25 | 26 | return maxLen 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/0004.median-of-two-sorted-arrays/README.md: -------------------------------------------------------------------------------- 1 | # [4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) 2 | 3 | ## 题目 4 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 5 | 6 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 7 | 8 | Example 1: 9 | ``` 10 | nums1 = [1, 3] 11 | nums2 = [2] 12 | The median is 2.0 13 | ``` 14 | Example 2: 15 | ``` 16 | nums1 = [1, 2] 17 | nums2 = [3, 4] 18 | The median is (2 + 3)/2 = 2.5 19 | ``` 20 | ## 解题思路 21 | 输入两个已经排序好的整数切片,合并两个切片,返回合并后切片的中位数。 22 | 23 | 所以,题目的关键是,如何高效地合并切片。 24 | 25 | ## 总结 26 | 分步骤完成程序 27 | 28 | -------------------------------------------------------------------------------- /Algorithms/0006.zigzag-conversion/zigzag-conversion.go: -------------------------------------------------------------------------------- 1 | package Problem0006 2 | 3 | import ( 4 | "bytes" 5 | ) 6 | 7 | func convert(s string, numRows int) string { 8 | if numRows == 1 || len(s) <= numRows { 9 | return s 10 | } 11 | 12 | res := bytes.Buffer{} 13 | // p pace 步距 14 | p := numRows*2 - 2 15 | 16 | // 处理第一行 17 | for i := 0; i < len(s); i += p { 18 | res.WriteByte(s[i]) 19 | } 20 | 21 | // 处理中间的行 22 | for r := 1; r <= numRows-2; r++ { 23 | // 添加r行的第一个字符 24 | res.WriteByte(s[r]) 25 | 26 | for k := p; k-r < len(s); k += p { 27 | res.WriteByte(s[k-r]) 28 | if k+r < len(s) { 29 | res.WriteByte(s[k+r]) 30 | } 31 | } 32 | } 33 | 34 | // 处理最后一行 35 | for i := numRows - 1; i < len(s); i += p { 36 | res.WriteByte(s[i]) 37 | } 38 | 39 | return res.String() 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/0007.reverse-integer/README.md: -------------------------------------------------------------------------------- 1 | # [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/) 2 | 3 | ## 题目 4 | Reverse digits of an integer. 5 | ``` 6 | Example1: x = 123, return 321 7 | Example2: x = -123, return -321 8 | ``` 9 | ## 解题思路 10 | 详见 程序注释 -------------------------------------------------------------------------------- /Algorithms/0007.reverse-integer/reverse-integer.go: -------------------------------------------------------------------------------- 1 | package Problem0007 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func reverse(x int) int { 8 | sign := 1 9 | 10 | // 处理负数 11 | if x < 0 { 12 | sign = -1 13 | x = -1 * x 14 | } 15 | 16 | res := 0 17 | for x > 0 { 18 | // 取出x的末尾 19 | temp := x % 10 20 | // 放入 res 的开头 21 | res = res*10 + temp 22 | // x 去除末尾 23 | x = x / 10 24 | } 25 | 26 | // 还原 x 的符号到 res 27 | res = sign * res 28 | 29 | // 处理 res 的溢出问题 30 | if res > math.MaxInt32 || res < math.MinInt32 { 31 | res = 0 32 | } 33 | 34 | return res 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0008.string-to-integer-atoi/README.md: -------------------------------------------------------------------------------- 1 | # [8. String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) 2 | 3 | ## 题目 4 | Implement atoi to convert a string to an integer. 5 | 6 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 7 | 8 | ## 解题思路 9 | 转换并不难,难得的是,处理各种奇葩的输入。详见程序注释。 10 | 11 | ## 总结 12 | 良好的单元测试真的很重要。 13 | -------------------------------------------------------------------------------- /Algorithms/0009.palindrome-number/README.md: -------------------------------------------------------------------------------- 1 | # [9. Palindrome Number](https://leetcode.com/problems/palindrome-number/) 2 | 3 | ## 题目 4 | Determine whether an integer is a palindrome. Do this without extra space. 5 | 6 | ## 解题思路 7 | 检查一个整数是否是回文。 8 | 9 | 先把整数转换成字符串,再检查字符串是否是回文。 10 | -------------------------------------------------------------------------------- /Algorithms/0009.palindrome-number/palindrome-number.go: -------------------------------------------------------------------------------- 1 | package Problem0009 2 | 3 | import "strconv" 4 | 5 | func isPalindrome(x int) bool { 6 | if x < 0 { 7 | return false 8 | } 9 | 10 | s := strconv.Itoa(x) 11 | 12 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 13 | if s[i] != s[j] { 14 | return false 15 | } 16 | } 17 | 18 | return true 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/0009.palindrome-number/palindrome-number_test.go: -------------------------------------------------------------------------------- 1 | package Problem0009 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type question struct { 10 | p para 11 | a ans 12 | } 13 | 14 | type para struct { 15 | one int 16 | } 17 | 18 | type ans struct { 19 | one bool 20 | } 21 | 22 | func Test_Problem0009(t *testing.T) { 23 | ast := assert.New(t) 24 | 25 | qs := []question{ 26 | question{ 27 | p: para{ 28 | one: 12321, 29 | }, 30 | a: ans{ 31 | one: true, 32 | }, 33 | }, 34 | question{ 35 | p: para{ 36 | one: 1231, 37 | }, 38 | a: ans{ 39 | one: false, 40 | }, 41 | }, 42 | question{ 43 | p: para{ 44 | one: -12321, 45 | }, 46 | a: ans{ 47 | one: false, 48 | }, 49 | }, 50 | } 51 | 52 | for _, q := range qs { 53 | a, p := q.a, q.p 54 | ast.Equal(a.one, isPalindrome(p.one), "输入:%v", p) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Algorithms/0010.regular-expression-matching/README.md: -------------------------------------------------------------------------------- 1 | # [10. Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) 2 | 3 | ## 题目 4 | Implement regular expression matching with support for '.' and '*'. 5 | ``` 6 | '.' Matches any single character. 7 | '*' Matches zero or more of the preceding element. 8 | 9 | The matching should cover the entire input string (not partial). 10 | 11 | The function prototype should be: 12 | bool isMatch(const char *s, const char *p) 13 | 14 | Some examples: 15 | 16 | isMatch("aa","a") ? false 17 | isMatch("aa","aa") ? true 18 | isMatch("aaa","aa") ? false 19 | isMatch("aa", "a*") ? true 20 | isMatch("aa", ".*") ? true 21 | isMatch("ab", ".*") ? true 22 | isMatch("aab", "c*a*b") ? true 23 | ``` 24 | 25 | ## 解题思路 26 | 27 | 28 | ## 总结 29 | 30 | 动态规划问题。 -------------------------------------------------------------------------------- /Algorithms/0011.container-with-most-water/README.md: -------------------------------------------------------------------------------- 1 | # [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/) 2 | 3 | ## 题目 4 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | 6 | 就是说,x轴上在1,2,...,n点上有许多垂直的线段,长度依次是a1, a2, ..., an。找出两条线段,使他们和x抽围成的面积最大。面积公式是 Min(ai, aj) X |j - i| 7 | 8 | ## 解题思路 9 | 穷举法是O(n^2)的复杂度,会触发leetcode的时间限制。 10 | 11 | O(n)的复杂度的解法是,保持两个指针i,j;分别指向长度数组的首尾。如果ai 小于aj,则移动i向后(i++)。反之,移动j向前(j--)。如果当前的area大于了所记录的area,替换之。这个想法的基础是,如果i的长度小于j,无论如何移动j,短板在i,不可能找到比当前记录的area更大的值了,只能通过移动i来找到新的可能的更大面积。 12 | -------------------------------------------------------------------------------- /Algorithms/0011.container-with-most-water/container-with-most-water.go: -------------------------------------------------------------------------------- 1 | package Problem0011 2 | 3 | func maxArea(height []int) int { 4 | // 从两端开始寻找,至少保证了宽度是最大值 5 | i, j := 0, len(height)-1 6 | max := 0 7 | 8 | for i < j { 9 | a, b := height[i], height[j] 10 | h := min(a, b) 11 | 12 | area := h * (j - i) 13 | if max < area { 14 | max = area 15 | } 16 | 17 | // 朝着area具有变大的可能性方向变化。 18 | if a < b { 19 | i++ 20 | } else { 21 | j-- 22 | } 23 | } 24 | 25 | return max 26 | } 27 | 28 | func min(i, j int) int { 29 | if i <= j { 30 | return i 31 | } 32 | return j 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/0011.container-with-most-water/container-with-most-water_test.go: -------------------------------------------------------------------------------- 1 | package Problem0011 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type question struct { 10 | para 11 | ans 12 | } 13 | 14 | // para 是参数 15 | // one 代表第一个参数 16 | type para struct { 17 | one []int 18 | } 19 | 20 | // ans 是答案 21 | // one 代表第一个答案 22 | type ans struct { 23 | one int 24 | } 25 | 26 | func Test_Problem0011(t *testing.T) { 27 | ast := assert.New(t) 28 | 29 | qs := []question{ 30 | question{ 31 | para{[]int{1, 2, 3, 1}}, 32 | ans{3}, 33 | }, 34 | question{ 35 | para{[]int{1, 3, 6, 4, 3, 5, 6, 7, 8, 9, 7, 5, 4, 3, 2, 1}}, 36 | ans{48}, 37 | }, 38 | question{ 39 | para{[]int{1, 1}}, 40 | ans{1}, 41 | }, 42 | } 43 | 44 | for _, q := range qs { 45 | a, p := q.ans, q.para 46 | 47 | ast.Equal(a.one, maxArea(p.one), "输入:%v", p) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/0012.integer-to-roman/integer-to-roman.go: -------------------------------------------------------------------------------- 1 | package Problem0012 2 | 3 | func intToRoman(num int) string { 4 | 5 | d := [4][]string{ 6 | []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, 7 | []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, 8 | []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, 9 | []string{"", "M", "MM", "MMM"}, 10 | } 11 | return d[3][num/1000] + 12 | d[2][num/100%10] + 13 | d[1][num/10%10] + 14 | d[0][num%10] 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/0012.integer-to-roman/integer-to-roman_test.go: -------------------------------------------------------------------------------- 1 | package Problem0012 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type question struct { 10 | para 11 | ans 12 | } 13 | 14 | // para 是参数 15 | // one 代表第一个参数 16 | type para struct { 17 | one int 18 | } 19 | 20 | // ans 是答案 21 | // one 代表第一个答案 22 | type ans struct { 23 | one string 24 | } 25 | 26 | func Test_Problem0012(t *testing.T) { 27 | ast := assert.New(t) 28 | 29 | qs := []question{ 30 | question{ 31 | para{39}, 32 | ans{"XXXIX"}, 33 | }, 34 | question{ 35 | para{1888}, 36 | ans{"MDCCCLXXXVIII"}, 37 | }, 38 | question{ 39 | para{1976}, 40 | ans{"MCMLXXVI"}, 41 | }, 42 | question{ 43 | para{3999}, 44 | ans{"MMMCMXCIX"}, 45 | }, 46 | } 47 | 48 | for _, q := range qs { 49 | a, p := q.ans, q.para 50 | 51 | ast.Equal(a.one, intToRoman(p.one), "输入:%v", p) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Algorithms/0013.roman-to-integer/README.md: -------------------------------------------------------------------------------- 1 | # [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/) 2 | 3 | ## 题目 4 | Given a roman numeral, convert it to an integer. 5 | 6 | Input is guaranteed to be within the range from 1 to 3999. 7 | 8 | ## 解题思路 9 | 这一题是[12. Integer to Roman](./Algorithms/0012.integer-to-roman)的一个逆转换。~~一样的解题思路~~ 10 | 11 | 此题,最关键的信息是 12 | > 右加左减,左减数字必须为一位,比如8写成VIII,而非IIX。 13 | 14 | 解题思路 15 | 1. 从右往左处理字符串。 16 | 1. 当前字符代表的数字,小于右边字符的时候,总体减去当前字符代表的数字。 17 | 1. 否则,总体加上当前字符代表的数字。 18 | ## 总结 19 | 抓住关键信息,避免思维定式。 -------------------------------------------------------------------------------- /Algorithms/0013.roman-to-integer/roman-to-integer.go: -------------------------------------------------------------------------------- 1 | package Problem0013 2 | 3 | func romanToInt(s string) int { 4 | res := 0 5 | m := map[byte]int{ 6 | 'I': 1, 7 | 'V': 5, 8 | 'X': 10, 9 | 'L': 50, 10 | 'C': 100, 11 | 'D': 500, 12 | 'M': 1000, 13 | } 14 | 15 | last := 0 16 | for i := len(s) - 1; i >= 0; i-- { 17 | temp := m[s[i]] 18 | 19 | sign := 1 20 | if temp < last { 21 | //小数在大数的左边,要减去小数 22 | sign = -1 23 | } 24 | 25 | res += sign * temp 26 | 27 | last = temp 28 | } 29 | 30 | return res 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/0014.longest-common-prefix/README.md: -------------------------------------------------------------------------------- 1 | # [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) 2 | 3 | ## 题目 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | 6 | ## 解题思路 7 | 1. 8 | 9 | ## 总结 10 | 11 | 12 | -------------------------------------------------------------------------------- /Algorithms/0014.longest-common-prefix/longest-common-prefix.go: -------------------------------------------------------------------------------- 1 | package Problem0014 2 | 3 | func longestCommonPrefix(strs []string) string { 4 | short := shortest(strs) 5 | 6 | for i, r := range short { 7 | for j := 0; j < len(strs); j++ { 8 | if strs[j][i] != byte(r) { 9 | return strs[j][:i] 10 | } 11 | } 12 | } 13 | 14 | return short 15 | } 16 | 17 | func shortest(strs []string) string { 18 | if len(strs) == 0 { 19 | return "" 20 | } 21 | 22 | res := strs[0] 23 | for _, s := range strs { 24 | if len(res) > len(s) { 25 | res = s 26 | } 27 | } 28 | 29 | return res 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/0015.3sum/README.md: -------------------------------------------------------------------------------- 1 | # [15. 3Sum](https://leetcode.com/problems/3sum/) 2 | 3 | ## 题目 4 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 5 | 6 | Note: The solution set must not contain duplicate triplets. 7 | ``` 8 | For example, given array S = [-1, 0, 1, 2, -1, -4], 9 | 10 | A solution set is: 11 | [ 12 | [-1, 0, 1], 13 | [-1, -1, 2] 14 | ] 15 | ``` 16 | ## 解题思路 17 | 穷举法无法通过时间限制 18 | 19 | 详见代码 20 | -------------------------------------------------------------------------------- /Algorithms/0016.3sum-closest/3sum-closest.go: -------------------------------------------------------------------------------- 1 | package Problem0016 2 | 3 | import ( 4 | "math" 5 | "sort" 6 | ) 7 | 8 | func threeSumClosest(nums []int, target int) int { 9 | // 排序后,可以按规律查找 10 | sort.Ints(nums) 11 | res, delta := 0, math.MaxInt64 12 | 13 | for i := range nums { 14 | // 避免重复计算 15 | if i > 0 && nums[i] == nums[i-1] { 16 | continue 17 | } 18 | 19 | l, r := i+1, len(nums)-1 20 | 21 | for l < r { 22 | s := nums[i] + nums[l] + nums[r] 23 | switch { 24 | case s < target: 25 | l++ 26 | if delta > target-s { 27 | delta = target - s 28 | res = s 29 | } 30 | case s > target: 31 | r-- 32 | if delta > s-target { 33 | delta = s - target 34 | res = s 35 | } 36 | default: 37 | return s 38 | } 39 | } 40 | } 41 | 42 | return res 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/0016.3sum-closest/README.md: -------------------------------------------------------------------------------- 1 | # [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/) 2 | 3 | ## 题目 4 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 5 | ``` 6 | For example, given array S = {-1 2 1 -4}, and target = 1. 7 | 8 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 9 | ``` 10 | ## 解题思路 11 | 这一题和15题的思路基本一致。 12 | 13 | ## 总结 14 | 15 | 16 | -------------------------------------------------------------------------------- /Algorithms/0017.letter-combinations-of-a-phone-number/README.md: -------------------------------------------------------------------------------- 1 | # [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) 2 | 3 | ## 题目 4 | Given a digit string, return all possible letter combinations that the number could represent. 5 | 6 | A mapping of digit to letters (just like on the telephone buttons) is given below. 7 | ![手机键盘](phone.png) 8 | ``` 9 | Input:Digit string "23" 10 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] 11 | ``` 12 | **Note**: 13 | Although the above answer is in lexicographical order, your answer could be in any order you want. 14 | 15 | ## 解题思路 16 | 见程序注释 17 | -------------------------------------------------------------------------------- /Algorithms/0017.letter-combinations-of-a-phone-number/phone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0017.letter-combinations-of-a-phone-number/phone.png -------------------------------------------------------------------------------- /Algorithms/0018.4sum/README.md: -------------------------------------------------------------------------------- 1 | # [18. 4Sum](https://leetcode.com/problems/4sum/) 2 | 3 | ## 题目 4 | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 5 | 6 | Note: The solution set must not contain duplicate quadruplets. 7 | ``` 8 | For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. 9 | 10 | A solution set is: 11 | [ 12 | [-1, 0, 0, 1], 13 | [-2, -1, 1, 2], 14 | [-2, 0, 0, 2] 15 | ] 16 | ``` 17 | ## 解题思路 18 | 我解答这一题的思路,和[15. 3Sum](./Algorithms/0015.3sum)的思路一样的,就是多套了一层循环而已。 19 | 20 | ## 总结 21 | 未知的问题,可以转换成已知的问题来求解。 -------------------------------------------------------------------------------- /Algorithms/0019.remove-nth-node-from-end-of-list/README.md: -------------------------------------------------------------------------------- 1 | # [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) 2 | 3 | ## 题目 4 | Given a linked list, remove the nth node from the end of list and return its head. 5 | 6 | For example, 7 | ``` 8 | Given linked list: 1->2->3->4->5, and n = 2. 9 | After removing the second node from the end, the linked list becomes 1->2->3->5. 10 | ``` 11 | **Note**: 12 | 1. Given n will always be valid. 不存在链的长度 0 说明"([{"的数量,大于")]}"的数量 19 | if len(*s) > 0 { 20 | return false 21 | } 22 | 23 | return true 24 | } 25 | 26 | var matching = map[rune]rune{ 27 | ')': '(', 28 | ']': '[', 29 | '}': '{', 30 | } 31 | 32 | type stack []rune 33 | 34 | func (s *stack) push(b rune) { 35 | *s = append(*s, b) 36 | } 37 | 38 | func (s *stack) pop() (rune, bool) { 39 | if len(*s) > 0 { 40 | res := (*s)[len(*s)-1] 41 | *s = (*s)[:len(*s)-1] 42 | return res, true 43 | } 44 | return 0, false 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/0021.merge-two-sorted-lists/README.md: -------------------------------------------------------------------------------- 1 | # [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) 2 | 3 | ## 题目 4 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 5 | 6 | ## 解题思路 7 | 把两个排序好的链合并,要求合并后依然是排序好的。结题步骤如下: 8 | 1. 先处理其中一条链为nil的情况,直接返回另一条链,这样可以简化后面的判断条件。 9 | 1. 设置好链接头head和用于移动节点指针node 10 | 1. 利用for循环反复比较,每次选取较小的节点,放在node.Next 11 | 1. 处理l1或l2中剩余的节点 12 | ## 总结 13 | 合理地安排步骤,可以有效地减轻后面的判断条件和处理步骤,让整个函数更清晰易懂。 -------------------------------------------------------------------------------- /Algorithms/0022.generate-parentheses/generate-parentheses.go: -------------------------------------------------------------------------------- 1 | package Problem0022 2 | 3 | func generateParenthesis(n int) []string { 4 | res := []string{} 5 | gen(n, n, "", &res) 6 | return res 7 | } 8 | 9 | func gen(left, right int, substr string, res *[]string) { 10 | // 成功找到一个解 11 | if left == 0 && right == 0 { 12 | *res = append(*res, substr) 13 | return 14 | } 15 | 16 | // 因为左括号不用担心匹配问题,只要还有左括号,就可以随便加。 17 | if left > 0 { 18 | gen(left-1, right, substr+"(", res) 19 | } 20 | 21 | // 右括号只有在左括号剩余较少的前提下,才能加 22 | if right > 0 && left < right { 23 | gen(left, right-1, substr+")", res) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0023.merge-k-sorted-lists/README.md: -------------------------------------------------------------------------------- 1 | # [23. Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) 2 | 3 | ## 题目 4 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 5 | 6 | ## 解题思路 7 | 最先想到的方案是,依次合并res=merge(res, lists[i]),这个方案的坏处是需要合并两个长度相差很大的链。 8 | LeetCode上最快的解决方法是,借鉴了[归并排序](https://zh.wikipedia.org/wiki/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F)的思想,让lists中临近的list先两两合并,再让新生成的lists中的临近list两两合并,直到合并完成。 9 | 10 | ## 总结 11 | -------------------------------------------------------------------------------- /Algorithms/0024.swap-nodes-in-pairs/README.md: -------------------------------------------------------------------------------- 1 | # [24. Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) 2 | 3 | ## 题目 4 | Given a linked list, swap every two adjacent nodes and return its head. 5 | 6 | For example, 7 | Given 1->2->3->4, you should return the list as 2->1->4->3. 8 | 9 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 10 | 11 | ## 解题思路 12 | 利用递归,可以简洁明了地完成程序。详见程序注释。 13 | 14 | ## 总结 15 | 16 | 17 | -------------------------------------------------------------------------------- /Algorithms/0024.swap-nodes-in-pairs/swap-nodes-in-pairs.go: -------------------------------------------------------------------------------- 1 | package Problem0024 2 | 3 | // ListNode ListNode 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | func swapPairs(head *ListNode) *ListNode { 10 | if head == nil || head.Next == nil { 11 | return head 12 | } 13 | 14 | // 让temp指向head.Next节点 15 | temp := head.Next 16 | // 让head.Next指向转换好了temp.Next节点 17 | head.Next = swapPairs(temp.Next) 18 | // 让temp.Next指向head节点 19 | temp.Next = head 20 | // temp成为新的head节点 21 | 22 | return temp 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/0025.reverse-nodes-in-k-group/README.md: -------------------------------------------------------------------------------- 1 | # [25. Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) 2 | 3 | ## 题目 4 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 5 | 6 | k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 7 | 8 | You may not alter the values in the nodes, only nodes itself may be changed. 9 | 10 | Only constant memory is allowed. 11 | 12 | For example, 13 | Given this linked list: 1->2->3->4->5 14 | 15 | For k = 2, you should return: 2->1->4->3->5 16 | 17 | For k = 3, you should return: 3->2->1->4->5 18 | 19 | ## 解题思路 20 | 题目要求,把一条链上的每k个节点进行逆转,不足k个的末尾,则不需要逆转。 21 | 22 | 详见注释 23 | 24 | ## 总结 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algorithms/0026.remove-duplicates-from-sorted-array/README.md: -------------------------------------------------------------------------------- 1 | # [26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) 2 | 3 | ## 题目 4 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 5 | 6 | Do not allocate extra space for another array, you must do this in place with constant memory. 7 | 8 | For example, 9 | Given input array nums = [1,1,2], 10 | 11 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 12 | 13 | ## 解题思路 14 | 题目要求原地删除重复的元素。并返回没有重复元素的切片的长度。 15 | 16 | ## 总结 17 | 18 | 19 | -------------------------------------------------------------------------------- /Algorithms/0026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.go: -------------------------------------------------------------------------------- 1 | package Problem0026 2 | 3 | func removeDuplicates(nums []int) int { 4 | if len(nums) <= 1 { 5 | return len(nums) 6 | } 7 | 8 | res := 1 9 | i := 1 10 | for ; i < len(nums); i++ { 11 | if nums[i] == nums[i-1] { 12 | continue 13 | } 14 | if res != i { 15 | nums[res] = nums[i] 16 | } 17 | 18 | res++ 19 | } 20 | 21 | return res 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/0027.remove-element/README.md: -------------------------------------------------------------------------------- 1 | # [27. Remove Element](https://leetcode.com/problems/remove-element/) 2 | 3 | ## 题目 4 | Given an array and a value, remove all instances of that value in place and return the new length. 5 | 6 | Do not allocate extra space for another array, you must do this in place with constant memory. 7 | 8 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 9 | 10 | Example: 11 | Given input array nums = [3,2,2,3], val = 3 12 | 13 | Your function should return length = 2, with the first two elements of nums being 2. 14 | 15 | ## 解题思路 16 | 把指定的值,丢到切片尾部,可以减少交换的次数。 17 | 18 | ## 总结 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/0027.remove-element/remove-element.go: -------------------------------------------------------------------------------- 1 | package Problem0027 2 | 3 | func removeElement(nums []int, val int) int { 4 | // j指向最后一个不为val的位置 5 | // i指向第一个值为val的位置 6 | i, j := 0, len(nums)-1 7 | for { 8 | for i < len(nums) && nums[i] != val { 9 | i++ 10 | } 11 | 12 | for j >= 0 && nums[j] == val { 13 | j-- 14 | } 15 | 16 | if i >= j { 17 | break 18 | } 19 | 20 | nums[i], nums[j] = nums[j], nums[i] 21 | } 22 | 23 | return i 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/0028.implement-strstr/README.md: -------------------------------------------------------------------------------- 1 | # [28. Implement strStr()](https://leetcode.com/problems/implement-strstr/) 2 | 3 | ## 题目 4 | Implement strStr(). 5 | 6 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 7 | 8 | ## 解题思路 9 | 依次对比查找 10 | 11 | ## 总结 12 | 13 | 14 | -------------------------------------------------------------------------------- /Algorithms/0028.implement-strstr/implement-strstr.go: -------------------------------------------------------------------------------- 1 | package Problem0028 2 | 3 | func strStr(haystack string, needle string) int { 4 | hlen, nlen := len(haystack), len(needle) 5 | // 当hlen等于nlen的时候,需要i == 0 6 | for i := 0; i <= hlen-nlen; i++ { 7 | if haystack[i:i+nlen] == needle { 8 | return i 9 | } 10 | } 11 | 12 | return -1 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/0029.divide-two-integers/README.md: -------------------------------------------------------------------------------- 1 | # [29. Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) 2 | 3 | ## 题目 4 | Divide two integers without using multiplication, division and mod operator. 5 | 6 | If it is overflow, return MAX_INT. 7 | 8 | ## 解题思路 9 | 不能使用乘法,除法和取余运算,编写一个除法函数。大的步骤是 10 | 1. 取出两个数的符号和绝对值 11 | 1. 使用绝对值做除法 12 | 1. 还原结果的符号 13 | 1. 检查是否溢出 14 | 15 | 其中,使用绝对值做除法是重点,思路参考程序注释。 16 | 17 | ## 总结 18 | 递归果然简洁有力 -------------------------------------------------------------------------------- /Algorithms/0030.substring-with-concatenation-of-all-words/README.md: -------------------------------------------------------------------------------- 1 | # [30. Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) 2 | 3 | ## 题目 4 | You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. 5 | ``` 6 | For example, given: 7 | s: "barfoothefoobarman" 8 | words: ["foo", "bar"] 9 | ``` 10 | You should return the indices: [0,9]. 11 | (order does not matter). 12 | 13 | ## 解题思路 14 | words中会包含重复的word 15 | 16 | 详见程序注释。 17 | ## 总结 18 | 19 | 20 | -------------------------------------------------------------------------------- /Algorithms/0031.next-permutation/next-permutation.go: -------------------------------------------------------------------------------- 1 | package Problem0031 2 | 3 | import "sort" 4 | 5 | func nextPermutation(nums []int) { 6 | var i int 7 | length := len(nums) 8 | 9 | if length <= 1 { 10 | return 11 | } 12 | 13 | for i = length - 1; i >= 1; i-- { 14 | if nums[i] > nums[i-1] { 15 | break 16 | } 17 | } 18 | 19 | if i > 0 { 20 | sort.Ints(nums[i:]) 21 | for j := i - 1; j < length; j++ { 22 | if nums[j] > nums[i-1] { 23 | nums[i-1], nums[j] = nums[j], nums[i-1] 24 | return 25 | } 26 | } 27 | } 28 | 29 | sort.Ints(nums) 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/0032.longest-valid-parentheses/README.md: -------------------------------------------------------------------------------- 1 | # [32. Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/) 2 | 3 | ## 题目 4 | Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring. 5 | 6 | For `"(()"`, the longest valid parentheses substring is `"()"`, which has length = 2. 7 | 8 | Another example is `")()())"`, where the longest valid parentheses substring is `"()()"`, which has length = 4. 9 | 10 | ## 解题思路 11 | 1.记录每个符号的状态,`(`一律对应于`0`;`)`如果能够和前面的配上对,就记录为`2`,否则,记录为`0` 12 | ``` 13 | ) ( ( ) ( ) ) ) ( ( ( ( ( ) ) ) ) ( 14 | ``` 15 | 形成记录 16 | ``` 17 | 0 0 0 2 0 2 2 0 0 0 0 0 0 2 2 2 2 0 18 | ``` 19 | 20 | 2.从左往右检查record,如果record[i]==2,record[j]==0,且record[j+1:i]中没有0,则record[i]=1,record[j]=1,那么,上面的record就变成了 21 | ``` 22 | 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 23 | ``` 24 | 3.统计record中,最多的连续为1的次数,就是结果。 25 | ## 总结 26 | 27 | 根据记录统计,往往是最清晰的 28 | -------------------------------------------------------------------------------- /Algorithms/0032.longest-valid-parentheses/longest-valid-parentheses.go: -------------------------------------------------------------------------------- 1 | package Problem0032 2 | 3 | func longestValidParentheses(s string) int { 4 | var left, max, temp int 5 | record := make([]int, len(s)) 6 | 7 | // 统计Record 8 | for i, b := range s { 9 | if b == '(' { 10 | left++ 11 | } else if left > 0 { 12 | left-- 13 | record[i] = 2 14 | } 15 | } 16 | 17 | // 修改record 18 | for i := 0; i < len(record); i++ { 19 | if record[i] == 2 { 20 | j := i - 1 21 | for record[j] != 0 { 22 | j-- 23 | } 24 | record[i], record[j] = 1, 1 25 | } 26 | } 27 | 28 | // 统计结果 29 | for _, r := range record { 30 | if r == 0 { 31 | temp = 0 32 | continue 33 | } 34 | 35 | temp++ 36 | if temp > max { 37 | max = temp 38 | } 39 | } 40 | 41 | return max 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/0033.search-in-rotated-sorted-array/README.md: -------------------------------------------------------------------------------- 1 | # [33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) 2 | 3 | ## 题目 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | 6 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 7 | 8 | You are given a target value to search. If found in the array return its index, otherwise return -1. 9 | 10 | You may assume no duplicate exists in the array. 11 | 12 | ## 解题思路 13 | 先假设old = [0, 1, 2, 4, 5, 6, 7],利用二分查找法,很容易可以`5`的索引号,当old变换成了new = [4, 5, 6, 7, 0, 1, 2]以后,同样可以使用二分查找法,因为old和new中的元素有明确的对应关系 14 | 15 | old[i] == new[j],只要i和j满足关系式 16 | ```go 17 | j=i+4 18 | if j > len(old) { 19 | j -= len(old) 20 | } 21 | ``` 22 | 其中,4 = old中的最大值在new中的索引号 + 1 23 | 24 | 所以,如果我们手中只有new,我们可以假装自己还是在对old使用二分查找法,当需要获取old[i]的值进行比较判断的时候,使用new[j]的值替代即可。 25 | 26 | 27 | ## 总结 28 | 本题是二分查找法的升级版 -------------------------------------------------------------------------------- /Algorithms/0034.search-for-a-range/README.md: -------------------------------------------------------------------------------- 1 | # [34. Search for a Range](https://leetcode.com/problems/search-for-a-range/) 2 | 3 | ## 题目 4 | Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. 5 | 6 | Your algorithm's runtime complexity must be in the order of O(log n). 7 | 8 | If the target is not found in the array, return [-1, -1]. 9 | 10 | For example, 11 | Given [5, 7, 7, 8, 8, 10] and target value 8, 12 | return [3, 4]. 13 | 14 | ## 解题思路 15 | 见注释 16 | 17 | ## 总结 18 | 19 | 20 | -------------------------------------------------------------------------------- /Algorithms/0035.search-insert-position/README.md: -------------------------------------------------------------------------------- 1 | # [35. Search Insert Position](https://leetcode.com/problems/search-insert-position/) 2 | 3 | ## 题目 4 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 5 | 6 | You may assume no duplicates in the array. 7 | ``` 8 | Here are few examples. 9 | [1,3,5,6], 5 → 2 10 | [1,3,5,6], 2 → 1 11 | [1,3,5,6], 7 → 4 12 | [1,3,5,6], 0 → 0 13 | ``` 14 | ## 解题思路 15 | 寻找target在nums中的位置。 16 | 详见程序注释。 17 | 18 | ## 总结 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/0035.search-insert-position/search-insert-position.go: -------------------------------------------------------------------------------- 1 | package Problem0035 2 | 3 | func searchInsert(nums []int, target int) int { 4 | // 没有把i放入for语句中 5 | // 是为了兼容,len(nums) == 0 和 target > nums[len(nums)-1]两种情况 6 | i := 0 7 | 8 | for i < len(nums) && nums[i] <= target { 9 | // 相等的时候,直接返回 10 | if nums[i] == target { 11 | return i 12 | } 13 | 14 | // 否则,就去检查下一个 15 | i++ 16 | } 17 | 18 | return i 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/0036.valid-sudoku/README.md: -------------------------------------------------------------------------------- 1 | # [36. Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) 2 | 3 | ## 题目 4 | Determine if a Sudoku is valid, according to: [Sudoku Puzzles - The Rules.](http://sudoku.com.au/TheRules.aspx) 5 | 6 | The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 7 | ![sudoku](sudoku.png) 8 | 9 | A partially filled sudoku which is valid. 10 | 11 | Note: 12 | A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. 13 | 14 | ## 解题思路 15 | 数独的规则很简单: 16 | 1. 横着的9个数,不能重复 17 | 1. 竖着的9个数,不能重复 18 | 1. 3×3小方块中的9个数,也不能重复 19 | 20 | 那么解题思路,就是依次检查这三个方面有没有重复。 21 | 22 | ## 总结 23 | 24 | 25 | -------------------------------------------------------------------------------- /Algorithms/0036.valid-sudoku/sudoku.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0036.valid-sudoku/sudoku.png -------------------------------------------------------------------------------- /Algorithms/0037.sudoku-solver/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0037.sudoku-solver/1.png -------------------------------------------------------------------------------- /Algorithms/0037.sudoku-solver/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0037.sudoku-solver/2.png -------------------------------------------------------------------------------- /Algorithms/0037.sudoku-solver/README.md: -------------------------------------------------------------------------------- 1 | # [37. Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) 2 | 3 | ## 题目 4 | Write a program to solve a Sudoku puzzle by filling the empty cells. 5 | 6 | Empty cells are indicated by the character `'.'`. 7 | 8 | You may assume that there will be only one unique solution. 9 | 10 | ![problem](1.png) 11 | 12 | A sudoku puzzle... 13 | 14 | ![solution](2.png) 15 | 16 | ...and its solution numbers marked in red. 17 | 18 | ## 解题思路 19 | 我把数独框中,需要保证数字不重复的3×3小块,称为一个block。 20 | 由于数独需要保持每行,每列,每个block中的数字不重复。解题思路如下: 21 | 1. 依次往9个block中,分别填写1~9。 22 | 1. 如果block中已经存在n了,去填写下一个数。 23 | 1. 在可行的空位填好 n 后 24 | 1. 如果后面的填写没有问题,返回true 25 | 1. 如果后面的填写有问题,把n移入下一个可行的位置。 26 | 1. n在这个block中,没有位置放了,返回false 27 | 1. 1~9都填写完了,就去填写下一个block分别填写1~9 28 | 1. 所有的block都填写完了,结束。 29 | 30 | 具体过程和细节,见程序及注释。 31 | ## 总结 32 | 虽然,我一直主张编写不超过20行的函数,但是匿名函数确实好用。 -------------------------------------------------------------------------------- /Algorithms/0038.count-and-say/README.md: -------------------------------------------------------------------------------- 1 | # [38. Count and Say](https://leetcode.com/problems/count-and-say/) 2 | 3 | ## 题目 4 | The count-and-say sequence is the sequence of integers with the first five terms as following: 5 | ``` 6 | 1. 1 7 | 2. 11 8 | 3. 21 9 | 4. 1211 10 | 5. 111221 11 | ``` 12 | 1 is read off as "one 1" or 11. 13 | 14 | 11 is read off as "two 1s" or 21. 15 | 16 | 21 is read off as "one 2, then one 1" or 1211. 17 | 18 | Given an integer n, generate the nth term of the count-and-say sequence. 19 | 20 | Note: Each term of the sequence of integers will be represented as a string. 21 | 22 | Example 1: 23 | ``` 24 | Input: 1 25 | Output: "1" 26 | ``` 27 | Example 2: 28 | ``` 29 | Input: 4 30 | Output: "1211" 31 | ``` 32 | 33 | ## 解题思路 34 | 利用[]byte记录上一次出现的次数和元素。 35 | 36 | 详见注释 37 | 38 | ## 总结 39 | 使用辅助数据,比如切片或者映射,记录信息,可以极大地加快程序。 -------------------------------------------------------------------------------- /Algorithms/0038.count-and-say/count-and-say.go: -------------------------------------------------------------------------------- 1 | package Problem0038 2 | 3 | func countAndSay(n int) string { 4 | buf := []byte{'1'} 5 | 6 | for n > 1 { 7 | buf = say(buf) 8 | n-- 9 | } 10 | 11 | return string(buf) 12 | } 13 | 14 | func say(buf []byte) []byte { 15 | // res 长度不会超过 buf 的两倍,所以,可以事先指定容量,加快append的速度 16 | res := make([]byte, 0, len(buf)*2) 17 | 18 | i, j := 0, 1 19 | for i < len(buf) { 20 | // 利用 j ,找到下一个不同的元素 21 | for j < len(buf) && buf[j] == buf[i] { 22 | j++ 23 | } 24 | 25 | // res 中 res[i] 表示 res[i+1] 的个数,i 为0,2,4,6,... 26 | res = append(res, byte(j-i+'0'), buf[i]) 27 | 28 | // 移动 i 到 j 29 | i = j 30 | } 31 | 32 | return res 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/0039.combination-sum/combination-sum.go: -------------------------------------------------------------------------------- 1 | package Problem0039 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func combinationSum(candidates []int, target int) [][]int { 8 | sort.Ints(candidates) 9 | 10 | res := [][]int{} 11 | solution := []int{} 12 | cs(candidates, solution, target, &res) 13 | 14 | return res 15 | } 16 | 17 | func cs(candidates, solution []int, target int, result *[][]int) { 18 | if target == 0 { 19 | *result = append(*result, solution) 20 | } 21 | 22 | if len(candidates) == 0 || target < candidates[0] { 23 | // target < candidates[0] 因为candidates是排序好的 24 | return 25 | } 26 | 27 | // 这样处理一下的用意是,让切片的容量等于长度,以后append的时候,会分配新的底层数组 28 | // 避免多处同时对底层数组进行修改,产生错误的答案。 29 | // 可以注释掉以下语句,运行单元测试,查看错误发生。 30 | solution = solution[:len(solution):len(solution)] 31 | 32 | cs(candidates, append(solution, candidates[0]), target-candidates[0], result) 33 | 34 | cs(candidates[1:], solution, target, result) 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0040.combination-sum-ii/100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0040.combination-sum-ii/100.png -------------------------------------------------------------------------------- /Algorithms/0040.combination-sum-ii/README.md: -------------------------------------------------------------------------------- 1 | # [40. Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) 2 | 3 | ## 题目 4 | Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 5 | 6 | Each number in C may only be used once in the combination. 7 | 8 | Note: 9 | 1. All numbers (including target) will be positive integers. 10 | 1. The solution set must not contain duplicate combinations. 11 | For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, 12 | A solution set is: 13 | ``` 14 | [ 15 | [1, 7], 16 | [1, 2, 5], 17 | [2, 6], 18 | [1, 1, 6] 19 | ] 20 | ``` 21 | ## 解题思路 22 | 这一题是[39. Combination Sum](https://leetcode.com/problems/combination-sum/)的变种。区别在于,元素不能重复使用。所以在划分的时候,对candidates的处理也不同。 23 | 24 | ## 总结 25 | 又提交了一次,一不小心就迎来了人生的第一个100%,主要的功劳在leetcode服务器。 26 | ![100%](100.png) 27 | -------------------------------------------------------------------------------- /Algorithms/0041.first-missing-positive/README.md: -------------------------------------------------------------------------------- 1 | # [41. First Missing Positive](https://leetcode.com/problems/first-missing-positive/) 2 | 3 | ## 题目 4 | Given an unsorted integer array, find the first missing positive integer. 5 | 6 | For example, 7 | ``` 8 | Given [1,2,0] return 3, 9 | and [3,4,-1,1] return 2. 10 | ``` 11 | Your algorithm should run in O(n) time and uses constant space. 12 | 13 | ## 解题思路 14 | 15 | 16 | ## 总结 17 | 18 | 19 | -------------------------------------------------------------------------------- /Algorithms/0042.trapping-rain-water/README.md: -------------------------------------------------------------------------------- 1 | # [42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) 2 | 3 | ## 题目 4 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 5 | 6 | For example, 7 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 8 | ![rainwatertrap](rainwatertrap.png) 9 | 10 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 11 | 12 | ## 解题思路 13 | 解题的关键有两点 14 | 1. 理解 i 点的存水量为 min(max(height[:i+1]...), max(height[i:]...)) - height[i] 15 | 1. 高效地找到 max(height[:i+1]...) 和 max(height[i:]...) 16 | 17 | ## 总结 18 | 利用记录,比每次现找要省时的多。 -------------------------------------------------------------------------------- /Algorithms/0042.trapping-rain-water/rainwatertrap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0042.trapping-rain-water/rainwatertrap.png -------------------------------------------------------------------------------- /Algorithms/0042.trapping-rain-water/trapping-rain-water.go: -------------------------------------------------------------------------------- 1 | package Problem0042 2 | 3 | func bigger(a int, b int) int { 4 | if a > b { 5 | return a 6 | } 7 | return b 8 | } 9 | 10 | func smaller(a int, b int) int { 11 | if a < b { 12 | return a 13 | } 14 | return b 15 | } 16 | 17 | func trap(height []int) int { 18 | length := len(height) 19 | if length <= 2 { 20 | return 0 21 | } 22 | 23 | left, right := make([]int, length), make([]int, length) 24 | 25 | left[0], right[length-1] = height[0], height[length-1] 26 | 27 | for i := 1; i < length; i++ { 28 | left[i] = bigger(left[i-1], height[i]) 29 | right[length-1-i] = bigger(right[length-i], height[length-1-i]) 30 | 31 | // left[i] 是 height[:i+1] 中的最大值 32 | // right[i] 是 height[i:] 中的最大值 33 | } 34 | 35 | water := 0 36 | for i := 0; i < length; i++ { 37 | // 存水量取决于 左右最大值 中的较小值 38 | water += smaller(left[i], right[i]) - height[i] 39 | } 40 | 41 | return water 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/0043.multiply-strings/README.md: -------------------------------------------------------------------------------- 1 | # [43. Multiply Strings](https://leetcode.com/problems/multiply-strings/) 2 | 3 | ## 题目 4 | Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`. 5 | 6 | Note: 7 | 1. The length of both `num1` and `num2` is < 110. 8 | 1. Both `num1` and `num2` contains only digits `0-9`. 9 | 1. Both `num1` and `num2` does not contain any leading zero. 10 | 1. You must not use any `built-in BigInteger library` or `convert the inputs to integer directly`. 11 | 12 | ## 解题思路 13 | 1. 利用[]int{}记录中间计算过程,此时不考虑进位,例如,"123" 和 "65" 的记录为 []int{6,17,28,15} 14 | 1. 统一处理进位,记录变为[]int{7,9,9,5} 15 | 1. 转换为string,返回 16 | 17 | 细节见程序注释。 18 | ## 总结 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/0044.wildcard-matching/README.md: -------------------------------------------------------------------------------- 1 | # [44. Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) 2 | 3 | ## 题目 4 | Implement wildcard pattern matching with support for '?' and '*'. 5 | 6 | '?' Matches any single character. 7 | '*' Matches any sequence of characters (including the empty sequence). 8 | 9 | The matching should cover the entire input string (not partial). 10 | 11 | The function prototype should be: 12 | bool isMatch(const char *s, const char *p) 13 | 14 | Some examples: 15 | isMatch("aa","a") → false 16 | isMatch("aa","aa") → true 17 | isMatch("aaa","aa") → false 18 | isMatch("aa", "*") → true 19 | isMatch("aa", "a*") → true 20 | isMatch("ab", "?*") → true 21 | isMatch("aab", "c*a*b") → false 22 | 23 | ## 解题思路 24 | 注意审题: 25 | 1. '?' 可以匹配任意一个字符,但是不能匹配空字符"" 26 | 1. '*' 可以任意多个字符,包括"" 27 | 28 | 见程序注释 29 | -------------------------------------------------------------------------------- /Algorithms/0045.jump-game-ii/README.md: -------------------------------------------------------------------------------- 1 | # [45. Jump Game II](https://leetcode.com/problems/jump-game-ii/) 2 | 3 | ## 题目 4 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 5 | 6 | Each element in the array represents your maximum jump length at that position. 7 | 8 | Your goal is to reach the last index in the minimum number of jumps. 9 | 10 | For example: 11 | ``` 12 | Given array A = [2,3,1,1,4] 13 | ``` 14 | The minimum number of jumps to reach the last index is `2`. (Jump `1` step from index `0` to `1`, then `3` steps to the last index.) 15 | 16 | Note: 17 | ``` 18 | You can assume that you can always reach the last index. 19 | ``` 20 | 21 | ## 解题思路 22 | 想清楚,i 定了以后,要保证 next i 为可以 jump 到最远的 i 23 | 24 | ## 总结 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algorithms/0045.jump-game-ii/jump-game-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0045 2 | 3 | func jump(nums []int) int { 4 | i, count, end := 0, 0, len(nums)-1 5 | 6 | var nextI, maxNextI, maxI int 7 | for i < end { 8 | if i+nums[i] >= end { 9 | return count + 1 10 | } 11 | 12 | nextI, maxNextI = i+1, i+nums[i] 13 | for nextI <= maxNextI { 14 | if nextI+nums[nextI] > maxI { 15 | maxI, i = nextI+nums[nextI], nextI 16 | } 17 | 18 | nextI++ 19 | } 20 | 21 | count++ 22 | } 23 | 24 | return count 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0046.permutations/README.md: -------------------------------------------------------------------------------- 1 | # [46. Permutations](https://leetcode.com/problems/permutations/) 2 | 3 | ## 题目 4 | Given a collection of distinct numbers, return all possible permutations. 5 | 6 | For example, 7 | `[1,2,3]` have the following permutations: 8 | ``` 9 | [ 10 | [1,2,3], 11 | [1,3,2], 12 | [2,1,3], 13 | [2,3,1], 14 | [3,1,2], 15 | [3,2,1] 16 | ] 17 | ``` 18 | 19 | ## 解题思路 20 | 按照手写排列的思路,编写递归程序即可。 21 | 22 | ## 总结 23 | -------------------------------------------------------------------------------- /Algorithms/0046.permutations/permutations_test.go: -------------------------------------------------------------------------------- 1 | package Problem0046 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | // one 代表第一个参数 17 | type para struct { 18 | one []int 19 | } 20 | 21 | // ans 是答案 22 | // one 代表第一个答案 23 | type ans struct { 24 | one [][]int 25 | } 26 | 27 | func Test_Problem0046(t *testing.T) { 28 | ast := assert.New(t) 29 | 30 | qs := []question{ 31 | 32 | question{ 33 | para{[]int{1, 2, 3}}, 34 | ans{[][]int{ 35 | []int{1, 2, 3}, 36 | []int{1, 3, 2}, 37 | []int{2, 1, 3}, 38 | []int{2, 3, 1}, 39 | []int{3, 1, 2}, 40 | []int{3, 2, 1}, 41 | }}, 42 | }, 43 | 44 | // 如需多个测试,可以复制上方元素。 45 | } 46 | 47 | for _, q := range qs { 48 | a, p := q.ans, q.para 49 | fmt.Printf("~~%v~~\n", p) 50 | 51 | ast.Equal(a.one, permute(p.one), "输入:%v", p) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Algorithms/0047.permutations-ii/README.md: -------------------------------------------------------------------------------- 1 | # [47. Permutations II](https://leetcode.com/problems/permutations-ii/) 2 | 3 | ## 题目 4 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 5 | 6 | For example, 7 | `[1,1,2]` have the following unique permutations: 8 | ``` 9 | [ 10 | [1,1,2], 11 | [1,2,1], 12 | [2,1,1] 13 | ] 14 | ``` 15 | ## 解题思路 16 | 本题和[46. Permutations](https://leetcode.com/problems/permutations/)的区别在于,存在重复的数字。根据46题思路,同一个cur下,已经使用过的数字,就不能再使用了。即可。 17 | ## 总结 -------------------------------------------------------------------------------- /Algorithms/0048.rotate-image/README.md: -------------------------------------------------------------------------------- 1 | # [48. Rotate Image](https://leetcode.com/problems/rotate-image/) 2 | 3 | ## 题目 4 | You are given an n x n 2D matrix representing an image. 5 | 6 | Rotate the image by 90 degrees (clockwise). 7 | 8 | Follow up: 9 | Could you do this in-place? 10 | 11 | ## 解题思路 12 | 对应的4个点,依次互换位置。 13 | 14 | ## 总结 15 | 16 | 17 | -------------------------------------------------------------------------------- /Algorithms/0048.rotate-image/rotate-image.go: -------------------------------------------------------------------------------- 1 | package Problem0048 2 | 3 | func rotate(m [][]int) { 4 | n := len(m) 5 | for i := 0; i < n/2; i++ { 6 | for j := i; j < n-i-1; j++ { 7 | temp := m[i][j] 8 | // 左边的行 等于 右边的列 9 | m[i][j] = m[n-j-1][i] 10 | m[n-j-1][i] = m[n-i-1][n-j-1] 11 | m[n-i-1][n-j-1] = m[j][n-i-1] 12 | m[j][n-i-1] = temp 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/0049.group-anagrams/README.md: -------------------------------------------------------------------------------- 1 | # [49. Group Anagrams](https://leetcode.com/problems/group-anagrams/) 2 | 3 | ## 题目 4 | Given an array of strings, group anagrams together. 5 | ``` 6 | For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 7 | Return: 8 | 9 | [ 10 | ["ate", "eat","tea"], 11 | ["nat","tan"], 12 | ["bat"] 13 | ] 14 | ``` 15 | ## 解题思路 16 | 17 | 18 | ## 总结 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/0049.group-anagrams/group-anagrams.go: -------------------------------------------------------------------------------- 1 | package Problem0049 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func groupAnagrams(strs []string) [][]string { 8 | res := [][]string{} 9 | record := make(map[string][]string) 10 | 11 | for _, str := range strs { 12 | temp := sortString(str) 13 | record[temp] = append(record[temp], str) 14 | } 15 | for _, v := range record { 16 | sort.Strings(v) 17 | res = append(res, v) 18 | } 19 | 20 | return res 21 | } 22 | 23 | func sortString(s string) string { 24 | bytes := []byte(s) 25 | 26 | temp := make([]int, len(bytes)) 27 | for i, b := range bytes { 28 | temp[i] = int(b) 29 | } 30 | 31 | sort.Ints(temp) 32 | 33 | for i, v := range temp { 34 | bytes[i] = byte(v) 35 | } 36 | 37 | return string(bytes) 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/0050.powx-n/README.md: -------------------------------------------------------------------------------- 1 | # [50. Pow(x, n)](https://leetcode.com/problems/powx-n/) 2 | 3 | ## 题目 4 | Implement pow(x, n). 5 | 6 | ## 解题思路 7 | 注意到指数是整数,所以,可以利用乘法计算幂 8 | ## 总结 9 | o(N)的算法会浪费很多时间,o(lgN)的算法要快的多。 10 | -------------------------------------------------------------------------------- /Algorithms/0050.powx-n/powx-n.go: -------------------------------------------------------------------------------- 1 | package Problem0050 2 | 3 | func myPow(x float64, n int) float64 { 4 | if n < 0 { 5 | return 1.0 / pow(x, -n) 6 | } 7 | 8 | return pow(x, n) 9 | } 10 | 11 | func pow(x float64, n int) float64 { 12 | if x == 0 { 13 | return 0 14 | } 15 | 16 | if n == 0 { 17 | return 1 18 | } 19 | 20 | res := pow(x, n>>1) 21 | if n&1 == 0 { 22 | return res * res 23 | } 24 | 25 | return res * res * x 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/0051.n-queens/8-queens.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0051.n-queens/8-queens.png -------------------------------------------------------------------------------- /Algorithms/0051.n-queens/README.md: -------------------------------------------------------------------------------- 1 | # [51. N-Queens](https://leetcode.com/problems/n-queens/) 2 | 3 | ## 题目 4 | The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. 5 | 6 | ![8-queens](8-queens.png) 7 | 8 | Given an integer n, return all distinct solutions to the n-queens puzzle. 9 | 10 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 11 | 12 | For example, 13 | There exist two distinct solutions to the 4-queens puzzle: 14 | ``` 15 | [ 16 | [".Q..", // Solution 1 17 | "...Q", 18 | "Q...", 19 | "..Q."], 20 | 21 | ["..Q.", // Solution 2 22 | "Q...", 23 | "...Q", 24 | ".Q.."] 25 | ] 26 | ``` 27 | ## 解题思路 28 | 题目要求,在以下地方都没有其他的Queen 29 | 1. 所在的行 30 | 1. 所在的列 31 | 1. 两条45度对角线上 32 | 33 | 和前面的数独问题一样的解题思路 34 | ## 总结 35 | 36 | 37 | -------------------------------------------------------------------------------- /Algorithms/0052.n-queens-ii/8-queens.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0052.n-queens-ii/8-queens.png -------------------------------------------------------------------------------- /Algorithms/0052.n-queens-ii/README.md: -------------------------------------------------------------------------------- 1 | # [52. N-Queens II](https://leetcode.com/problems/n-queens-ii/) 2 | 3 | ## 题目 4 | Follow up for N-Queens problem. 5 | 6 | ![8-queens](8-queens.png) 7 | 8 | Now, instead outputting board configurations, return the total number of distinct solutions. 9 | 10 | 11 | ## 解题思路 12 | 请参考51题的思路。 13 | 14 | ## 总结 15 | 16 | 17 | -------------------------------------------------------------------------------- /Algorithms/0052.n-queens-ii/n-queens-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0052 2 | 3 | func totalNQueens(n int) int { 4 | if n == 0 { 5 | return 0 6 | } 7 | 8 | cols := make([]bool, n) 9 | // 记录 '\' 方向的对角线的占用情况 10 | d1 := make([]bool, 2*n) 11 | // 记录 '/' 方向的对角线的占用情况 12 | d2 := make([]bool, 2*n) 13 | 14 | res := 0 15 | 16 | dfs(0, cols, d1, d2, &res) 17 | 18 | return res 19 | } 20 | 21 | func dfs(r int, cols, d1, d2 []bool, res *int) { 22 | n := len(cols) 23 | 24 | if r == n { 25 | *res++ 26 | return 27 | } 28 | 29 | for c := 0; c < n; c++ { 30 | id1 := r - c + n 31 | id2 := 2*n - r - c - 1 32 | if !cols[c] && !d1[id1] && !d2[id2] { 33 | 34 | // 标记占用 35 | cols[c], d1[id1], d2[id2] = true, true, true 36 | 37 | dfs(r+1, cols, d1, d2, res) 38 | 39 | // 解除标记 40 | cols[c], d1[id1], d2[id2] = false, false, false 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/0053.maximum-subarray/README.md: -------------------------------------------------------------------------------- 1 | # [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) 2 | 3 | ## 题目 4 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 5 | 6 | For example, given the array `[-2,1,-3,4,-1,2,1,-5,4]`, 7 | 8 | the contiguous subarray `[4,-1,2,1]` has the largest sum = `6`. 9 | 10 | More practice: 11 | 12 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 13 | ## 解题思路 14 | 利用好`连续`这个约束 15 | 16 | 详见注释 17 | 18 | ## 总结 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/0053.maximum-subarray/maximum-subarray.go: -------------------------------------------------------------------------------- 1 | package Problem0053 2 | 3 | func maxSubArray(nums []int) int { 4 | l := len(nums) 5 | 6 | if l == 0 { 7 | return 0 8 | } 9 | 10 | if l == 1 { 11 | return nums[0] 12 | } 13 | 14 | temp := nums[0] 15 | max := temp 16 | i := 1 17 | // 可以把 for 循环的过程,nums[:1] 每次增加一个,直到变成 nums 的过程。 18 | // temp 就是这个过程中,每个 nums[:i] 中的 max(nums[x:i]) (x=0,1,...,i-1) 19 | // 整个 nums 中连续子序列的最大值,就在 temp 的所有取值中 20 | for i < l { 21 | if temp < 0 { 22 | // 因为 连续性 的要求,而此时 temp < 0 23 | // temp 从 i 处重新开始 24 | temp = nums[i] 25 | } else { 26 | temp += nums[i] 27 | } 28 | 29 | if max < temp { 30 | max = temp 31 | } 32 | 33 | i++ 34 | } 35 | 36 | return max 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0054.spiral-matrix/README.md: -------------------------------------------------------------------------------- 1 | # [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) 2 | 3 | ## 题目 4 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 5 | 6 | ``` 7 | For example, 8 | Given the following matrix: 9 | 10 | [ 11 | [ 1, 2, 3 ], 12 | [ 4, 5, 6 ], 13 | [ 7, 8, 9 ] 14 | ] 15 | 16 | You should return [1,2,3,6,9,8,7,4,5]. 17 | ``` 18 | ## 解题思路 19 | 20 | 见程序注释 21 | -------------------------------------------------------------------------------- /Algorithms/0054.spiral-matrix/spiral-matrix.go: -------------------------------------------------------------------------------- 1 | package Problem0054 2 | 3 | func spiralOrder(matrix [][]int) []int { 4 | r := len(matrix) 5 | 6 | if r == 0 { 7 | return []int{} 8 | } 9 | 10 | c := len(matrix[0]) 11 | if c == 0 { 12 | return []int{} 13 | } 14 | 15 | if len(matrix) == 1 { 16 | return matrix[0] 17 | } 18 | 19 | res := make([]int, 0, r*c) 20 | 21 | res = append(res, matrix[0]...) 22 | 23 | for i := 1; i < r-1; i++ { 24 | res = append(res, matrix[i][c-1]) 25 | } 26 | 27 | for j := c - 1; j >= 0; j-- { 28 | res = append(res, matrix[r-1][j]) 29 | } 30 | 31 | for i := r - 2; i > 0 && c > 1; i-- { 32 | res = append(res, matrix[i][0]) 33 | } 34 | 35 | if r == 2 || c <= 2 { 36 | return res 37 | } 38 | 39 | nextMatrix := make([][]int, 0, r-2) 40 | for i := 1; i < r-1; i++ { 41 | nextMatrix = append(nextMatrix, matrix[i][1:c-1]) 42 | } 43 | 44 | return append(res, spiralOrder(nextMatrix)...) 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/0055.jump-game/README.md: -------------------------------------------------------------------------------- 1 | # [55. Jump Game](https://leetcode.com/problems/jump-game/) 2 | 3 | ## 题目 4 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 5 | 6 | Each element in the array represents your maximum jump length at that position. 7 | 8 | Determine if you are able to reach the last index. 9 | 10 | ``` 11 | For example: 12 | A = [2,3,1,1,4], return true. 13 | A = [3,2,1,0,4], return false. 14 | ``` 15 | ## 解题思路 16 | 关键能不能跨过数值为0的元素。 17 | 见程序注释 18 | -------------------------------------------------------------------------------- /Algorithms/0055.jump-game/jump-game.go: -------------------------------------------------------------------------------- 1 | package Problem0055 2 | 3 | func canJump(nums []int) bool { 4 | 5 | for i := len(nums) - 2; i >= 0; i-- { 6 | // 找到数值为 0 的元素 7 | if nums[i] != 0 { 8 | continue 9 | } 10 | 11 | j := i - 1 12 | for ; j >= 0; j-- { 13 | if i-j < nums[j] { 14 | // 在 j 号位置上,可以跨过 0 元素 15 | i = j 16 | break 17 | } 18 | } 19 | 20 | if j == -1 { 21 | // 在 0 元素之前,没有位置可以跨过 0 22 | return false 23 | } 24 | } 25 | 26 | return true 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/0056.merge-intervals/README.md: -------------------------------------------------------------------------------- 1 | # [56. Merge Intervals](https://leetcode.com/problems/merge-intervals/) 2 | 3 | ## 题目 4 | Given a collection of intervals, merge all overlapping intervals. 5 | 6 | ``` 7 | For example, 8 | Given [1,3],[2,6],[8,10],[15,18], 9 | return [1,6],[8,10],[15,18]. 10 | ``` 11 | ## 解题思路 12 | 1. 先对 intervals 进行排序,按照 Start 递增 13 | 1. 依次处理重叠的情况。 14 | 15 | ## 附注 16 | 最快的答案和我的思路一样,只是使用的是 merge sort ,自我感觉我的答案更清晰,就没有改成他的。 -------------------------------------------------------------------------------- /Algorithms/0057.insert-interval/README.md: -------------------------------------------------------------------------------- 1 | # [57. Insert Interval](https://leetcode.com/problems/insert-interval/) 2 | 3 | ## 题目 4 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 5 | 6 | You may assume that the intervals were initially sorted according to their start times. 7 | 8 | ``` 9 | Example 1: 10 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 11 | 12 | Example 2: 13 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 14 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 15 | ``` 16 | ## 解题思路 17 | 18 | 分情况讨论 19 | 20 | 见程序 21 | -------------------------------------------------------------------------------- /Algorithms/0058.length-of-last-word/README.md: -------------------------------------------------------------------------------- 1 | # [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/) 2 | 3 | ## 题目 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 5 | 6 | If the last word does not exist, return 0. 7 | 8 | **Note**: A word is defined as a character sequence consists of non-space characters only. 9 | 10 | ``` 11 | For example, 12 | Given s = "Hello World", 13 | return 5. 14 | ``` 15 | ## 解题思路 16 | 17 | 见程序注释 18 | -------------------------------------------------------------------------------- /Algorithms/0058.length-of-last-word/length-of-last-word.go: -------------------------------------------------------------------------------- 1 | package Problem0058 2 | 3 | func lengthOfLastWord(s string) int { 4 | size := len(s) 5 | if size == 0 { 6 | return 0 7 | } 8 | res := 0 9 | for i := size - 1; i >= 0; i-- { 10 | if s[i] == ' ' { 11 | if res != 0 { 12 | return res 13 | } 14 | continue 15 | } 16 | res++ 17 | } 18 | 19 | return res 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/0059.spiral-matrix-ii/README.md: -------------------------------------------------------------------------------- 1 | # [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) 2 | 3 | ## 题目 4 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 5 | 6 | ``` 7 | For example, Given n = 3, You should return the following matrix: 8 | [ 9 | [ 1, 2, 3 ], 10 | [ 8, 9, 4 ], 11 | [ 7, 6, 5 ] 12 | ] 13 | ``` 14 | ## 解题思路 15 | 依照题意,设置填充边界,沿着边界填写。 16 | 17 | 见程序注释 18 | -------------------------------------------------------------------------------- /Algorithms/0059.spiral-matrix-ii/spiral-matrix-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0059 2 | 3 | func generateMatrix(n int) [][]int { 4 | if n == 0 { 5 | return [][]int{} 6 | } 7 | 8 | res := make([][]int, n) 9 | for i := range res { 10 | res[i] = make([]int, n) 11 | } 12 | 13 | // 4 条边界,依照题意,沿着边界填写 14 | top, bottom, left, right := 0, n-1, 0, n-1 15 | num := 1 16 | for top <= bottom && left <= right { 17 | // → 18 | for j := left; j <= right; j++ { 19 | res[top][j] = num 20 | num++ 21 | } 22 | top++ 23 | // ↓ 24 | for j := top; j <= bottom; j++ { 25 | res[j][right] = num 26 | num++ 27 | } 28 | right-- 29 | // ← 30 | for j := right; j >= left; j-- { 31 | res[bottom][j] = num 32 | num++ 33 | } 34 | bottom-- 35 | // ↑ 36 | for j := bottom; j >= top; j-- { 37 | res[j][left] = num 38 | num++ 39 | } 40 | left++ 41 | } 42 | 43 | return res 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/0060.permutation-sequence/README.md: -------------------------------------------------------------------------------- 1 | # [60. Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) 2 | 3 | ## 题目 4 | The set `[1,2,3,…,n]` contains a total of n! unique permutations. 5 | 6 | By listing and labeling all of the permutations in order, 7 | We get the following sequence (ie, for n = 3): 8 | 9 | 1. "123" 10 | 1. "132" 11 | 1. "213" 12 | 1. "231" 13 | 1. "312" 14 | 1. "321" 15 | 16 | 17 | 18 | Given n and k, return the kth permutation sequence. 19 | 20 | Note: Given n will be between 1 and 9 inclusive. 21 | 22 | ## 解题思路 23 | 24 | 见程序注释 25 | -------------------------------------------------------------------------------- /Algorithms/0060.permutation-sequence/permutation-sequence.go: -------------------------------------------------------------------------------- 1 | package Problem0060 2 | 3 | func getPermutation(n int, k int) string { 4 | if n == 0 { 5 | return "" 6 | } 7 | 8 | // 用于存放结果的字符 9 | res := make([]byte, n) 10 | 11 | // 存放待抓取的数字 12 | rec := make([]byte, n) 13 | for i := 0; i < n; i++ { 14 | rec[i] = byte(i) + '1' 15 | } 16 | 17 | // 由于排列的序号是从 1 开始的。 18 | // k 需要减去 1 ,好从 0 开始表示 19 | k-- 20 | 21 | base := 1 22 | for i := 2; i < n; i++ { 23 | base *= i 24 | } 25 | 26 | for i := 0; i < n-1; i++ { 27 | idx := k / base 28 | res[i] = rec[idx] 29 | // 从 rec 中去除已经使用的数 rec[idx] 30 | rec = append(rec[:idx], rec[idx+1:]...) 31 | k %= base 32 | base /= (n - i - 1) 33 | } 34 | // 不要忘记最后一个数 35 | res[n-1] = rec[0] 36 | 37 | return string(res) 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/0061.rotate-list/README.md: -------------------------------------------------------------------------------- 1 | # [61. Rotate List](https://leetcode.com/problems/rotate-list/) 2 | 3 | ## 题目 4 | Given a list, rotate the list to the right by k places, where k is non-negative. 5 | For example: 6 | ``` 7 | Given 1->2->3->4->5->NULL and k = 2, 8 | return 4->5->1->2->3->NULL. 9 | ``` 10 | ## 解题思路 11 | 12 | 见程序注释 13 | -------------------------------------------------------------------------------- /Algorithms/0061.rotate-list/rotate-list.go: -------------------------------------------------------------------------------- 1 | package Problem0061 2 | 3 | // ListNode 是题目预定义的节点 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | func rotateRight(head *ListNode, k int) *ListNode { 10 | if k == 0 || head == nil { 11 | return head 12 | } 13 | 14 | fast := head 15 | for i := 0; i < k; i++ { 16 | if fast.Next == nil { 17 | // 处理 k 大于 list 的长度的情况 18 | // i+1 就是 list 的长度 19 | // 这一步很巧妙 20 | return rotateRight(head, k%(i+1)) 21 | } 22 | fast = fast.Next 23 | } 24 | 25 | slow := head 26 | for fast.Next != nil { 27 | slow, fast = slow.Next, fast.Next 28 | } 29 | 30 | newHead := slow.Next 31 | slow.Next, fast.Next = nil, head 32 | 33 | return newHead 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/0062.unique-paths/README.md: -------------------------------------------------------------------------------- 1 | # [62. Unique Paths](https://leetcode.com/problems/unique-paths/) 2 | 3 | ## 题目 4 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 5 | 6 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 7 | 8 | How many possible unique paths are there? 9 | 10 | ![robotMaze](robot_maze.png) 11 | 12 | Above is a 3 x 7 grid. How many possible unique paths are there? 13 | 14 | Note: m and n will be at most 100. 15 | 16 | ## 解题思路 17 | 18 | 见程序注释 19 | -------------------------------------------------------------------------------- /Algorithms/0062.unique-paths/robot_maze.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0062.unique-paths/robot_maze.png -------------------------------------------------------------------------------- /Algorithms/0062.unique-paths/unique-paths.go: -------------------------------------------------------------------------------- 1 | package Problem0062 2 | 3 | func uniquePaths(m int, n int) int { 4 | // dp[i][j] 代表了,到达 (i,j) 格子的不同路径数目 5 | dp := [][]int{} 6 | 7 | // 创建棋盘 8 | for i := 0; i < m; i++ { 9 | tmp := make([]int, n) 10 | dp = append(dp, tmp) 11 | } 12 | 13 | for i := 0; i < m; i++ { 14 | // 到达第 0 列的格子,只有一条路径 15 | dp[i][0] = 1 16 | } 17 | 18 | for j := 0; j < n; j++ { 19 | // 到达第 0 行的格子,只有一条路径 20 | dp[0][j] = 1 21 | } 22 | 23 | for i := 1; i < m; i++ { 24 | for j := 1; j < n; j++ { 25 | // 到达 (i,j) 格子的路径数目,等于 26 | // 到达 上方格子 和 左边格子 路径数之和 27 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 28 | } 29 | } 30 | 31 | return dp[m-1][n-1] 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/0063.unique-paths-ii/README.md: -------------------------------------------------------------------------------- 1 | # [63. Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) 2 | 3 | ## 题目 4 | Follow up for "Unique Paths": 5 | 6 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 7 | 8 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 9 | 10 | For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. 11 | ``` 12 | [ 13 | [0,0,0], 14 | [0,1,0], 15 | [0,0,0] 16 | ] 17 | ``` 18 | The total number of unique paths is `2`. 19 | 20 | **Note:** m and n will be at most 100. 21 | 22 | ## 解题思路 23 | 和[62. Unique Paths](../0062.unique-paths)的解题思路一样。 24 | 25 | 见程序注释 26 | -------------------------------------------------------------------------------- /Algorithms/0063.unique-paths-ii/unique-paths-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0063 2 | 3 | func uniquePathsWithObstacles(obstacleGrid [][]int) int { 4 | m := len(obstacleGrid) 5 | if m == 0 { 6 | return 0 7 | } 8 | 9 | n := len(obstacleGrid[0]) 10 | if n == 0 { 11 | return 0 12 | } 13 | 14 | dp := make([][]int, m) 15 | for i := range dp { 16 | dp[i] = make([]int, n) 17 | } 18 | 19 | if obstacleGrid[0][0] == 0 { 20 | dp[0][0] = 1 21 | } 22 | 23 | for i := 1; i < m; i++ { 24 | if obstacleGrid[i][0] == 0 { 25 | dp[i][0] = dp[i-1][0] 26 | } 27 | } 28 | 29 | for j := 1; j < n; j++ { 30 | if obstacleGrid[0][j] == 0 { 31 | dp[0][j] = dp[0][j-1] 32 | } 33 | } 34 | 35 | for i := 1; i < m; i++ { 36 | for j := 1; j < n; j++ { 37 | if obstacleGrid[i][j] == 0 { 38 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 39 | } 40 | } 41 | } 42 | 43 | return dp[m-1][n-1] 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/0064.minimum-path-sum/README.md: -------------------------------------------------------------------------------- 1 | # [64. Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) 2 | 3 | ## 题目 4 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 5 | 6 | Note: You can only move either down or right at any point in time. 7 | 8 | ## 解题思路 9 | 和[62. Unique Paths](../0062.unique-paths)的解题思路一样。 10 | 11 | 见程序注释 12 | -------------------------------------------------------------------------------- /Algorithms/0064.minimum-path-sum/minimum-path-sum.go: -------------------------------------------------------------------------------- 1 | package Problem0064 2 | 3 | func minPathSum(grid [][]int) int { 4 | // 已经默认 m 和 n 大于 0 了 5 | m := len(grid) 6 | n := len(grid[0]) 7 | 8 | dp := make([][]int, m) 9 | for i := range dp { 10 | dp[i] = make([]int, n) 11 | } 12 | 13 | dp[0][0] = grid[0][0] 14 | 15 | for i := 1; i < m; i++ { 16 | dp[i][0] = grid[i][0] + dp[i-1][0] 17 | } 18 | 19 | for j := 1; j < n; j++ { 20 | dp[0][j] = grid[0][j] + dp[0][j-1] 21 | } 22 | 23 | for i := 1; i < m; i++ { 24 | for j := 1; j < n; j++ { 25 | dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]) 26 | } 27 | } 28 | 29 | return dp[m-1][n-1] 30 | } 31 | 32 | func min(a, b int) int { 33 | if a < b { 34 | return a 35 | } 36 | return b 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0065.valid-number/README.md: -------------------------------------------------------------------------------- 1 | # [65. Valid Number](https://leetcode.com/problems/valid-number/) 2 | 3 | ## 题目 4 | Validate if a given string is numeric. 5 | 6 | ``` 7 | Some examples: 8 | "0" => true 9 | " 0.1 " => true 10 | "abc" => false 11 | "1 a" => false 12 | "2e10" => true 13 | ``` 14 | 15 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. 16 | 17 | 18 | ## 解题思路 19 | 20 | 见程序注释 21 | -------------------------------------------------------------------------------- /Algorithms/0066.plus-one/README.md: -------------------------------------------------------------------------------- 1 | # [66. Plus One](https://leetcode.com/problems/plus-one/) 2 | 3 | ## 题目 4 | Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 5 | 6 | You may assume the integer do not contain any leading zero, except the number 0 itself. 7 | 8 | The digits are stored such that the most significant digit is at the head of the list. 9 | 10 | ## 解题思路 11 | 12 | 见程序注释 13 | ## 总结 14 | 15 | 16 | -------------------------------------------------------------------------------- /Algorithms/0066.plus-one/plus-one.go: -------------------------------------------------------------------------------- 1 | package Problem0066 2 | 3 | func plusOne(digits []int) []int { 4 | length := len(digits) 5 | if length == 0 { 6 | return []int{1} 7 | } 8 | 9 | // 末尾加一 10 | digits[length-1]++ 11 | 12 | // 处理进位 13 | for i := length - 1; i > 0; i-- { 14 | if digits[i] < 10 { 15 | break 16 | } 17 | digits[i] -= 10 18 | digits[i-1]++ 19 | } 20 | 21 | // 处理首位的进位 22 | if digits[0] > 9 { 23 | digits[0] -= 10 24 | digits = append([]int{1}, digits...) 25 | } 26 | 27 | return digits 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/0067.add-binary/README.md: -------------------------------------------------------------------------------- 1 | # [67. Add Binary](https://leetcode.com/problems/add-binary/) 2 | 3 | ## 题目 4 | Given two binary strings, return their sum (also a binary string). 5 | 6 | ``` 7 | For example, 8 | a = "11" 9 | b = "1" 10 | Return "100". 11 | ``` 12 | ## 解题思路 13 | 14 | 见程序注释 15 | -------------------------------------------------------------------------------- /Algorithms/0069.sqrtx/README.md: -------------------------------------------------------------------------------- 1 | # [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/) 2 | 3 | ## 题目 4 | Implement int sqrt(int x). 5 | 6 | Compute and return the square root of x. 7 | 8 | ## 解题思路 9 | 10 | 见程序注释 11 | -------------------------------------------------------------------------------- /Algorithms/0069.sqrtx/sqrtx.go: -------------------------------------------------------------------------------- 1 | package Problem0069 2 | 3 | func mySqrt(x int) int { 4 | res := x 5 | 6 | // 牛顿法求平方根 7 | for res*res > x { 8 | res = (res + x/res) / 2 9 | } 10 | 11 | return res 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/0070.climbing-stairs/README.md: -------------------------------------------------------------------------------- 1 | # [70. Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) 2 | 3 | ## 题目 4 | You are climbing a stair case. It takes n steps to reach to the top. 5 | 6 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 7 | 8 | Note: Given n will be a positive integer. 9 | 10 | ## 解题思路 11 | 12 | 见程序注释 13 | -------------------------------------------------------------------------------- /Algorithms/0070.climbing-stairs/climbing-stairs.go: -------------------------------------------------------------------------------- 1 | package Problem0070 2 | 3 | func climbStairs(n int) int { 4 | if n < 2 { 5 | return 1 6 | } 7 | 8 | rec := make([]int, n+1) 9 | rec[0], rec[1] = 1, 1 10 | 11 | for i := 2; i <= n; i++ { 12 | rec[i] = rec[i-1] + rec[i-2] 13 | } 14 | 15 | return rec[n] 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/0071.simplify-path/README.md: -------------------------------------------------------------------------------- 1 | # [71. Simplify Path](https://leetcode.com/problems/simplify-path/) 2 | 3 | ## 题目 4 | Given an absolute path for a file (Unix-style), simplify it. 5 | 6 | ``` 7 | For example, 8 | path = "/home/", => "/home" 9 | path = "/a/./b/../../c/", => "/c" 10 | ``` 11 | 12 | click to show corner cases. 13 | 14 | Corner Cases: 15 | ``` 16 | Did you consider the case where path = "/../"? 17 | In this case, you should return "/". 18 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 19 | In this case, you should ignore redundant slashes and return "/home/foo". 20 | ``` 21 | ## 解题思路 22 | 23 | 见程序注释 24 | -------------------------------------------------------------------------------- /Algorithms/0071.simplify-path/simplify-path.go: -------------------------------------------------------------------------------- 1 | package Problem0071 2 | 3 | import "strings" 4 | 5 | func simplifyPath(path string) string { 6 | lp := len(path) 7 | stack := make([]string, 0, lp/2) 8 | dir := make([]byte, 0, lp) 9 | 10 | for i := 0; i < lp; i++ { 11 | // 使用前,清空 dir 12 | // 这个方法比 dir = []byte{} 快了近 8 倍 13 | dir = dir[:0] 14 | // 获取 dir 15 | for i < lp && path[i] != '/' { 16 | dir = append(dir, path[i]) 17 | i++ 18 | } 19 | 20 | s := string(dir) 21 | 22 | switch s { 23 | case ".", "": 24 | // do nothing 25 | case "..": 26 | if len(stack) > 0 { 27 | // pop 28 | stack = stack[:len(stack)-1] 29 | } 30 | default: 31 | stack = append(stack, s) 32 | } 33 | } 34 | 35 | return "/" + strings.Join(stack, "/") 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/0072.edit-distance/edit-distance.go: -------------------------------------------------------------------------------- 1 | package Problem0072 2 | 3 | func minDistance(word1 string, word2 string) int { 4 | m := len(word1) 5 | n := len(word2) 6 | cost := 0 7 | 8 | dp := make([][]int, m+1) 9 | for i := range dp { 10 | dp[i] = make([]int, n+1) 11 | } 12 | 13 | for i := 0; i <= m; i++ { 14 | dp[i][0] = i 15 | } 16 | for j := 0; j <= n; j++ { 17 | dp[0][j] = j 18 | } 19 | 20 | for i := 1; i <= m; i++ { 21 | for j := 1; j <= n; j++ { 22 | dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1) 23 | 24 | if word1[i-1] == word2[j-1] { 25 | cost = 0 26 | } else { 27 | cost = 1 28 | } 29 | 30 | dp[i][j] = min(dp[i][j], dp[i-1][j-1]+cost) 31 | } 32 | } 33 | 34 | return dp[m][n] 35 | } 36 | 37 | func min(a, b int) int { 38 | if a < b { 39 | return a 40 | } 41 | return b 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/0073.set-matrix-zeroes/README.md: -------------------------------------------------------------------------------- 1 | # [73. Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) 2 | 3 | ## 题目 4 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 5 | 6 | click to show follow up. 7 | ``` 8 | Follow up: 9 | Did you use extra space? 10 | A straight forward solution using O(mn) space is probably a bad idea. 11 | A simple improvement uses O(m + n) space, but still not the best solution. 12 | Could you devise a constant space solution? 13 | ``` 14 | ## 解题思路 15 | 16 | 见程序注释 17 | -------------------------------------------------------------------------------- /Algorithms/0073.set-matrix-zeroes/set-matrix-zeroes.go: -------------------------------------------------------------------------------- 1 | package Problem0073 2 | 3 | func setZeroes(m [][]int) { 4 | rows := make([]bool, len(m)) // rows[i] == true ,代表 i 行存在 0 元素 5 | cols := make([]bool, len(m[0])) // cols[j] == true ,代表 j 列存在 0 元素 6 | 7 | // 逐个检查元素 8 | for i := range m { 9 | for j := range m[i] { 10 | if m[i][j] == 0 { 11 | rows[i] = true 12 | cols[j] = true 13 | } 14 | } 15 | } 16 | 17 | // 按行修改 18 | for i := range rows { 19 | if rows[i] { 20 | for j := range m[i] { 21 | m[i][j] = 0 22 | } 23 | } 24 | } 25 | 26 | // 按列修改 27 | for i := range cols { 28 | if cols[i] { 29 | for j := range m { 30 | m[j][i] = 0 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/0074.search-a-2d-matrix/README.md: -------------------------------------------------------------------------------- 1 | # [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) 2 | 3 | ## 题目 4 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 5 | 6 | 1. Integers in each row are sorted from left to right. 7 | 1. The first integer of each row is greater than the last integer of the previous row. 8 | 9 | For example, Consider the following matrix: 10 | ``` 11 | [ 12 | [1, 3, 5, 7], 13 | [10, 11, 16, 20], 14 | [23, 30, 34, 50] 15 | ] 16 | ``` 17 | Given `target` = `3`, return `true`. 18 | 19 | ## 解题思路 20 | 21 | 见程序注释 22 | -------------------------------------------------------------------------------- /Algorithms/0074.search-a-2d-matrix/search-a-2d-matrix.go: -------------------------------------------------------------------------------- 1 | package Problem0074 2 | 3 | func searchMatrix(mat [][]int, target int) bool { 4 | m := len(mat) 5 | if m == 0 { 6 | return false 7 | } 8 | 9 | n := len(mat[0]) 10 | if n == 0 { 11 | return false 12 | } 13 | 14 | if target < mat[0][0] || mat[m-1][n-1] < target { 15 | return false 16 | } 17 | 18 | // 寻找行 19 | r := 0 20 | for r < m && mat[r][0] <= target { 21 | r++ 22 | } 23 | r-- 24 | 25 | // 二分法寻找 target 26 | i, j := 0, n-1 27 | for i <= j { 28 | med := (i + j) / 2 29 | switch { 30 | case mat[r][med] < target: 31 | i = med + 1 32 | case target < mat[r][med]: 33 | j = med - 1 34 | default: 35 | return true 36 | } 37 | } 38 | 39 | return mat[r][j] == target 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/0075.sort-colors/README.md: -------------------------------------------------------------------------------- 1 | # [75. Sort Colors](https://leetcode.com/problems/sort-colors/) 2 | 3 | ## 题目 4 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 5 | 6 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 7 | 8 | **Note:**You are not suppose to use the library's sort function for this problem. 9 | 10 | click to show follow up. 11 | ``` 12 | Follow up: 13 | A rather straight forward solution is a two-pass algorithm using counting sort. 14 | First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 15 | Could you come up with an one-pass algorithm using only constant space? 16 | ``` 17 | ## 解题思路 18 | 19 | 见程序注释 20 | -------------------------------------------------------------------------------- /Algorithms/0075.sort-colors/sort-colors.go: -------------------------------------------------------------------------------- 1 | package Problem0075 2 | 3 | func sortColors(nums []int) { 4 | length := len(nums) 5 | if length == 0 { 6 | return 7 | } 8 | 9 | // 三路快排需要 nums[0] == 1 10 | temp := nums[0] 11 | nums[0] = 1 12 | 13 | // 三路快排 14 | // 排序完成后, 15 | // i 指向 0 后的 1, 16 | // j 指向 最后一个 1 后面的位置, 17 | // k 指向 2 前面的 1, 18 | // 在整个排序过程中,nums[i:j]中始终都是1 19 | i, j, k := 0, 1, length-1 20 | for j <= k { 21 | switch { 22 | case nums[j] < 1: 23 | // 比 1 小的,放入队列首部 24 | nums[i], nums[j] = nums[j], nums[i] 25 | i++ 26 | j++ 27 | case 1 < nums[j]: 28 | // 比 1 大的,放入队列尾部 29 | nums[j], nums[k] = nums[k], nums[j] 30 | k-- 31 | default: 32 | j++ 33 | } 34 | } 35 | 36 | // 分情况,还原temp 37 | switch temp { 38 | case 0: 39 | nums[i] = temp 40 | case 2: 41 | nums[k] = temp 42 | } 43 | 44 | return 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/0076.minimum-window-substring/README.md: -------------------------------------------------------------------------------- 1 | # [76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) 2 | 3 | ## 题目 4 | Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 5 | 6 | ``` 7 | For example, 8 | S = "ADOBECODEBANC" 9 | T = "ABC" 10 | 11 | Minimum window is "BANC". 12 | ``` 13 | 14 | Note: 15 | 1. If there is no such window in S that covers all characters in T, return the empty string "". 16 | 1. If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 17 | 18 | ## 解题思路 19 | 双指针的解法 20 | 21 | 见程序注释 22 | -------------------------------------------------------------------------------- /Algorithms/0077.combinations/README.md: -------------------------------------------------------------------------------- 1 | # [77. Combinations](https://leetcode.com/problems/combinations/) 2 | 3 | ## 题目 4 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 5 | 6 | For example, 7 | If n = 4 and k = 2, a solution is: 8 | ``` 9 | [ 10 | [2,4], 11 | [3,4], 12 | [2,3], 13 | [1,2], 14 | [1,3], 15 | [1,4], 16 | ] 17 | ``` 18 | ## 解题思路 19 | 20 | 见程序注释 21 | -------------------------------------------------------------------------------- /Algorithms/0077.combinations/combinations.go: -------------------------------------------------------------------------------- 1 | package Problem0077 2 | 3 | func combine(n int, k int) [][]int { 4 | combination := make([]int, k) 5 | res := [][]int{} 6 | 7 | var dfs func(int, int) 8 | dfs = func(idx, begin int) { 9 | if idx == k { 10 | temp := make([]int, k) 11 | copy(temp, combination) 12 | res = append(res, temp) 13 | return 14 | } 15 | 16 | for i := begin; i <= n+1-k+idx; i++ { 17 | combination[idx] = i 18 | dfs(idx+1, i+1) 19 | } 20 | } 21 | 22 | dfs(0, 1) 23 | 24 | return res 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0077.combinations/combinations_test.go: -------------------------------------------------------------------------------- 1 | package Problem0077 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | type para struct { 17 | n int 18 | k int 19 | } 20 | 21 | // ans 是答案 22 | type ans struct { 23 | one [][]int 24 | } 25 | 26 | func Test_Problem0077(t *testing.T) { 27 | ast := assert.New(t) 28 | 29 | qs := []question{ 30 | 31 | question{ 32 | para{ 33 | 4, 34 | 2, 35 | }, 36 | ans{ 37 | [][]int{ 38 | []int{1, 2}, 39 | []int{1, 3}, 40 | []int{1, 4}, 41 | []int{2, 3}, 42 | []int{2, 4}, 43 | []int{3, 4}, 44 | }, 45 | }, 46 | }, 47 | 48 | // 如需多个测试,可以复制上方元素。 49 | } 50 | 51 | for _, q := range qs { 52 | a, p := q.ans, q.para 53 | fmt.Printf("~~%v~~\n", p) 54 | 55 | ast.Equal(a.one, combine(p.n, p.k), "输入:%v", p) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Algorithms/0078.subsets/README.md: -------------------------------------------------------------------------------- 1 | # [78. Subsets](https://leetcode.com/problems/subsets/) 2 | 3 | ## 题目 4 | Given a set of distinct integers, nums, return all possible subsets. 5 | 6 | Note: The solution set must not contain duplicate subsets. 7 | 8 | For example, 9 | If nums = [1,2,3], a solution is: 10 | 11 | ``` 12 | [ 13 | [3], 14 | [1], 15 | [2], 16 | [1,2,3], 17 | [1,3], 18 | [2,3], 19 | [1,2], 20 | [] 21 | ] 22 | ``` 23 | ## 解题思路 24 | 先`run`一下,观察输出结果的队形。再用递归的方式解题。 25 | 26 | 见程序注释 27 | -------------------------------------------------------------------------------- /Algorithms/0078.subsets/subsets.go: -------------------------------------------------------------------------------- 1 | package Problem0078 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func subsets(nums []int) [][]int { 8 | res := [][]int{} 9 | 10 | recur(nums, []int{}, &res) 11 | 12 | return res 13 | } 14 | 15 | func recur(nums, temp []int, res *[][]int) { 16 | l := len(nums) 17 | if l == 0 { 18 | sort.Ints(temp) 19 | *res = append(*res, temp) 20 | return 21 | } 22 | 23 | recur(nums[:l-1], temp, res) 24 | 25 | recur(nums[:l-1], append([]int{nums[l-1]}, temp...), res) 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/0079.word-search/README.md: -------------------------------------------------------------------------------- 1 | # [79. Word Search](https://leetcode.com/problems/word-search/) 2 | 3 | ## 题目 4 | Given a 2D board and a word, find if the word exists in the grid. 5 | 6 | 7 | The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. 8 | 9 | 10 | 11 | For example, 12 | Given board = 13 | ``` 14 | [ 15 | ['A','B','C','E'], 16 | ['S','F','C','S'], 17 | ['A','D','E','E'] 18 | ] 19 | ``` 20 | 21 | word = "ABCCED", -> returns true, 22 | word = "SEE", -> returns true, 23 | word = "ABCB", -> returns false. 24 | 25 | ## 解题思路 26 | 27 | 使用dfs 28 | 29 | 见程序注释 30 | -------------------------------------------------------------------------------- /Algorithms/0080.remove-duplicates-from-sorted-array-ii/README.md: -------------------------------------------------------------------------------- 1 | # [80. Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) 2 | 3 | ## 题目 4 | Follow up for "Remove Duplicates": 5 | What if duplicates are allowed at most twice? 6 | 7 | 8 | For example, 9 | Given sorted array nums = `[1,1,1,2,2,3]`, 10 | 11 | 12 | Your function should return length = `5`, with the first five elements of nums being `1`, `1`, `2`, `2` and `3`. It doesn't matter what you leave beyond the new length. 13 | 14 | ## 解题思路 15 | 16 | 见程序注释 17 | -------------------------------------------------------------------------------- /Algorithms/0080.remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0080 2 | 3 | func removeDuplicates(nums []int) int { 4 | length := len(nums) 5 | if length <= 2 { 6 | return length 7 | } 8 | 9 | res := 2 10 | for i := 2; i < length; i++ { 11 | if nums[i] != nums[res-2] { 12 | nums[res] = nums[i] 13 | res++ 14 | } 15 | } 16 | 17 | return res 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/0081.search-in-rotated-sorted-array-ii/README.md: -------------------------------------------------------------------------------- 1 | # [81. Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) 2 | 3 | ## 题目 4 | Follow up for "Search in Rotated Sorted Array": 5 | 1. What if duplicates are allowed? 6 | 1. Would this affect the run-time complexity? How and why? 7 | 8 | 9 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 10 | 11 | (i.e., `0 1 2 4 5 6 7` might become `4 5 6 7 0 1 2`). 12 | 13 | Write a function to determine if a given target is in the array. 14 | 15 | The array may contain duplicates. 16 | 17 | ## 解题思路 18 | 和[33. Search in Rotated Sorted Array](../0033.search-in-rotated-sorted-array)的解题思路一样,只是要先自己找到 k 的值。 19 | 20 | 见程序注释 21 | -------------------------------------------------------------------------------- /Algorithms/0081.search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0081 2 | 3 | func search(nums []int, target int) bool { 4 | length := len(nums) 5 | if length == 0 { 6 | return false 7 | } 8 | k := 1 9 | for k < len(nums) && nums[k-1] <= nums[k] { 10 | k++ 11 | } 12 | 13 | i, j := 0, length-1 14 | for i <= j { 15 | m := (i + j) / 2 16 | med := (m + k) % length 17 | 18 | switch { 19 | case nums[med] < target: 20 | i = m + 1 21 | case target < nums[med]: 22 | j = m - 1 23 | default: 24 | return true 25 | } 26 | } 27 | 28 | return false 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/0082.remove-duplicates-from-sorted-list-ii/README.md: -------------------------------------------------------------------------------- 1 | # [82. Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) 2 | 3 | ## 题目 4 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 5 | 6 | ``` 7 | For example, 8 | Given 1->2->3->3->4->4->5, return 1->2->5. 9 | Given 1->1->1->2->3, return 2->3. 10 | ``` 11 | ## 解题思路 12 | 13 | 见程序注释 14 | -------------------------------------------------------------------------------- /Algorithms/0082.remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0082 2 | 3 | // ListNode is singly-linked list. 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | func deleteDuplicates(head *ListNode) *ListNode { 10 | // 长度 <=1 的 list ,可以直接返回 11 | if head == nil || head.Next == nil { 12 | return head 13 | } 14 | 15 | // 处理 head 重复情况 16 | // 上面刚刚检查过了,head != nil && head.Next != nil 17 | if head.Val == head.Next.Val { 18 | val := head.Val 19 | head = head.Next.Next 20 | 21 | for head != nil && head.Val == val { 22 | head = head.Next 23 | } 24 | 25 | // 值为 val 的 node,已经全部删除了 26 | return deleteDuplicates(head) 27 | } 28 | 29 | // 处理 head 后面元素出现重复的情况 30 | head.Next = deleteDuplicates(head.Next) 31 | 32 | return head 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/0083.remove-duplicates-from-sorted-list/README.md: -------------------------------------------------------------------------------- 1 | # [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) 2 | 3 | ## 题目 4 | Given a sorted linked list, delete all duplicates such that each element appear only once. 5 | 6 | ``` 7 | For example, 8 | Given 1->1->2, return 1->2. 9 | Given 1->1->2->3->3, return 1->2->3. 10 | ``` 11 | 12 | ## 解题思路 13 | 14 | 见程序注释 15 | -------------------------------------------------------------------------------- /Algorithms/0083.remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.go: -------------------------------------------------------------------------------- 1 | package Problem0083 2 | 3 | // ListNode is singly-linked list 4 | type ListNode struct { 5 | Val int 6 | Next *ListNode 7 | } 8 | 9 | func deleteDuplicates(head *ListNode) *ListNode { 10 | if head == nil { 11 | return nil 12 | } 13 | 14 | temp := head 15 | 16 | for temp.Next != nil { 17 | if temp.Val == temp.Next.Val { 18 | temp.Next = temp.Next.Next 19 | } else { 20 | temp = temp.Next 21 | } 22 | } 23 | 24 | return head 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0084.largest-rectangle-in-histogram/histogram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0084.largest-rectangle-in-histogram/histogram.png -------------------------------------------------------------------------------- /Algorithms/0084.largest-rectangle-in-histogram/histogram_area.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0084.largest-rectangle-in-histogram/histogram_area.png -------------------------------------------------------------------------------- /Algorithms/0085.maximal-rectangle/README.md: -------------------------------------------------------------------------------- 1 | # [85. Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) 2 | 3 | ## 题目 4 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. 5 | 6 | For example, given the following matrix: 7 | ``` 8 | 1 0 1 0 0 9 | 1 0 1 1 1 10 | 1 1 1 1 1 11 | 1 0 0 1 0 12 | ``` 13 | Return 6. 14 | 15 | ## 解题思路 16 | 17 | http://blog.csdn.net/doc_sgl/article/details/11832965 18 | 19 | 见程序注释 20 | -------------------------------------------------------------------------------- /Algorithms/0086.partition-list/README.md: -------------------------------------------------------------------------------- 1 | # [86. Partition List](https://leetcode.com/problems/partition-list/) 2 | 3 | ## 题目 4 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 5 | 6 | You should preserve the original relative order of the nodes in each of the two partitions. 7 | 8 | ``` 9 | For example, 10 | Given 1->4->3->2->5->2 and x = 3, 11 | return 1->2->2->4->3->5. 12 | ``` 13 | ## 解题思路 14 | 15 | 见程序注释 16 | -------------------------------------------------------------------------------- /Algorithms/0086.partition-list/partition-list.go: -------------------------------------------------------------------------------- 1 | package Problem0086 2 | 3 | // ListNode 是链接节点 4 | // 这个不能复制到*_test.go文件中。会导致Travis失败 5 | type ListNode struct { 6 | Val int 7 | Next *ListNode 8 | } 9 | 10 | func partition(head *ListNode, x int) *ListNode { 11 | if head == nil || head.Next == nil { 12 | return head 13 | } 14 | 15 | // 存放 =x 的节点的链 18 | noLessHead := &ListNode{} 19 | // Head.Next 才是真正的 head 20 | // 这样处理是为了 for 循环中的逻辑简单 21 | 22 | lessEnd := lessHead 23 | noLessEnd := noLessHead 24 | 25 | for head != nil { 26 | if head.Val < x { 27 | lessEnd.Next = head 28 | lessEnd = lessEnd.Next 29 | } else { 30 | noLessEnd.Next = head 31 | noLessEnd = noLessEnd.Next 32 | } 33 | head = head.Next 34 | } 35 | 36 | // 把两部分首尾相连 37 | lessEnd.Next = noLessHead.Next 38 | // 注意封闭 noLessEnd 39 | noLessEnd.Next = nil 40 | 41 | head = lessHead.Next 42 | return head 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/0088.merge-sorted-array/README.md: -------------------------------------------------------------------------------- 1 | # [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) 2 | 3 | ## 题目 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | Note: 7 | 8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | 10 | ## 解题思路 11 | 见程序注释 12 | 13 | ## 总结 -------------------------------------------------------------------------------- /Algorithms/0088.merge-sorted-array/merge-sorted-array.go: -------------------------------------------------------------------------------- 1 | package Problem0088 2 | 3 | // 本题的要求是,把nums1的前m项和nums2的前n项合并,放入nums1中。 4 | func merge(nums1 []int, m int, nums2 []int, n int) { 5 | // 深度复制 nums1 6 | temp := make([]int, m) 7 | copy(temp, nums1) 8 | 9 | j, k := 0, 0 10 | for i := 0; i < len(nums1); i++ { 11 | // nums2用完了 12 | if k >= n { 13 | nums1[i] = temp[j] 14 | j++ 15 | continue 16 | } 17 | // temp 用完了 18 | if j >= m { 19 | nums1[i] = nums2[k] 20 | k++ 21 | continue 22 | } 23 | // 比较后,放入 24 | if temp[j] < nums2[k] { 25 | nums1[i] = temp[j] 26 | j++ 27 | } else { 28 | nums1[i] = nums2[k] 29 | k++ 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/0089.gray-code/README.md: -------------------------------------------------------------------------------- 1 | # [89. Gray Code](https://leetcode.com/problems/gray-code/) 2 | 3 | ## 题目 4 | The gray code is a binary numeral system where two successive values differ in only one bit. 5 | 6 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 7 | ``` 8 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 9 | 00 - 0 10 | 01 - 1 11 | 11 - 3 12 | 10 - 2 13 | ``` 14 | Note: 15 | For a given n, a gray code sequence is not uniquely defined. 16 | 17 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 18 | 19 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 20 | 21 | ## 解题思路 22 | 答案的顺序很重要,观察答案后,利用递归做。 23 | 24 | 见程序注释 25 | -------------------------------------------------------------------------------- /Algorithms/0089.gray-code/gray-code.go: -------------------------------------------------------------------------------- 1 | package Problem0089 2 | 3 | func grayCode(n int) []int { 4 | return recur(n, 1, []int{0}) 5 | } 6 | 7 | func recur(n, base int, nums []int) []int { 8 | if n == 0 { 9 | return nums 10 | } 11 | 12 | length := len(nums) 13 | temp := make([]int, length) 14 | for i := range nums { 15 | temp[length-i-1] = nums[i] + base 16 | } 17 | 18 | return recur(n-1, base*2, append(nums, temp...)) 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/0090.subsets-ii/README.md: -------------------------------------------------------------------------------- 1 | # [90. Subsets II](https://leetcode.com/problems/subsets-ii/) 2 | 3 | ## 题目 4 | Given a collection of integers that might contain duplicates, nums, return all possible subsets. 5 | 6 | Note: The solution set must not contain duplicate subsets. 7 | 8 | 9 | For example, 10 | If nums = [1,2,2], a solution is: 11 | 12 | 13 | [ 14 | [2], 15 | [1], 16 | [1,2,2], 17 | [2,2], 18 | [1,2], 19 | [] 20 | ] 21 | 22 | ## 解题思路 23 | 观察题目输出结果的规律后,利用dfs解题 24 | 25 | 见程序注释 26 | -------------------------------------------------------------------------------- /Algorithms/0090.subsets-ii/subsets-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0090 2 | 3 | import "sort" 4 | 5 | func subsetsWithDup(nums []int) [][]int { 6 | res := [][]int{} 7 | sort.Ints(nums) 8 | 9 | var dfs func(int, []int) 10 | dfs = func(idx int, temp []int) { 11 | t := make([]int, len(temp)) 12 | copy(t, temp) 13 | // 没有以上两行,答案就是错的 14 | // 因为temp的底层数组在递归过程中,不停地修改 15 | // 程序结束时,temp的底层数组的值,全部是 nums 的最大值。 16 | res = append(res, t) 17 | 18 | for i := idx; i < len(nums); i++ { 19 | if i == idx || nums[i] != nums[i-1] { 20 | dfs(i+1, append(temp, nums[i])) 21 | } 22 | } 23 | } 24 | 25 | temp := make([]int, 0, len(nums)) 26 | dfs(0, temp) 27 | 28 | return res 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/0091.decode-ways/README.md: -------------------------------------------------------------------------------- 1 | # [91. Decode Ways](https://leetcode.com/problems/decode-ways/) 2 | 3 | ## 题目 4 | A message containing letters from `A-Z` is being encoded to numbers using the following mapping: 5 | 6 | ``` 7 | 'A' -> 1 8 | 'B' -> 2 9 | ... 10 | 'Z' -> 26 11 | ``` 12 | 13 | Given an encoded message containing digits, determine the total number of ways to decode it. 14 | 15 | ``` 16 | For example, 17 | Given encoded message "12", 18 | it could be decoded as "AB" (1 2) or "L" (12). 19 | The number of ways decoding "12" is 2. 20 | ``` 21 | 22 | ## 解题思路 23 | 24 | 见程序注释 25 | -------------------------------------------------------------------------------- /Algorithms/0092.reverse-linked-list-ii/README.md: -------------------------------------------------------------------------------- 1 | # [92. Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) 2 | 3 | ## 题目 4 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 5 | 6 | ``` 7 | For example: 8 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 9 | return 1->4->3->2->5->NULL. 10 | ``` 11 | 12 | Note: Given m, n satisfy the following condition: 13 | 1. 1 ≤ m ≤ n ≤ length of list. 14 | 1. head 的序号为 1 15 | 16 | ## 解题思路 17 | 18 | 见程序注释 19 | -------------------------------------------------------------------------------- /Algorithms/0093.restore-ip-addresses/README.md: -------------------------------------------------------------------------------- 1 | # [93. Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) 2 | 3 | ## 题目 4 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 5 | 6 | ``` 7 | For example: 8 | Given "25525511135", 9 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 10 | ``` 11 | ## 解题思路 12 | 13 | 见程序注释 14 | 15 | 下次做此题,不要用 DFS 方法。普通的递归更快。 -------------------------------------------------------------------------------- /Algorithms/0094.binary-tree-inorder-traversal/README.md: -------------------------------------------------------------------------------- 1 | # [94. Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) 2 | 3 | ## 题目 4 | Given a binary tree, return the inorder traversal of its nodes' values. 5 | 6 | 7 | ``` 8 | For example: 9 | Given binary tree [1,null,2,3], 10 | 1 11 | \ 12 | 2 13 | / 14 | 3 15 | return [1,3,2]. 16 | ``` 17 | 18 | Note: Recursive solution is trivial, could you do it iteratively? 19 | 20 | ## 解题思路 21 | 22 | 见程序注释 23 | -------------------------------------------------------------------------------- /Algorithms/0094.binary-tree-inorder-traversal/binary-tree-inorder-traversal.go: -------------------------------------------------------------------------------- 1 | package Problem0094 2 | 3 | // TreeNode Definition for a binary tree node. 4 | type TreeNode struct { 5 | Val int 6 | Left *TreeNode 7 | Right *TreeNode 8 | } 9 | 10 | func inorderTraversal(root *TreeNode) []int { 11 | if root == nil { 12 | return nil 13 | } 14 | 15 | if root.Left == nil && root.Right == nil { 16 | return []int{root.Val} 17 | } 18 | 19 | res := inorderTraversal(root.Left) 20 | res = append(res, root.Val) 21 | res = append(res, inorderTraversal(root.Right)...) 22 | 23 | return res 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/0095.unique-binary-search-trees-ii/README.md: -------------------------------------------------------------------------------- 1 | # [95. Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) 2 | 3 | ## 题目 4 | Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n. 5 | 6 | ``` 7 | For example, 8 | Given n = 3, your program should return all 5 unique BST's shown below. 9 | 1 3 3 2 1 10 | \ / / / \ \ 11 | 3 2 1 1 3 2 12 | / / \ \ 13 | 2 1 2 3 14 | ``` 15 | 16 | ## 解题思路 17 | 18 | 见程序注释 19 | -------------------------------------------------------------------------------- /Algorithms/0096.unique-binary-search-trees/README.md: -------------------------------------------------------------------------------- 1 | # [96. Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) 2 | 3 | ## 题目 4 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 5 | 6 | ``` 7 | For example, 8 | Given n = 3, there are a total of 5 unique BST's. 9 | 10 | 1 3 3 2 1 11 | \ / / / \ \ 12 | 3 2 1 1 3 2 13 | / / \ \ 14 | 2 1 2 3 15 | ``` 16 | 17 | ## 解题思路 18 | 19 | 见程序注释 20 | -------------------------------------------------------------------------------- /Algorithms/0096.unique-binary-search-trees/unique-binary-search-trees.go: -------------------------------------------------------------------------------- 1 | package Problem0096 2 | 3 | func numTrees(n int) int { 4 | if n == 0 { 5 | return 1 6 | } 7 | if n == 1 || n == 2 { 8 | return n 9 | } 10 | 11 | if n == 3 { 12 | return 5 13 | } 14 | 15 | res := 0 16 | // 左右对称,所以只做一半 17 | for i := 1; i <= n/2; i++ { 18 | res += numTrees(i-1) * numTrees(n-i) 19 | } 20 | res *= 2 21 | // 处理 n 为奇数的情况 22 | if n%2 == 1 { 23 | temp := numTrees(n / 2) 24 | res += temp * temp 25 | } 26 | 27 | return res 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/0097.interleaving-string/README.md: -------------------------------------------------------------------------------- 1 | # [97. Interleaving String](https://leetcode.com/problems/interleaving-string/) 2 | 3 | ## 题目 4 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 5 | ``` 6 | For example, 7 | Given: 8 | s1 = "aabcc", 9 | s2 = "dbbca", 10 | 11 | When s3 = "aadbbcbcac", return true. 12 | When s3 = "aadbbbaccc", return false. 13 | ``` 14 | 15 | ## 解题思路 16 | s3 能否由 s1 和 s2,交替融合而生。 17 | 18 | 见程序注释 19 | -------------------------------------------------------------------------------- /Algorithms/0097.interleaving-string/interleaving-string.go: -------------------------------------------------------------------------------- 1 | package Problem0097 2 | 3 | func isInterleave(s1 string, s2 string, s3 string) bool { 4 | m, n := len(s1), len(s2) 5 | if m+n != len(s3) { 6 | return false 7 | } 8 | 9 | // dp[i][j][i+j] == true 表示 s1[:i] 和 s2[:j] 可以生成 s3[:i+j] 10 | dp := make([][][]bool, m+1) 11 | for i := 0; i <= m; i++ { 12 | dp[i] = make([][]bool, n+1) 13 | for j := 0; j <= n; j++ { 14 | dp[i][j] = make([]bool, m+n+1) 15 | } 16 | } 17 | dp[0][0][0] = true 18 | 19 | for i := 1; i <= m; i++ { 20 | dp[i][0][i] = dp[i-1][0][i-1] && s1[i-1] == s3[i-1] 21 | } 22 | 23 | for j := 1; j <= n; j++ { 24 | dp[0][j][j] = dp[0][j-1][j-1] && s2[j-1] == s3[j-1] 25 | } 26 | 27 | for i := 1; i <= m; i++ { 28 | for j := 1; j <= n; j++ { 29 | dp[i][j][i+j] = (dp[i-1][j][i+j-1] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1][i+j-1] && s2[j-1] == s3[i+j-1]) 30 | } 31 | } 32 | 33 | return dp[m][n][m+n] 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/0098.validate-binary-search-tree/README.md: -------------------------------------------------------------------------------- 1 | # [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) 2 | 3 | ## 题目 4 | Given a binary tree, determine if it is a valid binary search tree (BST). 5 | 6 | Assume a BST is defined as follows: 7 | 8 | The left subtree of a node contains only nodes with keys less than the node's key. 9 | The right subtree of a node contains only nodes with keys greater than the node's key. 10 | Both the left and right subtrees must also be binary search trees. 11 | Example 1: 12 | ``` 13 | 2 14 | / \ 15 | 1 3 16 | ``` 17 | Binary tree [2,1,3], return true. 18 | 19 | Example 2: 20 | ``` 21 | 1 22 | / \ 23 | 2 3 24 | ``` 25 | Binary tree [1,2,3], return false. 26 | 27 | ## 解题思路 28 | 29 | 见程序注释 30 | -------------------------------------------------------------------------------- /Algorithms/0098.validate-binary-search-tree/validate-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0098 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func isValidBST(root *TreeNode) bool { 10 | // Golang int 类型的最小值与最大值 11 | MIN, MAX := -1<<63, 1<<63-1 12 | 13 | return recur(MIN, MAX, root) 14 | } 15 | 16 | // 以递归的方式,检查 root.Val 是否在 (min, max) 范围内。 17 | func recur(min, max int, root *TreeNode) bool { 18 | if root == nil { 19 | return true 20 | } 21 | 22 | return min < root.Val && root.Val < max && 23 | recur(min, root.Val, root.Left) && 24 | recur(root.Val, max, root.Right) 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0099.recover-binary-search-tree/README.md: -------------------------------------------------------------------------------- 1 | # [99. Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) 2 | 3 | ## 题目 4 | Two elements of a binary search tree (BST) are swapped by mistake. 5 | 6 | Recover the tree without changing its structure. 7 | 8 | 9 | Note: 10 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 11 | 12 | ## 解题思路 13 | 14 | 见程序注释 15 | -------------------------------------------------------------------------------- /Algorithms/0100.same-tree/README.md: -------------------------------------------------------------------------------- 1 | # [100. Same Tree](https://leetcode.com/problems/same-tree/) 2 | 3 | ## 题目 4 | Given two binary trees, write a function to check if they are equal or not. 5 | 6 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 7 | 8 | ## 解题思路 9 | 10 | 见程序注释 11 | -------------------------------------------------------------------------------- /Algorithms/0100.same-tree/same-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0100 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func isSameTree(p *TreeNode, q *TreeNode) bool { 10 | if p == nil && q== nil { 11 | return true 12 | } 13 | 14 | if p == nil || q == nil { 15 | return false 16 | } 17 | 18 | return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/0101.symmetric-tree/README.md: -------------------------------------------------------------------------------- 1 | # [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) 2 | 3 | ## 题目 4 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 5 | 6 | ``` 7 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 8 | 1 9 | / \ 10 | 2 2 11 | / \ / \ 12 | 3 4 4 3 13 | 14 | But the following [1,2,2,null,3,null,3] is not: 15 | 1 16 | / \ 17 | 2 2 18 | \ \ 19 | 3 3 20 | ``` 21 | 22 | Note: 23 | Bonus points if you could solve it both recursively and iteratively. 24 | 25 | ## 解题思路 26 | 27 | 见程序注释 28 | -------------------------------------------------------------------------------- /Algorithms/0101.symmetric-tree/symmetric-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0101 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func isSymmetric(root *TreeNode) bool { 10 | if root == nil { 11 | return true 12 | } 13 | 14 | return recur(root.Left, root.Right) 15 | } 16 | 17 | func recur(left, right *TreeNode) bool { 18 | if left == nil && right == nil { 19 | return true 20 | } 21 | 22 | if left == nil || right == nil { 23 | return false 24 | } 25 | 26 | return left.Val == right.Val && recur(left.Left, right.Right) && recur(left.Right, right.Left) 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/0101.symmetric-tree/symmetric-tree_test.go: -------------------------------------------------------------------------------- 1 | package Problem0101 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0101(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | pre, in []int 18 | ans bool 19 | }{ 20 | 21 | { 22 | []int{}, 23 | []int{}, 24 | true, 25 | }, 26 | 27 | { 28 | []int{1, 2, 2}, 29 | []int{2, 1, 2}, 30 | true, 31 | }, 32 | 33 | { 34 | []int{1, 2, 3, 2, 3}, 35 | []int{2, 3, 1, 2, 3}, 36 | false, 37 | }, 38 | } 39 | 40 | for _, tc := range tcs { 41 | fmt.Printf("~~%v~~\n", tc) 42 | 43 | ast.Equal(tc.ans, isSymmetric(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/0102.binary-tree-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 | # [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) 2 | 3 | ## 题目 4 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 5 | 6 | For example: 7 | Given binary tree [3,9,20,null,null,15,7], 8 | ``` 9 | 3 10 | / \ 11 | 9 20 12 | / \ 13 | 15 7 14 | ``` 15 | return its level order traversal as: 16 | ``` 17 | [ 18 | [3], 19 | [9,20], 20 | [15,7] 21 | ] 22 | ``` 23 | ## 解题思路 24 | 25 | 见程序注释 26 | -------------------------------------------------------------------------------- /Algorithms/0102.binary-tree-level-order-traversal/binary-tree-level-order-traversal.go: -------------------------------------------------------------------------------- 1 | package Problem0102 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func levelOrder(root *TreeNode) [][]int { 10 | res := [][]int{} 11 | var dfs func(*TreeNode, int) 12 | 13 | dfs = func(root *TreeNode, level int) { 14 | if root == nil { 15 | return 16 | } 17 | 18 | // 出现了新的 level 19 | if level >= len(res) { 20 | res = append(res, []int{}) 21 | } 22 | res[level] = append(res[level], root.Val) 23 | 24 | dfs(root.Left, level+1) 25 | dfs(root.Right, level+1) 26 | } 27 | 28 | dfs(root, 0) 29 | 30 | return res 31 | } -------------------------------------------------------------------------------- /Algorithms/0102.binary-tree-level-order-traversal/binary-tree-level-order-traversal_test.go: -------------------------------------------------------------------------------- 1 | package Problem0102 2 | 3 | import ( 4 | "fmt" 5 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func Test_Problem0102(t *testing.T) { 12 | ast := assert.New(t) 13 | 14 | // tcs is testcase slice 15 | tcs := []struct { 16 | pre, in []int 17 | ans [][]int 18 | }{ 19 | 20 | { 21 | []int{3, 9, 20, 15, 7}, 22 | []int{9, 3, 15, 20, 7}, 23 | [][]int{ 24 | []int{3}, 25 | []int{9, 20}, 26 | []int{15, 7}, 27 | }, 28 | }, 29 | 30 | // 可以多个 testcase 31 | } 32 | 33 | for _, tc := range tcs { 34 | fmt.Printf("~~%v~~\n", tc) 35 | 36 | ast.Equal(tc.ans, levelOrder(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/0103.binary-tree-zigzag-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 | # [103. Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) 2 | 3 | ## 题目 4 | Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). 5 | 6 | For example: 7 | Given binary tree [3,9,20,null,null,15,7], 8 | ``` 9 | 3 10 | / \ 11 | 9 20 12 | / \ 13 | 15 7 14 | ``` 15 | 16 | return its zigzag level order traversal as: 17 | ``` 18 | [ 19 | [3], 20 | [20,9], 21 | [15,7] 22 | ] 23 | ``` 24 | ## 解题思路 25 | 26 | 见程序注释 27 | -------------------------------------------------------------------------------- /Algorithms/0103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.go: -------------------------------------------------------------------------------- 1 | package Problem0103 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func zigzagLevelOrder(root *TreeNode) [][]int { 10 | res := [][]int{} 11 | 12 | var dfs func(*TreeNode, int) 13 | dfs = func(root *TreeNode, level int) { 14 | if root == nil { 15 | return 16 | } 17 | // 出现了新的 level 18 | if level >= len(res) { 19 | res = append(res, []int{}) 20 | } 21 | // 与 102 题相比,level 的奇偶不同,append 会不同。 22 | if level%2 == 0 { 23 | res[level] = append(res[level], root.Val) 24 | } else { 25 | temp := make([]int , len(res[level])+1) 26 | temp[0] = root.Val 27 | copy(temp[1:], res[level]) 28 | res[level] = temp 29 | } 30 | dfs(root.Left, level+1) 31 | dfs(root.Right, level+1) 32 | } 33 | 34 | dfs(root, 0) 35 | 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal_test.go: -------------------------------------------------------------------------------- 1 | package Problem0103 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0103(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | pre, in []int 18 | ans [][]int 19 | }{ 20 | 21 | { 22 | []int{3, 9, 20, 15, 7}, 23 | []int{9, 3, 15, 20, 7}, 24 | [][]int{ 25 | []int{3}, 26 | []int{20, 9}, 27 | []int{15, 7}, 28 | }, 29 | }, 30 | 31 | // 可以多个 testcase 32 | } 33 | 34 | for _, tc := range tcs { 35 | fmt.Printf("~~%v~~\n", tc) 36 | 37 | ast.Equal(tc.ans, zigzagLevelOrder(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/0104.maximum-depth-of-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | # [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) 2 | 3 | ## 题目 4 | Given a binary tree, find its maximum depth. 5 | 6 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | 8 | ## 解题思路 9 | 10 | 见程序注释 11 | -------------------------------------------------------------------------------- /Algorithms/0104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0104 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func maxDepth(root *TreeNode) int { 10 | if root == nil { 11 | return 0 12 | } 13 | 14 | return 1 + max(maxDepth(root.Left), maxDepth(root.Right)) 15 | } 16 | 17 | func max(a, b int) int { 18 | if a > b { 19 | return a 20 | } 21 | return b 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/0104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree_test.go: -------------------------------------------------------------------------------- 1 | package Problem0104 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0104(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | pre, in []int 18 | ans int 19 | }{ 20 | 21 | { 22 | []int{}, 23 | []int{}, 24 | 0, 25 | }, 26 | 27 | { 28 | []int{3, 9, 20, 15, 7}, 29 | []int{9, 3, 15, 20, 7}, 30 | 3, 31 | }, 32 | 33 | { 34 | []int{3, 9, 20, 15, 10, 7}, 35 | []int{9, 3, 10, 15, 20, 7}, 36 | 4, 37 | }, 38 | 39 | // 可以多个 testcase 40 | } 41 | 42 | for _, tc := range tcs { 43 | fmt.Printf("~~%v~~\n", tc) 44 | 45 | ast.Equal(tc.ans, maxDepth(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/0105.construct-binary-tree-from-preorder-and-inorder-traversal/README.md: -------------------------------------------------------------------------------- 1 | # [105. Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) 2 | 3 | ## 题目 4 | Given preorder and inorder traversal of a tree, construct the binary tree. 5 | 6 | **Note:** 7 | You may assume that duplicates do not exist in the tree. 8 | 9 | ## 解题思路 10 | 11 | 见程序注释 12 | -------------------------------------------------------------------------------- /Algorithms/0105.construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.go: -------------------------------------------------------------------------------- 1 | package Problem0105 2 | import ( 3 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 4 | ) 5 | type TreeNode = kit.TreeNode 6 | 7 | func buildTree(pre, in []int) *TreeNode { 8 | 9 | if len(in) == 0 { 10 | return nil 11 | } 12 | 13 | res := &TreeNode{ 14 | Val: pre[0], 15 | } 16 | 17 | if len(in) == 1 { 18 | return res 19 | } 20 | 21 | idx := indexOf(res.Val, in) 22 | 23 | res.Left = buildTree(pre[1:idx+1], in[:idx]) 24 | res.Right = buildTree(pre[idx+1:], in[idx+1:]) 25 | 26 | return res 27 | } 28 | 29 | func indexOf(val int, nums []int) int { 30 | for i, v := range nums { 31 | if v == val { 32 | return i 33 | } 34 | } 35 | 36 | return 0 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0106.construct-binary-tree-from-inorder-and-postorder-traversal/README.md: -------------------------------------------------------------------------------- 1 | # [106. Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) 2 | 3 | ## 题目 4 | Given inorder and postorder traversal of a tree, construct the binary tree. 5 | 6 | **Note:** 7 | You may assume that duplicates do not exist in the tree. 8 | 9 | ## 解题思路 10 | 11 | 见程序注释 12 | -------------------------------------------------------------------------------- /Algorithms/0106.construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.go: -------------------------------------------------------------------------------- 1 | package Problem0106 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func buildTree(in []int, post []int) *TreeNode { 10 | if len(in) == 0 { 11 | return nil 12 | } 13 | 14 | res := &TreeNode{ 15 | Val: post[len(post)-1], 16 | } 17 | 18 | if len(in) == 1 { 19 | return res 20 | } 21 | 22 | idx := indexOf(res.Val, in) 23 | 24 | res.Left = buildTree(in[:idx], post[:idx]) 25 | res.Right = buildTree(in[idx+1:], post[idx:len(post)-1]) 26 | 27 | return res 28 | } 29 | 30 | 31 | func indexOf(val int, nums []int) int { 32 | for i, v := range nums { 33 | if v == val { 34 | return i 35 | } 36 | } 37 | 38 | return 0 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/0107.binary-tree-level-order-traversal-ii/README.md: -------------------------------------------------------------------------------- 1 | # [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/) 2 | 3 | ## 题目 4 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 5 | 6 | 7 | For example: 8 | Given binary tree [3,9,20,null,null,15,7], 9 | ``` 10 | 3 11 | / \ 12 | 9 20 13 | / \ 14 | 15 7 15 | ``` 16 | 17 | return its bottom-up level order traversal as: 18 | ``` 19 | [ 20 | [15,7], 21 | [9,20], 22 | [3] 23 | ] 24 | ``` 25 | 26 | ## 解题思路 27 | 28 | 见程序注释 29 | -------------------------------------------------------------------------------- /Algorithms/0107.binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0107 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func levelOrderBottom(root *TreeNode) [][]int { 10 | res := [][]int{} 11 | 12 | var dfs func(*TreeNode, int) 13 | dfs = func(root *TreeNode, level int) { 14 | if root == nil { 15 | return 16 | } 17 | 18 | // 出现了新的 level 19 | if level >= len(res) { 20 | res = append([][]int{[]int{}}, res... ) 21 | } 22 | n := len(res ) 23 | res[n-level-1] = append(res[n-level-1], root.Val) 24 | 25 | dfs(root.Left, level+1) 26 | dfs(root.Right, level+1) 27 | } 28 | 29 | dfs(root, 0) 30 | 31 | return res 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/0107.binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii_test.go: -------------------------------------------------------------------------------- 1 | package Problem0107 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func Test_Problem0107(t *testing.T) { 12 | ast := assert.New(t) 13 | 14 | // tcs is testcase slice 15 | tcs := []struct { 16 | pre, in []int 17 | ans [][]int 18 | }{ 19 | 20 | { 21 | []int{3, 9, 20, 15, 7}, 22 | []int{9, 3, 15, 20, 7}, 23 | [][]int{ 24 | []int{15, 7}, 25 | []int{9, 20}, 26 | []int{3}, 27 | }, 28 | }, 29 | 30 | // 可以多个 testcase 31 | } 32 | 33 | for _, tc := range tcs { 34 | fmt.Printf("~~%v~~\n", tc) 35 | 36 | ast.Equal(tc.ans, levelOrderBottom(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/0108.convert-sorted-array-to-binary-search-tree/README.md: -------------------------------------------------------------------------------- 1 | # [108. Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) 2 | 3 | ## 题目 4 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 5 | 6 | ## 解题思路 7 | > 高度平衡二叉树是每一个节点的两个子树的深度差不能超过1。 8 | 见程序注释 -------------------------------------------------------------------------------- /Algorithms/0108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0108 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func sortedArrayToBST(nums []int) *TreeNode { 10 | if len(nums) == 0 { 11 | return nil 12 | } 13 | 14 | mid := len(nums) / 2 15 | return &TreeNode{ 16 | Val: nums[mid], 17 | Left: sortedArrayToBST(nums[:mid]), 18 | Right: sortedArrayToBST(nums[mid+1:]), 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/0108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree_test.go: -------------------------------------------------------------------------------- 1 | package Problem0108 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0108(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | nums []int 18 | pre []int 19 | }{ 20 | 21 | { 22 | []int{}, 23 | nil, 24 | }, 25 | 26 | { 27 | []int{1, 2, 3, 4, 5, 6, 7}, 28 | []int{4, 2, 1, 3, 6, 5, 7}, 29 | }, 30 | 31 | // 可以多个 testcase 32 | } 33 | 34 | for _, tc := range tcs { 35 | fmt.Printf("~~%v~~\n", tc) 36 | 37 | ast.Equal(tc.pre, kit.Tree2Preorder(sortedArrayToBST(tc.nums)), "输入:%v", tc) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/0109.convert-sorted-list-to-binary-search-tree/109.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0109.convert-sorted-list-to-binary-search-tree/109.png -------------------------------------------------------------------------------- /Algorithms/0109.convert-sorted-list-to-binary-search-tree/README.md: -------------------------------------------------------------------------------- 1 | # [109. Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) 2 | 3 | ## 题目 4 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 5 | 6 | ## 解题思路 7 | 8 | 见程序注释 9 | 10 | 又见 100% ,感谢 LeetCode 服务器。 11 | 12 | ![100%](109.png) -------------------------------------------------------------------------------- /Algorithms/0109.convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0109 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type ListNode = kit.ListNode 8 | type TreeNode = kit.TreeNode 9 | 10 | func sortedListToBST(head *ListNode) *TreeNode { 11 | return sortedArrayToBST(list2Slice(head)) 12 | } 13 | 14 | func list2Slice(head *ListNode) []int { 15 | res := []int{} 16 | for head != nil { 17 | res = append(res, head.Val) 18 | head = head.Next 19 | } 20 | 21 | return res 22 | } 23 | 24 | func sortedArrayToBST(nums []int) *TreeNode { 25 | if len(nums) == 0 { 26 | return nil 27 | } 28 | 29 | mid := len(nums) / 2 30 | return &TreeNode{ 31 | Val: nums[mid], 32 | Left: sortedArrayToBST(nums[:mid]), 33 | Right: sortedArrayToBST(nums[mid+1:]), 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0109.convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree_test.go: -------------------------------------------------------------------------------- 1 | package Problem0109 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0109(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | head []int 18 | ans []int 19 | }{ 20 | 21 | { 22 | []int{}, 23 | nil, 24 | }, 25 | 26 | { 27 | []int{1, 2, 3, 4, 5, 6, 7, 8}, 28 | []int{1, 2, 3, 4, 5, 6, 7, 8}, 29 | }, 30 | 31 | // 可以多个 testcase 32 | } 33 | 34 | for _, tc := range tcs { 35 | fmt.Printf("~~%v~~\n", tc) 36 | 37 | ast.Equal(tc.ans, kit.Tree2Inorder(sortedListToBST(kit.Slice2List(tc.head))), "输入:%v", tc) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/0110.balanced-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | # [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) 2 | 3 | ## 题目 4 | Given a binary tree, determine if it is height-balanced. 5 | 6 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | 8 | ## 解题思路 9 | 10 | 见程序注释 11 | -------------------------------------------------------------------------------- /Algorithms/0110.balanced-binary-tree/balanced-binary-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0110 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func isBalanced(root *TreeNode) bool { 10 | _, isBalanced := recur(root) 11 | return isBalanced 12 | } 13 | 14 | func recur(root *TreeNode) (int, bool) { 15 | if root == nil { 16 | return 0, true 17 | } 18 | 19 | leftDepth, leftIsBalanced := recur(root.Left) 20 | rightDepth, rightIsBalanced := recur(root.Right) 21 | 22 | if leftIsBalanced && rightIsBalanced && 23 | -1 <= leftDepth-rightDepth && leftDepth - rightDepth <= 1 { 24 | return max(leftDepth, rightDepth) + 1, true 25 | } 26 | 27 | return 0, false 28 | } 29 | 30 | func max(a, b int) int { 31 | if a > b { 32 | return a 33 | } 34 | return b 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0110.balanced-binary-tree/balanced-binary-tree_test.go: -------------------------------------------------------------------------------- 1 | package Problem0110 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0110(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | pre, in []int 18 | ans bool 19 | }{ 20 | 21 | { 22 | []int{2, 1, 5, 4, 3, 6, 7}, 23 | []int{1, 2, 3, 4, 5, 6, 7}, 24 | false, 25 | }, 26 | 27 | { 28 | []int{4, 2, 1, 3, 6, 5, 7}, 29 | []int{1, 2, 3, 4, 5, 6, 7}, 30 | true, 31 | }, 32 | 33 | // 可以多个 testcase 34 | } 35 | 36 | for _, tc := range tcs { 37 | fmt.Printf("~~%v~~\n", tc) 38 | 39 | ast.Equal(tc.ans, isBalanced(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/0111.minimum-depth-of-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | # [111. Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) 2 | 3 | ## 题目 4 | Given a binary tree, find its minimum depth. 5 | 6 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 7 | 8 | ## 解题思路 9 | 10 | 见程序注释 11 | -------------------------------------------------------------------------------- /Algorithms/0111.minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | package Problem0111 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | // 注意审题,没有子节点的 node 才是 leaf 10 | func minDepth(root *TreeNode) int { 11 | switch { 12 | case root == nil: 13 | return 0 14 | case root.Left == nil: 15 | return 1 + minDepth(root.Right) 16 | case root.Right == nil: 17 | return 1 + minDepth(root.Left) 18 | default: 19 | return 1 + min(minDepth(root.Left), minDepth(root.Right)) 20 | } 21 | } 22 | 23 | func min(a, b int) int { 24 | if a < b { 25 | return a 26 | } 27 | return b 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/0112.path-sum/README.md: -------------------------------------------------------------------------------- 1 | # [112. Path Sum](https://leetcode.com/problems/path-sum/) 2 | 3 | ## 题目 4 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 5 | 6 | For example: 7 | Given the below binary tree and sum = 22, 8 | ``` 9 | 5 10 | / \ 11 | 4 8 12 | / / \ 13 | 11 13 4 14 | / \ \ 15 | 7 2 1 16 | ``` 17 | 18 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 19 | 20 | ## 解题思路 21 | 22 | 见程序注释 23 | -------------------------------------------------------------------------------- /Algorithms/0112.path-sum/path-sum.go: -------------------------------------------------------------------------------- 1 | package Problem0112 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func hasPathSum(root *TreeNode, sum int) bool { 10 | if root == nil { 11 | return false 12 | } 13 | 14 | sum -= root.Val 15 | 16 | if root.Left == nil && root.Right == nil { 17 | // 此时 root 才为 leaf 18 | return sum == 0 19 | } 20 | 21 | return hasPathSum(root.Left, sum) || hasPathSum(root.Right, sum) 22 | } -------------------------------------------------------------------------------- /Algorithms/0113.path-sum-ii/README.md: -------------------------------------------------------------------------------- 1 | # [113. Path Sum II](https://leetcode.com/problems/path-sum-ii/) 2 | 3 | ## 题目 4 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 5 | 6 | 7 | For example: 8 | Given the below binary tree and sum = 22, 9 | ``` 10 | 5 11 | / \ 12 | 4 8 13 | / / \ 14 | 11 13 4 15 | / \ / \ 16 | 7 2 5 1 17 | ``` 18 | return 19 | ``` 20 | [ 21 | [5,4,11,2], 22 | [5,8,4,5] 23 | ] 24 | ``` 25 | ## 解题思路 26 | 27 | 见程序注释 28 | -------------------------------------------------------------------------------- /Algorithms/0114.flatten-binary-tree-to-linked-list/README.md: -------------------------------------------------------------------------------- 1 | # [114. Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) 2 | 3 | ## 题目 4 | Given a binary tree, flatten it to a linked list in-place. 5 | 6 | 7 | ``` 8 | For example, 9 | Given 10 | 1 11 | / \ 12 | 2 5 13 | / \ \ 14 | 3 4 6 15 | 16 | The flattened tree should look like: 17 | 1 18 | \ 19 | 2 20 | \ 21 | 3 22 | \ 23 | 4 24 | \ 25 | 5 26 | \ 27 | 6 28 | ``` 29 | 30 | click to show hints. 31 | 32 | Hints: 33 | If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. 34 | 35 | ## 解题思路 36 | 37 | 见程序注释 38 | -------------------------------------------------------------------------------- /Algorithms/0114.flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.go: -------------------------------------------------------------------------------- 1 | package Problem0114 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func flatten(root *TreeNode) { 10 | recur(root) 11 | } 12 | 13 | // recur 会 flatten root,并返回 flatten 后的 leaf 节点 14 | func recur(root *TreeNode) *TreeNode { 15 | if root == nil || 16 | (root.Left == nil && root.Right == nil) { 17 | return root 18 | } 19 | 20 | if root.Left == nil { 21 | return recur(root.Right) 22 | } 23 | 24 | if root.Right == nil { 25 | root.Right = root.Left 26 | root.Left = nil 27 | return recur(root.Right) 28 | } 29 | 30 | res := recur(root.Right) 31 | recur(root.Left).Right = root.Right 32 | root.Right = root.Left 33 | // 不要忘记封闭 left 节点 34 | root.Left = nil 35 | 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0115.distinct-subsequences/README.md: -------------------------------------------------------------------------------- 1 | # [115. Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/) 2 | 3 | ## 题目 4 | Given a string S and a string T, count the number of distinct subsequences of S which equals T. 5 | 6 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 7 | 8 | Here is an example: 9 | ``` 10 | S = "rabbbit", T = "rabbit" 11 | Return 3. 12 | ``` 13 | 14 | ## 解题思路 15 | 16 | 见程序注释 17 | -------------------------------------------------------------------------------- /Algorithms/0115.distinct-subsequences/distinct-subsequences.go: -------------------------------------------------------------------------------- 1 | package Problem0115 2 | 3 | func numDistinct(s string, t string) int { 4 | m, n := len(s), len(t) 5 | 6 | dp := make([]int, m+1) 7 | for i := 0; i < m+1; i++ { 8 | dp[i] = 1 9 | } 10 | 11 | // dp[i] 在更新前的值,即 s[:i] 与 t[:j] 的匹配值 12 | // 有可能会在更新 dp[i+1] ,即 s[:i] 与 t[:j+1] 的匹配值,的时候用到 13 | // 利用 prev 保存起来 14 | var prev int 15 | 16 | for j := 0; j < n; j++ { 17 | dp[j], prev = 0, dp[j] 18 | 19 | for i := j + 1; i < m+1; i++ { 20 | // 对于 dp[i] 来说 21 | // s[:i] 中符合条件的子字符串,按照是否包含 s[i-1],可以分成两个部分: 22 | // 第一部分: 23 | // **不**包含 s[i-1], 24 | // 这部分的数量,等于 dp[i-1] 25 | // 第二部分: 26 | // 包含 s[i-1] 27 | // 这部分,只有当 s[i-1] == t[j-1] 的时候,才存在 28 | // 存在的话,这部分的数量,等于 prev 29 | if t[j] == s[i-1] { 30 | dp[i], prev = dp[i-1]+prev, dp[i] 31 | } else { 32 | dp[i], prev = dp[i-1], dp[i] 33 | } 34 | } 35 | } 36 | 37 | return dp[m] 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/0118.pascals-triangle/README.md: -------------------------------------------------------------------------------- 1 | # [118. Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/) 2 | 3 | ## 题目 4 | Given numRows, generate the first numRows of Pascal's triangle. 5 | 6 | For example, given numRows = 5, Return 7 | ``` 8 | [ 9 | [1], 10 | [1,1], 11 | [1,2,1], 12 | [1,3,3,1], 13 | [1,4,6,4,1] 14 | ] 15 | ``` 16 | ## 解题思路 17 | 按照 numRows 分情况讨论 18 | 19 | ## 总结 20 | 21 | 22 | -------------------------------------------------------------------------------- /Algorithms/0118.pascals-triangle/pascals-triangle.go: -------------------------------------------------------------------------------- 1 | package Problem0118 2 | 3 | func generate(numRows int) [][]int { 4 | res := [][]int{} 5 | if numRows == 0 { 6 | return res 7 | } 8 | 9 | res = append(res, []int{1}) 10 | if numRows == 1 { 11 | return res 12 | } 13 | 14 | for i := 1; i < numRows; i++ { 15 | res = append(res, genNext(res[i-1])) 16 | } 17 | 18 | return res 19 | } 20 | 21 | func genNext(p []int) []int { 22 | res := make([]int, 1, len(p)+1) 23 | res = append(res, p...) 24 | 25 | for i := 0; i < len(res)-1; i++ { 26 | res[i] += res[i+1] 27 | } 28 | 29 | return res 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/0119.pascals-triangle-ii/README.md: -------------------------------------------------------------------------------- 1 | # [119. Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/) 2 | 3 | ## 题目 4 | Given an index k, return the kth row of the Pascal's triangle. 5 | 6 | For example, given k = 3, 7 | Return [1,3,3,1]. 8 | 9 | Note: 10 | Could you optimize your algorithm to use only O(k) extra space? 11 | 12 | ## 解题思路 13 | 14 | 见程序注释 15 | -------------------------------------------------------------------------------- /Algorithms/0119.pascals-triangle-ii/pascals-triangle-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0119 2 | 3 | func getRow(rowIndex int) []int { 4 | res := make([]int, 1, rowIndex+1) 5 | res[0] = 1 6 | if rowIndex == 0 { 7 | return res 8 | } 9 | 10 | for i := 0; i < rowIndex; i++ { 11 | res = append(res, 1) 12 | for j := len(res) - 2; j > 0; j-- { 13 | res[j] += res[j-1] 14 | } 15 | } 16 | 17 | return res 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/0119.pascals-triangle-ii/pascals-triangle-ii_test.go: -------------------------------------------------------------------------------- 1 | package Problem0119 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | type para struct { 17 | rowIndex int 18 | } 19 | 20 | // ans 是答案 21 | type ans struct { 22 | one []int 23 | } 24 | 25 | func Test_Problem0119(t *testing.T) { 26 | ast := assert.New(t) 27 | 28 | qs := []question{ 29 | 30 | question{ 31 | para{ 32 | 3, 33 | }, 34 | ans{ 35 | []int{1, 3, 3, 1}, 36 | }, 37 | }, 38 | 39 | question{ 40 | para{ 41 | 0, 42 | }, 43 | ans{ 44 | []int{1}, 45 | }, 46 | }, 47 | // 如需多个测试,可以复制上方元素。 48 | } 49 | 50 | for _, q := range qs { 51 | a, p := q.ans, q.para 52 | fmt.Printf("~~%v~~\n", p) 53 | 54 | ast.Equal(a.one, getRow(p.rowIndex), "输入:%v", p) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Algorithms/0120.triangle/README.md: -------------------------------------------------------------------------------- 1 | # [120. Triangle](https://leetcode.com/problems/triangle/) 2 | 3 | ## 题目 4 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 5 | 6 | For example, given the following triangle 7 | ``` 8 | [ 9 | [`2`], 10 | [`3`,4], 11 | [6,`5`,7], 12 | [4,`1`,8,3] 13 | ] 14 | ``` 15 | 16 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 17 | 18 | **Note:** 19 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 20 | 21 | ## 解题思路 22 | 动态规划问题,见程序注释 23 | -------------------------------------------------------------------------------- /Algorithms/0120.triangle/triangle.go: -------------------------------------------------------------------------------- 1 | package Problem0120 2 | 3 | func minimumTotal(triangle [][]int) int { 4 | n := len(triangle) 5 | if n == 0 { 6 | return 0 7 | } 8 | 9 | // 从上往下,依次修改triangle 10 | // 使得 triangle[i][j] 表示到达 (i,j) 点的最小值 11 | for i := 1; i < n; i++ { 12 | for j := 0; j <= i; j++ { 13 | switch { 14 | case j == 0: 15 | triangle[i][0] += triangle[i-1][0] 16 | case j == i: 17 | triangle[i][i] += triangle[i-1][i-1] 18 | case triangle[i-1][j-1] < triangle[i-1][j]: 19 | triangle[i][j] += triangle[i-1][j-1] 20 | default: 21 | triangle[i][j] += triangle[i-1][j] 22 | } 23 | } 24 | } 25 | 26 | // 从最后一行,获取最小值 27 | min := triangle[n-1][0] 28 | for j := 1; j < n; j++ { 29 | if min > triangle[n-1][j] { 30 | min = triangle[n-1][j] 31 | } 32 | } 33 | 34 | return min 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0121.best-time-to-buy-and-sell-stock/README.md: -------------------------------------------------------------------------------- 1 | # [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) 2 | 3 | ## 题目 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 7 | Example 1: 8 | ``` 9 | Input: [7, 1, 5, 3, 6, 4] 10 | Output: 5 11 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 12 | 13 | ``` 14 | Example 2: 15 | ``` 16 | Input: [7, 6, 4, 3, 1] 17 | Output: 0 18 | In this case, no transaction is done, i.e. max profit = 0. 19 | ``` 20 | 21 | ## 解题思路 22 | 23 | 见程序注释 24 | -------------------------------------------------------------------------------- /Algorithms/0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.go: -------------------------------------------------------------------------------- 1 | package Problem0121 2 | 3 | func maxProfit(prices []int) int { 4 | max := 0 5 | temp := 0 6 | for i := 1; i < len(prices); i++ { 7 | temp += prices[i] - prices[i-1] 8 | if temp < 0 { 9 | temp = 0 10 | } 11 | if max < temp { 12 | max = temp 13 | } 14 | } 15 | 16 | return max 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/0122.best-time-to-buy-and-sell-stock-ii/README.md: -------------------------------------------------------------------------------- 1 | # [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) 2 | 3 | ## 题目 4 | 5 | Say you have an array for which the ith element is the price of a given stock on day i. 6 | 7 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 8 | 9 | 10 | ## 解题思路 11 | 12 | 13 | 见程序注释 14 | -------------------------------------------------------------------------------- /Algorithms/0122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0122 2 | 3 | func maxProfit(prices []int) int { 4 | res := 0 5 | 6 | for i := 1; i < len(prices); i++ { 7 | if prices[i] > prices[i-1] { 8 | res += prices[i] - prices[i-1] 9 | } 10 | } 11 | 12 | return res 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/0123.best-time-to-buy-and-sell-stock-iii/README.md: -------------------------------------------------------------------------------- 1 | # [123. Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) 2 | 3 | ## 题目 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 7 | 8 | Note: 9 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 10 | 11 | ## 解题思路 12 | 13 | max = max(prices[:i]) + max(prices[i:]) 14 | 15 | 见程序注释 16 | -------------------------------------------------------------------------------- /Algorithms/0124.binary-tree-maximum-path-sum/README.md: -------------------------------------------------------------------------------- 1 | # [124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) 2 | 3 | ## 题目 4 | Given a binary tree, find the maximum path sum. 5 | 6 | For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 7 | 8 | For example: 9 | ``` 10 | Given the below binary tree, 11 | 1 12 | / \ 13 | 2 3 14 | 15 | Return 6. 16 | ``` 17 | ## 解题思路 18 | 19 | 见程序注释 20 | -------------------------------------------------------------------------------- /Algorithms/0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.go: -------------------------------------------------------------------------------- 1 | package Problem0124 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func maxPathSum(root *TreeNode) int { 10 | if root == nil { 11 | return 0 12 | } 13 | 14 | maxSum := root.Val 15 | 16 | var dfs func(*TreeNode) int 17 | // 返回,以 root 为起点,所有可能路径的 sum 值中的最大值。 18 | dfs = func(root *TreeNode) int { 19 | if root == nil { 20 | return 0 21 | } 22 | 23 | left := max(0, dfs(root.Left)) 24 | right := max(0, dfs(root.Right)) 25 | sum := left + root.Val + right 26 | if maxSum < sum { 27 | maxSum = sum 28 | } 29 | 30 | return max(left, right) + root.Val 31 | } 32 | 33 | dfs(root) 34 | 35 | return maxSum 36 | } 37 | 38 | func max(a, b int) int { 39 | if a > b { 40 | return a 41 | } 42 | return b 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/0125.valid-palindrome/README.md: -------------------------------------------------------------------------------- 1 | # [125. Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) 2 | 3 | ## 题目 4 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | 6 | For example, 7 | ``` 8 | "A man, a plan, a canal: Panama" is a palindrome. 9 | "race a car" is not a palindrome. 10 | ``` 11 | Note: 12 | Have you consider that the string might be empty? This is a good question to ask during an interview. 13 | 14 | For the purpose of this problem, we define empty string as valid palindrome. 15 | 16 | ## 解题思路 17 | palindrome: 回文(指顺读和倒读都一样的词语) 18 | 19 | 见程序注释 20 | -------------------------------------------------------------------------------- /Algorithms/0125.valid-palindrome/valid-palindrome.go: -------------------------------------------------------------------------------- 1 | package Problem0125 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | func isPalindrome(s string) bool { 8 | s = strings.ToLower(s) 9 | i, j := 0, len(s)-1 10 | for i < j { 11 | for i < j && !isChar(s[i]) { 12 | i++ 13 | } 14 | for i < j && !isChar(s[j]) { 15 | j-- 16 | } 17 | if s[i] != s[j] { 18 | return false 19 | } 20 | i++ 21 | j-- 22 | } 23 | 24 | return true 25 | } 26 | 27 | // 判断 c 是否是需要检查的字符 28 | func isChar(c byte) bool { 29 | if ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') { 30 | return true 31 | } 32 | return false 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/0125.valid-palindrome/valid-palindrome_test.go: -------------------------------------------------------------------------------- 1 | package Problem0125 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func Test_Problem0125(t *testing.T) { 11 | ast := assert.New(t) 12 | 13 | // tcs is testcase slice 14 | tcs := []struct { 15 | s string 16 | ans bool 17 | }{ 18 | 19 | { 20 | "0p", 21 | false, 22 | }, 23 | 24 | { 25 | "0", 26 | true, 27 | }, 28 | 29 | { 30 | "race a car", 31 | false, 32 | }, 33 | 34 | { 35 | "A man, a plan, a canal: Panama", 36 | true, 37 | }, 38 | 39 | // 可以多个 testcase 40 | } 41 | 42 | for _, tc := range tcs { 43 | fmt.Printf("~~%v~~\n", tc) 44 | 45 | ast.Equal(tc.ans, isPalindrome(tc.s), "输入:%v", tc) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/0126.word-ladder-ii/126.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0126.word-ladder-ii/126.png -------------------------------------------------------------------------------- /Algorithms/0152.maximum-product-subarray/README.md: -------------------------------------------------------------------------------- 1 | # [152. Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) 2 | 3 | ## 题目 4 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 5 | 6 | For example, given the array `[2,3,-2,4]`, 7 | the contiguous subarray `[2,3]` has the largest product = `6`. 8 | 9 | ## 解题思路 10 | 见程序注释 11 | -------------------------------------------------------------------------------- /Algorithms/0152.maximum-product-subarray/maximum-product-subarray.go: -------------------------------------------------------------------------------- 1 | package Problem0152 2 | 3 | func maxProduct(a []int) int { 4 | cur, neg, max := 1, 1, a[0] 5 | 6 | for i := 0; i < len(a); i++ { 7 | 8 | switch { 9 | case a[i] > 0: 10 | cur, neg = a[i]*cur, a[i]*neg 11 | case a[i] < 0: 12 | cur, neg = a[i]*neg, a[i]*cur 13 | default: 14 | cur, neg = 0, 1 15 | } 16 | 17 | if max < cur { 18 | max = cur 19 | } 20 | 21 | if cur <= 0 { 22 | cur = 1 23 | } 24 | } 25 | 26 | return max 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/0153.find-minimum-in-rotated-sorted-array/README.md: -------------------------------------------------------------------------------- 1 | # [153. Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) 2 | 3 | ## 题目 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | 6 | (i.e., `0 1 2 4 5 6 7` might become `4 5 6 7 0 1 2`). 7 | 8 | Find the minimum element. 9 | 10 | You may assume no duplicate exists in the array. 11 | 12 | ## 解题思路 13 | 14 | 见程序注释 15 | -------------------------------------------------------------------------------- /Algorithms/0153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.go: -------------------------------------------------------------------------------- 1 | package Problem0153 2 | 3 | func findMin(a []int) int { 4 | Len := len(a) 5 | 6 | i := 1 7 | for i < Len && a[i-1] < a[i] { 8 | i++ 9 | } 10 | 11 | return a[i%Len] 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/0154.find-minimum-in-rotated-sorted-array-ii/README.md: -------------------------------------------------------------------------------- 1 | # [154. Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) 2 | 3 | ## 题目 4 | Follow up for "Find Minimum in Rotated Sorted Array": 5 | What if duplicates are allowed? 6 | 7 | Would this affect the run-time complexity? How and why? 8 | 9 | 10 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 11 | 12 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 13 | 14 | Find the minimum element. 15 | 16 | The array may contain duplicates. 17 | 18 | ## 解题思路 19 | 20 | 见程序注释 21 | -------------------------------------------------------------------------------- /Algorithms/0154.find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0154 2 | 3 | func findMin(a []int) int { 4 | L := len(a) 5 | 6 | if a[0] < a[L-1] { 7 | return a[0] 8 | } 9 | 10 | i, j := 0, L-1 11 | for i < j { 12 | if a[i] > a[i+1] { 13 | return a[i+1] 14 | } 15 | 16 | if a[j-1] > a[j] { 17 | return a[j] 18 | } 19 | 20 | i++ 21 | j-- 22 | } 23 | 24 | return a[i] 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0162.find-peak-element/README.md: -------------------------------------------------------------------------------- 1 | # [162. Find Peak Element](https://leetcode.com/problems/find-peak-element/) 2 | 3 | ## 题目 4 | A peak element is an element that is greater than its neighbors. 5 | 6 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 7 | 8 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 9 | 10 | You may imagine that num[-1] = num[n] = -∞. 11 | 12 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 13 | 14 | click to show spoilers. 15 | 16 | Note: 17 | Your solution should be in logarithmic complexity. 18 | 19 | 20 | ## 解题思路 21 | 注意理解题意,题目要求, 22 | 1. 返回任意一个局部高点即可 23 | 1. 要求程序的复杂度为O(logN) 24 | 见程序注释 25 | -------------------------------------------------------------------------------- /Algorithms/0162.find-peak-element/find-peak-element.go: -------------------------------------------------------------------------------- 1 | package Problem0162 2 | 3 | func findPeakElement(nums []int) int { 4 | low := -1 5 | high := len(nums) 6 | mid := (low + high) / 2 7 | 8 | // low +2 < high 9 | // low + 1 <= mid < high -1 10 | for low+1 <= mid && mid < high-1 { 11 | if nums[mid] < nums[mid+1] { 12 | low = mid 13 | } else { 14 | high = mid + 1 15 | } 16 | mid = (high + low) / 2 17 | } 18 | 19 | return low + 1 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/0167.two-sum-ii-input-array-is-sorted/README.md: -------------------------------------------------------------------------------- 1 | # [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) 2 | 3 | ## 题目 4 | 5 | Given an array of integers that is already sorted `in ascending order`, find two numbers such that they add up to a specific target number. 6 | 7 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 8 | 9 | You may assume that each input would have exactly one solution and you may not use the same element twice. 10 | 11 | ``` 12 | **Input:*** numbers={2, 7, 11, 15}, target=9 13 | ***Output:*** index1=1, index2=2 14 | ``` 15 | 16 | 17 | ## 解题思路 18 | 19 | 参考 [1.Two Sum](./Algorithms/0001.two-sum) 20 | -------------------------------------------------------------------------------- /Algorithms/0167.two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.go: -------------------------------------------------------------------------------- 1 | package Problem0167 2 | 3 | func twoSum(nums []int, target int) []int { 4 | m := make(map[int]int, len(nums)) 5 | 6 | for i, n := range nums { 7 | if m[target-n] != 0 { 8 | return []int{m[target-n], i + 1} 9 | } 10 | m[n] = i + 1 11 | } 12 | 13 | return nil 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/0169.majority-element/README.md: -------------------------------------------------------------------------------- 1 | # [169. Majority Element](https://leetcode.com/problems/majority-element/) 2 | 3 | ## 题目 4 | 5 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 6 | 7 | You may assume that the array is non-empty and the majority element always exist in the array. 8 | 9 | ## 解题思路 10 | 11 | 12 | 见程序注释 13 | -------------------------------------------------------------------------------- /Algorithms/0169.majority-element/majority-element.go: -------------------------------------------------------------------------------- 1 | package Problem0169 2 | 3 | func majorityElement(nums []int) int { 4 | // 根据题意 len[nums] > 0 且 出现次数大于 n/2 的元素存在。 5 | x, t := nums[0], 1 6 | 7 | for i := 1; i < len(nums); i++ { 8 | switch { 9 | case x == nums[i]: 10 | t++ 11 | case t > 0: 12 | t-- 13 | default: 14 | // 此时 x != nums[i] 且 t == 0 15 | // 可知 i 必定为 偶数 16 | // 假设 nums 中出现最多的元素是 z,其出现次数为 zn > n/2 17 | // 在 nums[:i] 中,z 出现次数 <=i/2 18 | // 那么,在 nums[i:] 中,z 出现的次数 >= zn - i/2 > n/2 - i/2 = (n-i)/2 19 | // 即 z 在 nums[i:] 中出现的次数,依然超过了 len(nums[i:])/2 20 | x = nums[i] 21 | t = 1 22 | } 23 | } 24 | 25 | return x 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/0188.best-time-to-buy-and-sell-stock-iv/best-time-to-buy-and-sell-stock-iv.go: -------------------------------------------------------------------------------- 1 | package Problem0188 2 | 3 | func maxProfit(k int, prices []int) int { 4 | size := len(prices) 5 | if size <= 1 { 6 | return 0 7 | } 8 | 9 | if k >= size { 10 | return profits(prices) 11 | } 12 | 13 | local := make([]int, k+1) 14 | global := make([]int, k+1) 15 | 16 | for i := 1; i < size; i++ { 17 | diff := prices[i] - prices[i-1] 18 | for j := k; j >= 1; j-- { 19 | local[j] = max(global[j-1]+max(diff, 0), local[j]+diff) 20 | global[j] = max(local[j], global[j]) 21 | } 22 | } 23 | 24 | return global[k] 25 | } 26 | 27 | func max(a, b int) int { 28 | if a > b { 29 | return a 30 | } 31 | return b 32 | } 33 | 34 | func profits(prices []int) int { 35 | res := 0 36 | for i := 1; i < len(prices); i++ { 37 | tmp := prices[i] - prices[i-1] 38 | if tmp > 0 { 39 | res += tmp 40 | } 41 | } 42 | 43 | return res 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/0189.rotate-array/README.md: -------------------------------------------------------------------------------- 1 | # [189. Rotate Array](https://leetcode.com/problems/rotate-array/) 2 | 3 | ## 题目 4 | 5 | Rotate an array of n elements to the right by k steps. 6 | For example, with n = 7 and k = 3, the array `[1,2,3,4,5,6,7]` is rotated to `[5,6,7,1,2,3,4]`. 7 | 8 | Note: 9 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 10 | 11 | 12 | [show hint] 13 | Hint: 14 | Could you do it in-place with O(1) extra space? 15 | 16 | 17 | Related problem: [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) 18 | 19 | ## 解题思路 20 | ### 三次翻转 21 | 1. nums 整体翻转 22 | 1. nums[:k] 翻转 23 | 1. nums[k:] 翻转 24 | -------------------------------------------------------------------------------- /Algorithms/0189.rotate-array/rotate-array.go: -------------------------------------------------------------------------------- 1 | package Problem0189 2 | 3 | func rotate(nums []int, k int) { 4 | // 我已经假定 k >= 0 5 | 6 | n := len(nums) 7 | 8 | if k > n { 9 | k %= n 10 | } 11 | if k == 0 || k == n { 12 | return 13 | } 14 | 15 | reverse(nums, 0, n-1) 16 | reverse(nums, 0, k-1) 17 | reverse(nums, k, n-1) 18 | } 19 | 20 | func reverse(nums []int, i, j int) { 21 | for i < j { 22 | nums[i], nums[j] = nums[j], nums[i] 23 | i++ 24 | j-- 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/0206.reverse-linked-list/README.md: -------------------------------------------------------------------------------- 1 | # [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) 2 | 3 | ## 题目 4 | Reverse a singly linked list. 5 | 6 | ## 解题思路 7 | 详见注释 8 | 9 | ## 总结 10 | 11 | 12 | -------------------------------------------------------------------------------- /Algorithms/0206.reverse-linked-list/reverse-linked-list.go: -------------------------------------------------------------------------------- 1 | package Problem0206 2 | 3 | func reverseList(head *ListNode) *ListNode { 4 | // prev 是所有已经逆转的节点的head 5 | var prev *ListNode 6 | 7 | // head 是下一个被逆转的节点 8 | for head != nil { 9 | // 让temp指向head.Next, 免得head.Next不见了. 10 | temp := head.Next 11 | // head称为已经逆转的节点的新head 12 | head.Next = prev 13 | // 让prev重新称为所有已被逆转节点的head 14 | prev = head 15 | // 让head指向下一个被逆转的节点 16 | head = temp 17 | } 18 | 19 | return prev 20 | } 21 | 22 | // ListNode 是链接节点 23 | type ListNode struct { 24 | Val int 25 | Next *ListNode 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/0209.minimum-size-subarray-sum/README.md: -------------------------------------------------------------------------------- 1 | # [209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) 2 | 3 | ## 题目 4 | Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. 5 | 6 | For example, given the array `[2,3,1,2,4,3]` and s = `7`, 7 | the subarray `[4,3]` has the minimal length under the problem constraint. 8 | 9 | **More practice:** 10 | 11 | If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 12 | 13 | ## 解题思路 14 | 充分利用题目信息,切片中的数,全部是正数。 15 | 16 | 见程序注释 17 | -------------------------------------------------------------------------------- /Algorithms/0209.minimum-size-subarray-sum/minimum-size-subarray-sum.go: -------------------------------------------------------------------------------- 1 | package Problem0209 2 | 3 | func minSubArrayLen(s int, a []int) int { 4 | n := len(a) 5 | res, i, j, sum := n+1, 0, 0, 0 6 | 7 | for j < n { 8 | sum += a[j] 9 | j++ 10 | 11 | for sum >= s { 12 | sum -= a[i] 13 | i++ 14 | if res > j-i+1 { 15 | res = j - i + 1 16 | } 17 | } 18 | } 19 | 20 | // res % (n+1) 是为了处理 sum(a) < s 的情况 21 | return res % (n + 1) 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/0216.combination-sum-iii/README.md: -------------------------------------------------------------------------------- 1 | # [216. Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) 2 | 3 | ## 题目 4 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 5 | 6 | Example 1: 7 | ``` 8 | Input: k = 3, n = 7 9 | Output: [[1,2,4]] 10 | ``` 11 | Example 2: 12 | ``` 13 | Input: k = 3, n = 9 14 | Output: [[1,2,6], [1,3,5], [2,3,4]] 15 | ``` 16 | 17 | 18 | Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 19 | 20 | ## 解题思路 21 | 常见的dfs搜索,见程序注释 22 | -------------------------------------------------------------------------------- /Algorithms/0216.combination-sum-iii/combination-sum-iii.go: -------------------------------------------------------------------------------- 1 | package Problem0216 2 | 3 | func combinationSum3(k int, n int) [][]int { 4 | res := [][]int{} 5 | temp := make([]int, k+1) 6 | used := make([]bool, 10) 7 | 8 | var dfs func(int, int) 9 | dfs = func(idx, remain int) { 10 | if idx == k { 11 | if remain < 10 && !used[remain] { 12 | temp[idx] = remain 13 | t := make([]int, k) 14 | copy(t, temp[1:]) 15 | res = append(res, t) 16 | } 17 | return 18 | } 19 | 20 | for i := temp[idx-1] + 1; i < 10; i++ { 21 | if remain-i < i { 22 | return 23 | } 24 | used[i] = true 25 | temp[idx] = i 26 | dfs(idx+1, remain-i) 27 | used[i] = false 28 | } 29 | } 30 | 31 | dfs(1, n) 32 | 33 | return res 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/0217.contains-duplicate/README.md: -------------------------------------------------------------------------------- 1 | # [217. Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) 2 | 3 | ## 题目 4 | 5 | 6 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 7 | 8 | 9 | 10 | ## 解题思路 11 | 12 | 13 | 见程序注释 14 | -------------------------------------------------------------------------------- /Algorithms/0217.contains-duplicate/contains-duplicate.go: -------------------------------------------------------------------------------- 1 | package Problem0217 2 | 3 | func containsDuplicate(nums []int) bool { 4 | // 利用 m 记录 nums 中的元素是否出现过 5 | m := make(map[int]bool, len(nums)) 6 | for _, n := range nums { 7 | if m[n] { 8 | return true 9 | } 10 | m[n] = true 11 | } 12 | 13 | return false 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/0217.contains-duplicate/contains-duplicate_test.go: -------------------------------------------------------------------------------- 1 | package Problem0217 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | type para struct { 17 | nums []int 18 | } 19 | 20 | // ans 是答案 21 | type ans struct { 22 | one bool 23 | } 24 | 25 | func Test_Problem0217(t *testing.T) { 26 | ast := assert.New(t) 27 | 28 | qs := []question{ 29 | 30 | question{ 31 | para{ 32 | []int{1, 2, 3, 3}, 33 | }, 34 | ans{ 35 | true, 36 | }, 37 | }, 38 | question{ 39 | para{ 40 | []int{1, 2, 3, 4}, 41 | }, 42 | ans{ 43 | false, 44 | }, 45 | }, 46 | 47 | // 如需多个测试,可以复制上方元素。 48 | } 49 | 50 | for _, q := range qs { 51 | a, p := q.ans, q.para 52 | fmt.Printf("~~%v~~\n", p) 53 | 54 | ast.Equal(a.one, containsDuplicate(p.nums), "输入:%v", p) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Algorithms/0219.contains-duplicate-ii/README.md: -------------------------------------------------------------------------------- 1 | # [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) 2 | 3 | ## 题目 4 | 5 | 6 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 7 | 8 | 9 | 10 | ## 解题思路 11 | 12 | 13 | 见程序注释 14 | -------------------------------------------------------------------------------- /Algorithms/0219.contains-duplicate-ii/contains-duplicate-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0219 2 | 3 | func containsNearbyDuplicate(nums []int, k int) bool { 4 | if k <= 0 { 5 | return false 6 | } 7 | 8 | // 利用 m 记录 a[i]中的值,每次出现的(索引号+1) 9 | m := make(map[int]int, len(nums)) 10 | 11 | for i, n := range nums { 12 | if m[n] != 0 && i-(m[n]-1) <= k { 13 | return true 14 | } 15 | m[n] = i + 1 16 | } 17 | 18 | return false 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/0228.summary-ranges/README.md: -------------------------------------------------------------------------------- 1 | # [228. Summary Ranges](https://leetcode.com/problems/summary-ranges/) 2 | 3 | ## 题目 4 | Given a sorted integer array without duplicates, return the summary of its ranges. 5 | 6 | Example 1: 7 | ``` 8 | Input: [0,1,2,4,5,7] 9 | Output: ["0->2","4->5","7"] 10 | ``` 11 | 12 | Example 2: 13 | ``` 14 | Input: [0,2,3,4,6,8,9] 15 | Output: ["0","2->4","6","8->9"] 16 | ``` 17 | 18 | 19 | ## 解题思路 20 | 21 | 见程序注释 22 | -------------------------------------------------------------------------------- /Algorithms/0228.summary-ranges/summary-ranges.go: -------------------------------------------------------------------------------- 1 | package Problem0228 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func summaryRanges(a []int) []string { 8 | res := []string{} 9 | 10 | l := len(a) 11 | if l == 0 { 12 | return res 13 | } 14 | 15 | begin := a[0] 16 | str := "" 17 | 18 | for i := 0; i < l; i++ { 19 | if i == l-1 || a[i]+1 != a[i+1] { 20 | if a[i] == begin { 21 | str = fmt.Sprintf("%d", begin) 22 | } else { 23 | str = fmt.Sprintf("%d->%d", begin, a[i]) 24 | } 25 | 26 | if i+1 < l { 27 | begin = a[i+1] 28 | } 29 | 30 | res = append(res, str) 31 | } 32 | } 33 | 34 | return res 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0229.majority-element-ii/README.md: -------------------------------------------------------------------------------- 1 | # [229. Majority Element II](https://leetcode.com/problems/majority-element-ii/) 2 | 3 | ## 题目 4 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. 5 | 6 | ## 解题思路 7 | 8 | 见程序注释 9 | -------------------------------------------------------------------------------- /Algorithms/0229.majority-element-ii/majority-element-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0229 2 | 3 | func majorityElement(a []int) []int { 4 | if len(a) <= 1 { 5 | return a 6 | } 7 | 8 | e1, e2, c1, c2 := 0, 1, 0, 0 9 | for _, e := range a { 10 | switch { 11 | case e == e1: 12 | c1++ 13 | case e == e2: 14 | c2++ 15 | case c1 == 0: 16 | e1 = e 17 | c1 = 1 18 | case c2 == 0: 19 | e2 = e 20 | c2 = 1 21 | default: 22 | c1-- 23 | c2-- 24 | } 25 | } 26 | 27 | res := []int{} 28 | 29 | if maj(a, e2) { 30 | res = append(res, e2) 31 | } 32 | 33 | if maj(a, e1) { 34 | res = append(res, e1) 35 | } 36 | 37 | return res 38 | } 39 | 40 | func maj(a []int, n int) bool { 41 | c := 0 42 | for _, e := range a { 43 | if e == n { 44 | c++ 45 | } 46 | } 47 | return c > (len(a) / 3) 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/0238.product-of-array-except-self/238.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0238.product-of-array-except-self/238.png -------------------------------------------------------------------------------- /Algorithms/0238.product-of-array-except-self/README.md: -------------------------------------------------------------------------------- 1 | # [238. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) 2 | 3 | ## 题目 4 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 5 | 6 | Solve it without division and in O(n). 7 | 8 | For example, given [1,2,3,4], return [24,12,8,6]. 9 | 10 | Follow up: 11 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 12 | 13 | ## 解题思路 14 | 15 | 见程序注释 16 | 17 | 有一个100%,主要还是服务器的功劳,因为我同样的程序再提交一次,就只有40%了。 18 | 19 | ![100%](238.png) -------------------------------------------------------------------------------- /Algorithms/0238.product-of-array-except-self/product-of-array-except-self.go: -------------------------------------------------------------------------------- 1 | package Problem0238 2 | 3 | func productExceptSelf(a []int) []int { 4 | l := len(a) 5 | // left[i] 是 a[i] 左侧所有元素的乘积 6 | // right[i] 是 a[i] 右侧所有元素的乘积 7 | left, right := make([]int, l), make([]int, l) 8 | 9 | // 题目已经保证了 n >= 2 10 | left[0], right[l-1] = 1, 1 11 | left[1], right[l-2] = a[0], a[l-1] 12 | 13 | for i := 2; i < l; i++ { 14 | left[i] = a[i-1] * left[i-1] 15 | right[l-i-1] = a[l-i] * right[l-i] 16 | } 17 | 18 | res := make([]int, l) 19 | for i := 0; i < l; i++ { 20 | res[i] = left[i] * right[i] 21 | } 22 | 23 | return res 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/0268.missing-number/README.md: -------------------------------------------------------------------------------- 1 | # [268. Missing Number](https://leetcode.com/problems/missing-number/) 2 | 3 | ## 题目 4 | 5 | 6 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 7 | 8 | 9 | For example, 10 | Given nums = [0, 1, 3] return 2. 11 | 12 | 13 | 14 | Note: 15 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 16 | 17 | 18 | ## 解题思路 19 | `^`:按位异或运算符,是双目运算符。 其功能是参与运算的两数各对应的二进位相异或,当两对应的二进位相异时,结果为1。 20 | 21 | 特别地,`^`支持交换律 22 | ``` 23 | 1^1^2^2^3^3 == 1^2^2^3^3^1 == 1^3^2^3^1^2 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /Algorithms/0268.missing-number/missing-number.go: -------------------------------------------------------------------------------- 1 | package Problem0268 2 | 3 | func missingNumber(nums []int) int { 4 | xor := 0 5 | 6 | for i, n := range nums { 7 | xor ^= i ^ n 8 | } 9 | 10 | // 所有的 i 再加上 len(nums),就相当于 0,1,...,n。 11 | // 利用 相同的数异或为0,及其交换律 12 | // xor 最后的值,就是那个缺失的数 13 | 14 | return xor ^ len(nums) 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/0283.move-zeroes/README.md: -------------------------------------------------------------------------------- 1 | # [283. Move Zeroes](https://leetcode.com/problems/move-zeroes/) 2 | 3 | ## 题目 4 | 5 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 6 | 7 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 8 | 9 | Note: 10 | 1. You must do this in-place without making a copy of the array. 11 | 1. Minimize the total number of operations. 12 | 13 | 14 | ## 解题思路 15 | 见注释 16 | -------------------------------------------------------------------------------- /Algorithms/0283.move-zeroes/move-zeroes.go: -------------------------------------------------------------------------------- 1 | package Problem0283 2 | 3 | func moveZeroes(nums []int) { 4 | l := len(nums) 5 | i, j := 0, 0 6 | 7 | for j < l { 8 | if nums[j] != 0 { 9 | nums[i] = nums[j] 10 | i++ 11 | } 12 | j++ 13 | } 14 | 15 | // 此时,i 以前的位置上,保存了nums中所有的非零数 16 | // 所以,只要把 nums[i:] 都置零,即可 17 | for i < l { 18 | nums[i] = 0 19 | i++ 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/0283.move-zeroes/move-zeroes_test.go: -------------------------------------------------------------------------------- 1 | package Problem0283 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | // one 代表第一个参数 17 | type para struct { 18 | nums []int 19 | } 20 | 21 | // ans 是答案 22 | // one 代表第一个答案 23 | type ans struct { 24 | one []int 25 | } 26 | 27 | func Test_Problem0283(t *testing.T) { 28 | ast := assert.New(t) 29 | 30 | qs := []question{ 31 | 32 | question{ 33 | para{[]int{1, 0, 1, 0, 3, 12}}, 34 | ans{[]int{1, 1, 3, 12, 0, 0}}, 35 | }, 36 | question{ 37 | para{[]int{0, 1, 0, 3, 12}}, 38 | ans{[]int{1, 3, 12, 0, 0}}, 39 | }, 40 | 41 | // 如需多个测试,可以复制上方元素。 42 | } 43 | 44 | for _, q := range qs { 45 | a, p := q.ans, q.para 46 | fmt.Printf("~~%v~~\n", p) 47 | moveZeroes(p.nums) 48 | ast.Equal(a.one, p.nums, "输入:%v", p) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/0287.find-the-duplicate-number/README.md: -------------------------------------------------------------------------------- 1 | # [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) 2 | 3 | ## 题目 4 | Given an array nums containing `n + 1` integers where each integer is between `1` and `n` (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 5 | 6 | Note: 7 | 1. You must not modify the array (assume the array is read only). 8 | 1. You must use only constant, O(1) extra space. 9 | 1. Your runtime complexity should be less than O(n2). 10 | 1. There is only one duplicate number in the array, but it could be repeated more than once. 11 | 12 | 13 | 14 | 15 | ## 解题思路 16 | 关键词, 快慢指针 17 | 18 | 见程序注释 19 | -------------------------------------------------------------------------------- /Algorithms/0287.find-the-duplicate-number/find-the-duplicate-number.go: -------------------------------------------------------------------------------- 1 | package Problem0287 2 | 3 | func findDuplicate(a []int) int { 4 | slow, fast := a[0], a[a[0]] 5 | for slow != fast { 6 | slow, fast = a[slow], a[a[fast]] 7 | } 8 | 9 | slow = 0 10 | for slow != fast { 11 | slow, fast = a[slow], a[fast] 12 | } 13 | 14 | return slow 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/0289.game-of-life/game-of-life.go: -------------------------------------------------------------------------------- 1 | package Problem0289 2 | 3 | func gameOfLife(board [][]int) { 4 | m := len(board) 5 | if m == 0 { 6 | return 7 | } 8 | 9 | n := len(board[0]) 10 | if n == 0 { 11 | return 12 | } 13 | 14 | check := func(i, j int) { 15 | count := 0 16 | for r := i - 1; r <= i+1; r++ { 17 | for c := j - 1; c <= j+1; c++ { 18 | if 0 <= r && r < m && 0 <= c && c < n && 19 | !(r == i && c == j) && 20 | (board[r][c] == 1 || board[r][c] == 2) { 21 | count++ 22 | } 23 | } 24 | } 25 | 26 | if board[i][j] == 1 && (count < 2 || count > 3) { 27 | board[i][j] = 2 28 | } else if board[i][j] == 0 && count == 3 { 29 | board[i][j] = 3 30 | } 31 | } 32 | 33 | for i := 0; i < m; i++ { 34 | for j := 0; j < n; j++ { 35 | check(i, j) 36 | } 37 | } 38 | 39 | for i := 0; i < m; i++ { 40 | for j := 0; j < n; j++ { 41 | board[i][j] %= 2 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/0380.insert-delete-getrandom-o1/insert-delete-getrandom-o1_test.go: -------------------------------------------------------------------------------- 1 | package Problem0380 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_Problem0380(t *testing.T) { 10 | ast := assert.New(t) 11 | 12 | rs := Constructor() 13 | 14 | ast.True(rs.Insert(1), "插入1") 15 | 16 | ast.False(rs.Remove(2), "删除2") 17 | 18 | ast.True(rs.Insert(2), "插入2") 19 | 20 | ast.Contains([]int{1, 2}, rs.GetRandom(), "返回1或2") 21 | 22 | ast.True(rs.Remove(1), "删除1") 23 | 24 | ast.False(rs.Insert(2), "再一次插入2") 25 | 26 | ast.Equal(2, rs.GetRandom(), "从只有2的集合中随机取出2") 27 | 28 | length := 100 29 | result := make([]int, length) 30 | for i := 0; i < 100; i++ { 31 | rs.Insert(i) 32 | result[i] = i 33 | } 34 | ast.Contains(result, rs.GetRandom(), "随机获取0~100之间的数") 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/0381.insert-delete-getrandom-o1-duplicates-allowed/381.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wufenggirl/LeetCode-in-Golang/f6bca86795dcfb1c31b7a5d9d2225e2953f1442c/Algorithms/0381.insert-delete-getrandom-o1-duplicates-allowed/381.png -------------------------------------------------------------------------------- /Algorithms/0414.third-maximum-number/third-maximum-number.go: -------------------------------------------------------------------------------- 1 | package Problem0414 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func thirdMax(nums []int) int { 8 | max1, max2, max3 := math.MinInt64, math.MinInt64, math.MinInt64 9 | for _, n := range nums { 10 | if n == max1 || n == max2 { // 过滤掉前两大的重复数据 11 | continue 12 | } 13 | 14 | switch { 15 | case max1 < n: 16 | max3, max2, max1 = max2, max1, n 17 | case max2 < n: 18 | max3, max2 = max2, n 19 | case max3 < n: 20 | max3 = n 21 | } 22 | } 23 | 24 | // 说明没有第三大的数 25 | if max3 == math.MinInt64 { 26 | return max1 27 | } 28 | 29 | return max3 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/0437.path-sum-iii/README.md: -------------------------------------------------------------------------------- 1 | # [437. Path Sum III](https://leetcode.com/problems/path-sum-iii/) 2 | 3 | ## 题目 4 | You are given a binary tree in which each node contains an integer value. 5 | 6 | Find the number of paths that sum to a given value. 7 | 8 | The path does not need to start or end at the root or a leaf, but it must go downwards 9 | (traveling only from parent nodes to child nodes). 10 | 11 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. 12 | 13 | Example: 14 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 15 | ``` 16 | 10 17 | / \ 18 | 5 -3 19 | / \ \ 20 | 3 2 11 21 | / \ \ 22 | 3 -2 1 23 | ``` 24 | Return 3. The paths that sum to 8 are: 25 | 1. 5 -> 3 26 | 2. 5 -> 2 -> 1 27 | 3. -3 -> 11 28 | 29 | ## 解题思路 30 | 31 | 见程序注释 32 | -------------------------------------------------------------------------------- /Algorithms/0437.path-sum-iii/path-sum-iii.go: -------------------------------------------------------------------------------- 1 | package Problem0437 2 | 3 | import ( 4 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 5 | ) 6 | 7 | type TreeNode = kit.TreeNode 8 | 9 | func pathSum(root *TreeNode, sum int) int { 10 | if root == nil { 11 | return 0 12 | } 13 | 14 | cnt := 0 15 | 16 | var dfs func(*TreeNode, int) 17 | dfs = func(node *TreeNode, sum int) { 18 | if node == nil { 19 | return 20 | } 21 | 22 | sum -= node.Val 23 | if sum == 0 { 24 | cnt++ 25 | } 26 | 27 | dfs(node.Left, sum) 28 | dfs(node.Right, sum) 29 | } 30 | 31 | dfs(root, sum) 32 | 33 | return cnt + 34 | pathSum(root.Left, sum) + 35 | pathSum(root.Right, sum) 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/0437.path-sum-iii/path-sum-iii_test.go: -------------------------------------------------------------------------------- 1 | package Problem0437 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/aQuaYi/LeetCode-in-Golang/kit" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func Test_Problem0437(t *testing.T) { 13 | ast := assert.New(t) 14 | 15 | // tcs is testcase slice 16 | tcs := []struct { 17 | pre, in []int 18 | sum int 19 | ans int 20 | }{ 21 | 22 | { 23 | []int{8, 5, 3, 5, -2, 2, 1, -3, 11, 0, 8}, 24 | []int{5, 3, -2, 5, 2, 1, 8, -3, 11, 0, 8}, 25 | 8, 26 | 8, 27 | }, 28 | 29 | // 可以多个 testcase 30 | } 31 | 32 | for _, tc := range tcs { 33 | fmt.Printf("~~%v~~\n", tc) 34 | 35 | ast.Equal(tc.ans, pathSum(kit.PreIn2Tree(tc.pre, tc.in), tc.sum), "输入:%v", tc) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0442.find-all-duplicates-in-an-array/README.md: -------------------------------------------------------------------------------- 1 | # [442. Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) 2 | 3 | ## 题目 4 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 5 | 6 | Find all the elements that appear twice in this array. 7 | 8 | Could you do it without extra space and in O(n) runtime? 9 | 10 | Example: 11 | ``` 12 | Input: 13 | [4,3,2,7,8,2,3,1] 14 | Output: 15 | [2,3] 16 | ``` 17 | ## 解题思路 18 | 19 | 见程序注释 20 | -------------------------------------------------------------------------------- /Algorithms/0442.find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.go: -------------------------------------------------------------------------------- 1 | package Problem0442 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func findDuplicates(a []int) []int { 8 | for i := 0; i < len(a); i++ { 9 | for a[i] != a[a[i]-1] { 10 | a[i], a[a[i]-1] = a[a[i]-1], a[i] 11 | } 12 | } 13 | 14 | res := make([]int, 0, len(a)) 15 | 16 | for i, n := range a { 17 | if i != n-1 { 18 | res = append(res, n) 19 | } 20 | } 21 | 22 | sort.Ints(res) 23 | 24 | return res 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0442.find-all-duplicates-in-an-array/find-all-duplicates-in-an-array_test.go: -------------------------------------------------------------------------------- 1 | package Problem0442 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | type para struct { 17 | nums []int 18 | } 19 | 20 | // ans 是答案 21 | type ans struct { 22 | one []int 23 | } 24 | 25 | func Test_Problem0442(t *testing.T) { 26 | ast := assert.New(t) 27 | 28 | qs := []question{ 29 | 30 | question{ 31 | para{ 32 | []int{4, 3, 2, 7, 8, 2, 3, 1}, 33 | }, 34 | ans{ 35 | []int{2, 3}, 36 | }, 37 | }, 38 | 39 | // 如需多个测试,可以复制上方元素。 40 | } 41 | 42 | for _, q := range qs { 43 | a, p := q.ans, q.para 44 | fmt.Printf("~~%v~~\n", p) 45 | 46 | ast.Equal(a.one, findDuplicates(p.nums), "输入:%v", p) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/0448.find-all-numbers-disappeared-in-an-array/README.md: -------------------------------------------------------------------------------- 1 | # [448. Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) 2 | 3 | ## 题目 4 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 5 | 6 | Find all the elements of [1, n] inclusive that do not appear in this array. 7 | 8 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 9 | 10 | Example: 11 | ``` 12 | Input: 13 | [4,3,2,7,8,2,3,1] 14 | 15 | Output: 16 | [5,6] 17 | ``` 18 | 19 | ## 解题思路 20 | 利用切片的元素的特性,不断地把 a[i] 直接放入 a[i]-1 位,这样就可以很快地排序好切片。 21 | 然后,检查切片各个元素的值是否符合属性,不符合的,就放入答案中。 22 | 23 | ## 总结 24 | 25 | 26 | -------------------------------------------------------------------------------- /Algorithms/0448.find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.go: -------------------------------------------------------------------------------- 1 | package Problem0448 2 | 3 | func findDisappearedNumbers(nums []int) []int { 4 | for i := 0; i < len(nums); i++ { 5 | for nums[i] != nums[nums[i]-1] { 6 | nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] 7 | } 8 | } 9 | 10 | res := make([]int, 0, len(nums)) 11 | 12 | for i, n := range nums { 13 | if n != i+1 { 14 | res = append(res, i+1) 15 | } 16 | } 17 | 18 | return res 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/0448.find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array_test.go: -------------------------------------------------------------------------------- 1 | package Problem0448 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | // one 代表第一个参数 17 | type para struct { 18 | one []int 19 | } 20 | 21 | // ans 是答案 22 | // one 代表第一个答案 23 | type ans struct { 24 | one []int 25 | } 26 | 27 | func Test_Problem0448(t *testing.T) { 28 | ast := assert.New(t) 29 | 30 | qs := []question{ 31 | 32 | question{ 33 | para{[]int{4, 3, 2, 7, 8, 2, 3, 1}}, 34 | ans{[]int{5, 6}}, 35 | }, 36 | 37 | // 如需多个测试,可以复制上方元素。 38 | } 39 | 40 | for _, q := range qs { 41 | a, p := q.ans, q.para 42 | fmt.Printf("~~%v~~\n", p) 43 | 44 | ast.Equal(a.one, findDisappearedNumbers(p.one), "输入:%v", p) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/0485.max-consecutive-ones/README.md: -------------------------------------------------------------------------------- 1 | # [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) 2 | 3 | ## 题目 4 | Given a binary array, find the maximum number of consecutive 1s in this array. 5 | 6 | Example 1: 7 | ``` 8 | Input: [1,1,0,1,1,1] 9 | Output: 3 10 | Explanation: The first two digits or the last three digits are consecutive 1s. 11 | The maximum number of consecutive 1s is 3. 12 | ``` 13 | Note: 14 | 1. The input array will only contain `0` and `1`. 15 | 1. The length of input array is a positive integer and will not exceed `10,000` 16 | 17 | ## 解题思路 18 | 1. 标记 19 | 2. 比较 20 | 3. 记录 21 | 22 | ## 总结 23 | 24 | 25 | -------------------------------------------------------------------------------- /Algorithms/0485.max-consecutive-ones/max-consecutive-ones.go: -------------------------------------------------------------------------------- 1 | package Problem0485 2 | 3 | func findMaxConsecutiveOnes(nums []int) int { 4 | max := 0 5 | 6 | for i, j := 0, -1; i < len(nums); i++ { 7 | if nums[i] == 0 { 8 | j = i 9 | } else { 10 | if max < i-j { 11 | max = i - j 12 | } 13 | } 14 | } 15 | 16 | return max 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/0485.max-consecutive-ones/max-consecutive-ones_test.go: -------------------------------------------------------------------------------- 1 | package Problem0485 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | // one 代表第一个参数 17 | type para struct { 18 | one []int 19 | } 20 | 21 | // ans 是答案 22 | // one 代表第一个答案 23 | type ans struct { 24 | one int 25 | } 26 | 27 | func Test_Problem0485(t *testing.T) { 28 | ast := assert.New(t) 29 | 30 | qs := []question{ 31 | 32 | question{ 33 | para{[]int{1, 1, 0, 1, 1, 1}}, 34 | ans{3}, 35 | }, 36 | 37 | question{ 38 | para{[]int{0, 1, 0, 0, 0}}, 39 | ans{1}, 40 | }, 41 | 42 | // 如需多个测试,可以复制上方元素。 43 | } 44 | 45 | for _, q := range qs { 46 | a, p := q.ans, q.para 47 | fmt.Printf("~~%v~~\n", p) 48 | 49 | ast.Equal(a.one, findMaxConsecutiveOnes(p.one), "输入:%v", p) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Algorithms/0495.teemo-attacking/teemo-attacking.go: -------------------------------------------------------------------------------- 1 | package Problem0495 2 | 3 | func findPoisonedDuration(time []int, duration int) int { 4 | res := 0 5 | n := len(time) 6 | if n == 0 { 7 | return 0 8 | } 9 | 10 | for i := 0; i+1 < n; i++ { 11 | res += min(duration, time[i+1]-time[i]) 12 | } 13 | 14 | return res + duration 15 | } 16 | 17 | func min(a, b int) int { 18 | if a < b { 19 | return a 20 | } 21 | return b 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/0526.beautiful-arrangement/beautiful-arrangement.go: -------------------------------------------------------------------------------- 1 | package Problem0526 2 | 3 | func countArrangement(N int) int { 4 | count := 0 5 | a := make([]int, N+1) 6 | for i := 0; i <= N; i++ { 7 | a[i] = i 8 | } 9 | 10 | var dfs func(int) 11 | dfs = func(idx int) { 12 | if idx == 0 { 13 | count++ 14 | return 15 | } 16 | 17 | for i := idx; i > 0; i-- { 18 | a[idx], a[i] = a[i], a[idx] 19 | if isBeautiful(a[idx], idx) { 20 | dfs(idx - 1) 21 | } 22 | a[idx], a[i] = a[i], a[idx] 23 | } 24 | } 25 | 26 | dfs(N) 27 | return count 28 | } 29 | 30 | func isBeautiful(i, j int) bool { 31 | return i%j == 0 || j%i == 0 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/0532.k-diff-pairs-in-an-array/k-diff-pairs-in-an-array.go: -------------------------------------------------------------------------------- 1 | package Problem0532 2 | 3 | func findPairs(nums []int, k int) int { 4 | if k < 0 { 5 | return 0 6 | } 7 | 8 | record := make(map[int]int) 9 | for _, num := range nums { 10 | record[num]++ 11 | } 12 | 13 | ans := 0 14 | 15 | if k == 0 { 16 | for _, count := range record { 17 | if count > 1 { 18 | ans++ 19 | } 20 | } 21 | return ans 22 | } 23 | 24 | for n := range record { 25 | if record[n-k] > 0 { 26 | ans++ 27 | } 28 | } 29 | 30 | return ans 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/0560.subarray-sum-equals-k/README.md: -------------------------------------------------------------------------------- 1 | # [560. Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) 2 | 3 | ## 题目 4 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 5 | 6 | Example 1: 7 | ``` 8 | Input:nums = [1,1,1], k = 2 9 | Output: 2 10 | ``` 11 | 12 | Note: 13 | 1. The length of the array is in range [1, 20,000]. 14 | 1. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 15 | 16 | ## 解题思路 17 | 18 | 见程序注释 19 | -------------------------------------------------------------------------------- /Algorithms/0560.subarray-sum-equals-k/subarray-sum-equals-k.go: -------------------------------------------------------------------------------- 1 | package Problem0560 2 | 3 | func subarraySum(a []int, k int) int { 4 | res, sum := 0, 0 5 | rec := make(map[int]int, len(a)) 6 | rec[0] = 1 7 | 8 | for i := range a { 9 | // sum 等于 a[:i] 中所有元素之和 10 | sum += a[i] 11 | // rec[x] 是 a[:i] 中所有和为 x 的连续子序列的个数 12 | // 假设 rec[sum-k] == 1 13 | // 那么,有且仅有一个 j,满足 0<= j < i,且 a[j:i] 中所有元素的和为 k 14 | res += rec[sum-k] 15 | // 更新 rec 16 | rec[sum]++ 17 | } 18 | 19 | return res 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/0561.array-partition-i/README.md: -------------------------------------------------------------------------------- 1 | # [561. Array Partition I](https://leetcode.com/problems/array-partition-i/) 2 | 3 | ## 题目 4 | Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 5 | 6 | Example 1: 7 | ``` 8 | Input: [1,4,3,2] 9 | Output: 4 10 | Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 11 | ``` 12 | Note: 13 | 1. n is a positive integer, which is in the range of [1, 10000]. 14 | 1. All the integers in the array will be in the range of [-10000, 10000]. 15 | 16 | ## 解题思路 17 | 排序后,把序号为偶数的元素相加起来。 18 | 19 | ## 总结 20 | -------------------------------------------------------------------------------- /Algorithms/0561.array-partition-i/array-partition-i.go: -------------------------------------------------------------------------------- 1 | package Problem0561 2 | 3 | func arrayPairSum(nums []int) int { 4 | var buckets [20001]int8 5 | for _, num := range nums { 6 | buckets[num+10000]++ 7 | } 8 | 9 | sum := 0 10 | needAdd := true 11 | for num, count := range buckets { 12 | for count > 0 { 13 | if needAdd { 14 | sum += num - 10000 15 | } 16 | needAdd = !needAdd 17 | count-- 18 | } 19 | } 20 | 21 | return sum 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/0561.array-partition-i/array-partition-i_test.go: -------------------------------------------------------------------------------- 1 | package Problem0561 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | // one 代表第一个参数 17 | type para struct { 18 | one []int 19 | } 20 | 21 | // ans 是答案 22 | // one 代表第一个答案 23 | type ans struct { 24 | one int 25 | } 26 | 27 | func Test_Problem0561(t *testing.T) { 28 | ast := assert.New(t) 29 | 30 | qs := []question{ 31 | 32 | question{ 33 | para{[]int{4, 3, 2, 1}}, 34 | ans{4}, 35 | }, 36 | 37 | question{ 38 | para{[]int{6, 7, 8, 5, 4, 3, 2, 1}}, 39 | ans{16}, 40 | }, 41 | 42 | // 如需多个测试,可以复制上方元素。 43 | } 44 | 45 | for _, q := range qs { 46 | a, p := q.ans, q.para 47 | fmt.Printf("~~%v~~\n", p) 48 | ast.Equal(a.one, arrayPairSum(p.one), "输入:%v", p) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/0565.array-nesting/array-nesting.go: -------------------------------------------------------------------------------- 1 | package Problem0565 2 | 3 | func arrayNesting(a []int) int { 4 | max := 0 5 | 6 | for i := range a { 7 | temp := 1 8 | 9 | for a[i] != i { 10 | a[i], a[a[i]] = a[a[i]], a[i] 11 | temp++ 12 | } 13 | 14 | if max < temp { 15 | max = temp 16 | } 17 | } 18 | 19 | return max 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/0565.array-nesting/array-nesting_test.go: -------------------------------------------------------------------------------- 1 | package Problem0565 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | type para struct { 17 | nums []int 18 | } 19 | 20 | // ans 是答案 21 | type ans struct { 22 | one int 23 | } 24 | 25 | func Test_Problem0565(t *testing.T) { 26 | ast := assert.New(t) 27 | 28 | qs := []question{ 29 | 30 | question{ 31 | para{ 32 | []int{5, 4, 0, 3, 1, 6, 2}, 33 | }, 34 | ans{ 35 | 4, 36 | }, 37 | }, 38 | 39 | // 如需多个测试,可以复制上方元素。 40 | } 41 | 42 | for _, q := range qs { 43 | a, p := q.ans, q.para 44 | fmt.Printf("~~%v~~\n", p) 45 | 46 | ast.Equal(a.one, arrayNesting(p.nums), "输入:%v", p) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/0566.reshape-the-matrix/reshape-the-matrix.go: -------------------------------------------------------------------------------- 1 | package Problem0566 2 | 3 | func matrixReshape(nums [][]int, r int, c int) [][]int { 4 | if len(nums) == 0 || len(nums[0]) == 0 || len(nums)*len(nums[0]) != r*c || len(nums) == r && len(nums[0]) == c { 5 | return nums 6 | } 7 | 8 | res := make([][]int, r) 9 | count, col := 0, len(nums[0]) 10 | for i := range res { 11 | res[i] = make([]int, c) 12 | 13 | for j := range res[i] { 14 | res[i][j] = nums[count/col][count%col] 15 | count++ 16 | } 17 | } 18 | 19 | return res 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/0581.shortest-unsorted-continuous-subarray/README.md: -------------------------------------------------------------------------------- 1 | # [581. Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/) 2 | 3 | ## 题目 4 | Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. 5 | 6 | You need to find the shortest such subarray and output its length. 7 | 8 | Example 1: 9 | ``` 10 | Input: [2, 6, 4, 8, 10, 9, 15] 11 | Output: 5 12 | Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. 13 | ``` 14 | Note: 15 | 1. Then length of the input array is in range [1, 10,000]. 16 | 1. The input array may contain duplicates, so ascending order here means <=. 17 | 18 | ## 解题思路 19 | 详见注释 20 | 21 | ## 总结 22 | 23 | 24 | -------------------------------------------------------------------------------- /Algorithms/0581.shortest-unsorted-continuous-subarray/shortest-unsorted-continuous-subarray.go: -------------------------------------------------------------------------------- 1 | package Problem0581 2 | 3 | func findUnsortedSubarray(nums []int) int { 4 | n := len(nums) 5 | left, right := 0, -1 // left和right的取值,只要满足 right - left + 1 == 0 即可 6 | min, max := nums[n-1], nums[0] 7 | 8 | for i := 1; i < n; i++ { 9 | if max <= nums[i] { // 如果 nums 是递增的话,if 的判断语句应该总是成立 10 | max = nums[i] 11 | } else { // 说明 nums[i] 比它前面的数小,它错位了,需要被重新排序 12 | right = i 13 | } 14 | 15 | // min 与 max 同理 16 | j := n - i - 1 17 | if min >= nums[j] { 18 | min = nums[j] 19 | } else { 20 | left = j 21 | } 22 | } 23 | 24 | return right - left + 1 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/0605.can-place-flowers/can-place-flowers.go: -------------------------------------------------------------------------------- 1 | package Problem0605 2 | 3 | func canPlaceFlowers(bed []int, n int) bool { 4 | l := len(bed) 5 | for i := 0; i < l; i++ { 6 | if bed[i] == 0 && // 检查 i 的值 7 | ((i+1 < l && bed[i+1] == 0) || i+1 >= l) && // 检查 i+1 的值 8 | ((i-1 >= 0 && bed[i-1] == 0) || i-1 < 0) { // 检查 i-1 的值 9 | bed[i] = 1 10 | n-- 11 | if n <= 0 { 12 | return true 13 | } 14 | } 15 | } 16 | 17 | return n <= 0 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/0611.valid-triangle-number/README.md: -------------------------------------------------------------------------------- 1 | # [611. Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) 2 | 3 | ## 题目 4 | Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. 5 | 6 | Example 1: 7 | ``` 8 | Input: [2,2,3,4] 9 | Output: 3 10 | Explanation: 11 | Valid combinations are: 12 | 2,3,4 (using the first 2) 13 | 2,3,4 (using the second 2) 14 | 2,2,3 15 | ``` 16 | 17 | Note: 18 | 1. The length of the given array won't exceed 1000. 19 | 1. The integers in the given array are in the range of [0, 1000]. 20 | 21 | ## 解题思路 22 | 23 | 见程序注释 24 | -------------------------------------------------------------------------------- /Algorithms/0611.valid-triangle-number/valid-triangle-number.go: -------------------------------------------------------------------------------- 1 | package Problem0611 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func triangleNumber(a []int) int { 8 | sort.Ints(a) 9 | n := len(a) 10 | 11 | res := 0 12 | for k := n - 1; 2 <= k; k-- { 13 | for i, j := 0, k-1; i < j; { 14 | // 由于 a 是递增的,保证了 a[i] <= a[j] <= a[k] 15 | // 所以,只要 a[i] + a[j] > a[k] 16 | // 三者就可以构成三角形 17 | if a[i]+a[j] > a[k] { 18 | // a[j], a[k] 和 a[i:j] 中的任意一个,都可以组成三角形 19 | // a[i:j] 中元素个数是 j-i 20 | res += j - i 21 | // a[j] 足够长,可以变短试试看 22 | j-- 23 | } else { 24 | // a[i] 不够长,需要变长后,再看看 25 | i++ 26 | } 27 | } 28 | } 29 | 30 | return res 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/0611.valid-triangle-number/valid-triangle-number_test.go: -------------------------------------------------------------------------------- 1 | package Problem0611 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | type para struct { 17 | nums []int 18 | } 19 | 20 | // ans 是答案 21 | type ans struct { 22 | one int 23 | } 24 | 25 | func Test_Problem0611(t *testing.T) { 26 | ast := assert.New(t) 27 | 28 | qs := []question{ 29 | 30 | question{ 31 | para{ 32 | []int{2, 2, 3, 4}, 33 | }, 34 | ans{ 35 | 3, 36 | }, 37 | }, 38 | 39 | // 如需多个测试,可以复制上方元素。 40 | } 41 | 42 | for _, q := range qs { 43 | a, p := q.ans, q.para 44 | fmt.Printf("~~%v~~\n", p) 45 | 46 | ast.Equal(a.one, triangleNumber(p.nums), "输入:%v", p) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/0628.maximum-product-of-three-numbers/README.md: -------------------------------------------------------------------------------- 1 | # [628. Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) 2 | 3 | ## 题目 4 | Given an integer array, find three numbers whose product is maximum and output the maximum product. 5 | 6 | Example 1: 7 | ``` 8 | Input: [1,2,3] 9 | Output: 6 10 | ``` 11 | Example 2: 12 | ``` 13 | Input: [1,2,3,4] 14 | Output: 24 15 | ``` 16 | Note: 17 | 18 | The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 19 | 20 | Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. 21 | 22 | ## 解题思路 23 | 24 | 25 | ## 总结 26 | 27 | 28 | -------------------------------------------------------------------------------- /Algorithms/0628.maximum-product-of-three-numbers/maximum-product-of-three-numbers.go: -------------------------------------------------------------------------------- 1 | package Problem0628 2 | 3 | func maximumProduct(nums []int) int { 4 | 5 | max := -1001 6 | max1 := -1001 7 | max2 := -1001 8 | min1 := 1001 9 | min2 := 1001 10 | 11 | for _, n := range nums { 12 | switch { 13 | case n > max: 14 | max2, max1, max = max1, max, n 15 | case n > max1: 16 | max2, max1 = max1, n 17 | case n > max2: 18 | max2 = n 19 | } 20 | 21 | switch { 22 | case n < min1: 23 | min2, min1 = min1, n 24 | case n < min2: 25 | min2 = n 26 | } 27 | } 28 | 29 | return bigger(max1*max2, min1*min2) * max 30 | } 31 | 32 | func bigger(a, b int) int { 33 | if a > b { 34 | return a 35 | } 36 | return b 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/0643.maximum-average-subarray-i/README.md: -------------------------------------------------------------------------------- 1 | # [643. Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) 2 | 3 | ## 题目 4 | Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. 5 | 6 | Example 1: 7 | ``` 8 | Input: [1,12,-5,-6,50,3], k = 4 9 | Output: 12.75 10 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 11 | ``` 12 | Note: 13 | 1 <= k <= n <= 30,000. 14 | Elements of the given array will be in the range [-10,000, 10,000]. 15 | 16 | ## 解题思路 17 | 见程序 18 | 19 | ## 总结 20 | 21 | 22 | -------------------------------------------------------------------------------- /Algorithms/0643.maximum-average-subarray-i/maximum-average-subarray-i.go: -------------------------------------------------------------------------------- 1 | package Problem0643 2 | 3 | func findMaxAverage(nums []int, k int) float64 { 4 | temp := 0 5 | // 获取第一个temp 6 | for i := 0; i < k; i++ { 7 | temp += nums[i] 8 | } 9 | 10 | max := temp 11 | 12 | for i := k; i < len(nums); i++ { 13 | // 根据 i 获取 temp 14 | temp = temp - nums[i-k] + nums[i] 15 | 16 | if max < temp { 17 | max = temp 18 | } 19 | } 20 | 21 | return float64(max) / float64(k) 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/0643.maximum-average-subarray-i/maximum-average-subarray-i_test.go: -------------------------------------------------------------------------------- 1 | package Problem0643 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type question struct { 11 | para 12 | ans 13 | } 14 | 15 | // para 是参数 16 | // one 代表第一个参数 17 | type para struct { 18 | nums []int 19 | k int 20 | } 21 | 22 | // ans 是答案 23 | // one 代表第一个答案 24 | type ans struct { 25 | one float64 26 | } 27 | 28 | func Test_Problem0643(t *testing.T) { 29 | ast := assert.New(t) 30 | 31 | qs := []question{ 32 | 33 | question{ 34 | para{[]int{-1}, 1}, 35 | ans{-1}, 36 | }, 37 | 38 | question{ 39 | para{[]int{1, 12, -5, -6, 50, 3}, 4}, 40 | ans{12.75}, 41 | }, 42 | 43 | // 如需多个测试,可以复制上方元素。 44 | } 45 | 46 | for _, q := range qs { 47 | a, p := q.ans, q.para 48 | fmt.Printf("~~%v~~\n", p) 49 | 50 | ast.Equal(a.one, findMaxAverage(p.nums, p.k), "输入:%v", p) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Algorithms/0660.remove-9/README.md: -------------------------------------------------------------------------------- 1 | # [660. Remove 9](https://leetcode.com/problems/remove-9/) 2 | 3 | ## 题目 4 | Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... 5 | 6 | So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ... 7 | 8 | Given a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer. 9 | 10 | Example 1: 11 | ``` 12 | Input: 9 13 | Output: 10 14 | ``` 15 | **Hint:** n will not exceed 9 x 10^8. 16 | 17 | ## 解题思路 18 | 其实就是把10进制转换成9进制。 19 | 20 | ## 总结 21 | -------------------------------------------------------------------------------- /Algorithms/0660.remove-9/remove-9.go: -------------------------------------------------------------------------------- 1 | package Problem0660 2 | 3 | func newInteger(n int) int { 4 | res, base := 0, 1 5 | for n > 0 { 6 | res += n % 9 * base 7 | base *= 10 8 | n /= 9 9 | } 10 | return res 11 | } 12 | -------------------------------------------------------------------------------- /Algorithms/0661.image-smoother/image-smoother.go: -------------------------------------------------------------------------------- 1 | package Problem0661 2 | 3 | func imageSmoother(M [][]int) [][]int { 4 | res := make([][]int, len(M)) 5 | for i := range res { 6 | res[i] = make([]int, len(M[0])) 7 | for j := range res[i] { 8 | res[i][j] = getValue(M, i, j) 9 | } 10 | } 11 | 12 | return res 13 | } 14 | 15 | func getValue(M [][]int, r, c int) int { 16 | value, count := 0, 0 17 | for i := r - 1; i < r+2; i++ { 18 | for j := c - 1; j < c+2; j++ { 19 | if 0 <= i && i < len(M) && 0 <= j && j < len(M[0]) { 20 | value += M[i][j] 21 | count++ 22 | } 23 | } 24 | } 25 | return value / count 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/0667.beautiful-arrangement-ii/beautiful-arrangement-ii.go: -------------------------------------------------------------------------------- 1 | package Problem0667 2 | 3 | func constructArray(n int, k int) []int { 4 | res := make([]int, 0, n) 5 | 6 | i, j := 1, n 7 | 8 | for i <= j { 9 | if k%2 == 1 { 10 | res = append(res, i) 11 | i++ 12 | } else { 13 | res = append(res, j) 14 | j-- 15 | } 16 | if k > 1 { 17 | k-- 18 | } 19 | } 20 | 21 | return res 22 | } 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | run: 2 | @./helper 3 | git commit -am '更新README.md' 4 | git push 5 | git checkout master 6 | git merge develop 7 | git push 8 | git checkout develop -------------------------------------------------------------------------------- /README_HEAD.md: -------------------------------------------------------------------------------- 1 | # [LeetCode](https://leetcode.com)习题的Golang解答 2 | [![LeetCode](https://img.shields.io/badge/LeetCode-%s-blue.svg)](https://leetcode.com/%s/) 3 | [![LeetCode Ranking](https://img.shields.io/badge/Ranking-%d-blue.svg)](https://leetcode.com/%s/) 4 | [![Build Status](https://www.travis-ci.org/aQuaYi/LeetCode-in-Golang.svg?branch=master)](https://www.travis-ci.org/aQuaYi/LeetCode-in-Golang) 5 | [![codecov](https://codecov.io/gh/aQuaYi/LeetCode-in-Golang/branch/master/graph/badge.svg)](https://codecov.io/gh/aQuaYi/LeetCode-in-Golang) 6 | 7 | -------------------------------------------------------------------------------- /README_TAIL.md: -------------------------------------------------------------------------------- 1 | 以下题目,暂时不能使用 Golang 解答 2 | - [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) 3 | - [117. Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/) 4 | 5 | 6 | ## helper 7 | [helper](./helper.v4)会帮助处理大部分琐碎的工作。 8 | 9 | ## notes 10 | [notes](./notes)记录了我答题过程中,对知识点的总结。 11 | 12 | ## kit 13 | 在[kit](./kit)中添加了LeetCode常用的数据结构和处理函数: 14 | 1. 为[*ListNode](./kit/ListNode.go)添加了与[]int相互转换的函数,方便添加单元测试。使用方式可以参考[21. Merge Two Sorted Lists](./Algorithms/0021.merge-two-sorted-lists/merge-two-sorted-lists_test.go) 15 | 1. 为[*TreeNode](./kit/TreeNode.go)添加了与[]int相互转换的函数,方便添加单元测试。 -------------------------------------------------------------------------------- /helper.v4/Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | @go build 3 | @mv helper.v4 ../helper 4 | 5 | test: 6 | @go build 7 | -------------------------------------------------------------------------------- /helper.v4/README.md: -------------------------------------------------------------------------------- 1 | # helper 2 | 3 | ## 功能 4 | 1. 按照程序中设置的模板,生成习题解答文件夹,包括: 5 | 1. README.md 6 | 1. [题目].go 7 | 1. [题目]_test.go 8 | 1. 统计已经解答题目,在`LeetCode-in-Golang/README.md`中生成 9 | 1. 标题下的LeetCode主页和LeetCode排名图标 10 | 1. 统计报表 11 | 1. 已完成题目的目录 12 | 13 | ## 使用方式 14 | 1. 在命令行的本目录下,运行`make`,会自动生成程序。 15 | 1. 在命令行的`LeetCode-in-Golang`目录下,运行`./helper`,会自动重新生成项目的`README.md` 16 | 1. 在命令行的`LeetCode-in-Golang`目录下,运行`./helper [题号]`,会自动生成相应的答题文件夹。 17 | 18 | ## 配置方法 19 | 1. 在`.gitignore`中,添加一行`*.toml`。 20 | 1. 在`LeetCode-in-Golang`目录下,添加文件`leetcode.toml`。 21 | 1. 把以下内容中的`test`分别修改为你的leetcode用户名和密码后,复制到`leetcode.toml`中。 22 | ```toml 23 | Login="test" 24 | Password="test" 25 | ``` 26 | -------------------------------------------------------------------------------- /helper.v4/util.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | ) 7 | 8 | func read(path string) []byte { 9 | file, err := os.Open(path) 10 | if err != nil { 11 | panic(err) 12 | } 13 | defer file.Close() 14 | 15 | data, err := ioutil.ReadAll(file) 16 | return data 17 | } 18 | -------------------------------------------------------------------------------- /notes/DynamicProgramming/README.md: -------------------------------------------------------------------------------- 1 | # 动态规划 2 | 3 | 动态规划(dynamic programming)多应用于子问题重叠的情况,每个子问题只求解一次。动态规划方法通常用来求解最优化问题的一个最优解。 4 | 5 | 设计动态规划方法的4个步骤: 6 | 1. 刻画一个最优解的结构特征 7 | 1. 递归地定义最优解的值 8 | 1. 计算最优解的值,通常采用自底向上的方法 9 | 1. 利用计算出的信息构造一个最优解 10 | 11 | ## 最优子结构(optimal substructure) 12 | 问题的最优解由相关子问题的最优解组合而成,而这些子问题可以独立求解。 13 | 14 | -------------------------------------------------------------------------------- /notes/README.md: -------------------------------------------------------------------------------- 1 | # 笔记 2 | 3 | ## 目录 4 | 1. [动态规划](./DynamicProgramming) 5 | 1. [二叉树](./Tree) -------------------------------------------------------------------------------- /notes/Tree/README.md: -------------------------------------------------------------------------------- 1 | # 二叉树 2 | 3 | ## 树的遍历方式 4 | 5 | 一个节点的左孩子为L,根节点为D,右孩子为R,那么, 6 | 1. 先序遍历(preorder):DLR 7 | 1. 中序遍历(inorder):LDR 8 | 1. 后序遍历(postorder):LRD 9 | 其中,先,中,后指的是根节点D的位置。 10 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | echo "" > coverage.txt 5 | 6 | for d in $(go list ./... | grep -v vendor); do 7 | echo $d 8 | go test -coverprofile=profile.out -covermode=atomic $d 9 | if [ -f profile.out ]; then 10 | cat profile.out >> coverage.txt 11 | rm profile.out 12 | fi 13 | done --------------------------------------------------------------------------------