Repository: keep-practicing/leetcode-go Branch: master Commit: 8fb3d0066cf6 Files: 252 Total size: 229.4 KB Directory structure: gitextract_t27zlmsi/ ├── .codacy.yml ├── .codecov.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── _config.yml ├── bak.README.md ├── docs/ │ ├── _config.yml │ └── index.md ├── go.mod ├── solutions/ │ ├── 0001_two_sum/ │ │ ├── twosum.go │ │ └── twosum_test.go │ ├── 0002_add_two_numbers/ │ │ ├── add_two_numbers.go │ │ └── add_two_numbers_test.go │ ├── 0003_longest_substring_without_repeating_characters/ │ │ ├── longest_substring_without_repeating_characters.go │ │ └── longest_substring_without_repeating_characters_test.go │ ├── 0004_median_of_two_sorted_arrays/ │ │ ├── motsa.go │ │ └── motsa_test.go │ ├── 0007_reverse_integer/ │ │ ├── reverse_integer.go │ │ └── reverse_integer_test.go │ ├── 0009_palindrome_number/ │ │ ├── palindrome_number.go │ │ └── palindrome_number_test.go │ ├── 0011_container_with_most_water/ │ │ ├── container_with_most_water.go │ │ └── container_with_most_water_test.go │ ├── 0013_roman_to_integer/ │ │ ├── roman_to_integer.go │ │ └── roman_to_integer_test.go │ ├── 0014_longest_common_prefix/ │ │ ├── lcp.go │ │ └── lcp_test.go │ ├── 0015_3Sum/ │ │ ├── 3sum.go │ │ └── 3sum_test.go │ ├── 0017_letter_combination_of_a_phone_number/ │ │ ├── letter_combination_of_phone_number.go │ │ └── letter_combination_of_phone_number_test.go │ ├── 0019_remove_nth_node_from_end_of_list/ │ │ ├── remove_nth_node_from_end_of_list.go │ │ └── remove_nth_node_from_end_of_list_test.go │ ├── 0020_valid_parentheses/ │ │ ├── valid_parentheses.go │ │ └── valid_parentheses_test.go │ ├── 0021_merge_two_sorted_lists/ │ │ ├── mergeTwoLists.go │ │ └── mergeTwoLists_test.go │ ├── 0023_merge_k_sorted_lists/ │ │ ├── mksl.go │ │ └── mksl_test.go │ ├── 0024_swap_nodes_in_pairs/ │ │ ├── swap_nodes_in_pairs.go │ │ └── swap_nodes_in_pairs_test.go │ ├── 0025_reverse_nodes_in_k_group/ │ │ ├── reverse_node_k_group.go │ │ └── reverse_node_k_group_test.go │ ├── 0026_remove_duplicates_from_sorted_array/ │ │ ├── rdfsa.go │ │ └── rdfsa_test.go │ ├── 0027_remove_element/ │ │ ├── remove_element.go │ │ └── remove_element_test.go │ ├── 0028_implement_strstr/ │ │ ├── implement_strstr.go │ │ └── implement_strstr_test.go │ ├── 0033_search_in_rotated_sorted_array/ │ │ ├── search_in_rotated_sorted_array.go │ │ └── search_in_rotated_sorted_array_test.go │ ├── 0034_find_first_and_last_position_of_element_in_sorted_array/ │ │ ├── find_first_and_last_position_of_element_in_sorted_array.go │ │ └── find_first_and_last_position_of_element_in_sorted_array_test.go │ ├── 0035_search_insert_position/ │ │ ├── search_insert_position.go │ │ └── search_insert_position_test.go │ ├── 0048_rotate_image/ │ │ ├── rotate_image.go │ │ └── rotate_image_test.go │ ├── 0053_maximum_subarray/ │ │ ├── maximum_subarray.go │ │ └── maximum_subarray_test.go │ ├── 0058_length_of_last_word/ │ │ ├── len_of_last_word.go │ │ └── len_of_last_word_test.go │ ├── 0061_rotate_list/ │ │ ├── rotate_list.go │ │ └── rotate_list_test.go │ ├── 0062_unique_paths/ │ │ ├── unique_paths.go │ │ └── unique_paths_test.go │ ├── 0063_unique_paths_2/ │ │ ├── unique_paths2.go │ │ └── unique_paths2_test.go │ ├── 0064_minimum_path_sum/ │ │ ├── minimum_path_sum.go │ │ └── minimum_path_sum_test.go │ ├── 0066_plus_one/ │ │ ├── plus_one.go │ │ └── plus_one_test.go │ ├── 0067_add_binary/ │ │ ├── add_binary.go │ │ └── add_binary_test.go │ ├── 0069_sqrtx/ │ │ ├── sqrtx.go │ │ └── sqrtx_test.go │ ├── 0070_climbing_stairs/ │ │ ├── climbing_stairs.go │ │ └── climbing_stairs_test.go │ ├── 0075_sort_colors/ │ │ ├── sort_colors.go │ │ └── sort_colors_test.go │ ├── 0076_minimum_window_substring/ │ │ ├── minimum_window_substring.go │ │ └── minimum_window_substring_test.go │ ├── 0077_combinations/ │ │ ├── combinations.go │ │ └── combinations_test.go │ ├── 0079_word_search/ │ │ ├── word_search.go │ │ └── word_search_test.go │ ├── 0080_remove_duplicates_from_sorted_array2/ │ │ ├── rdfsa2.go │ │ └── rdfsa2_test.go │ ├── 0082_remove_duplicates_from_sorted_list_2/ │ │ ├── rdfsl.go │ │ └── rdfsl_test.go │ ├── 0083_remove_duplicates_from_sorted_list/ │ │ ├── rdfsl.go │ │ └── rdfsl_test.go │ ├── 0086_partition_list/ │ │ ├── partition_list.go │ │ └── partition_list_test.go │ ├── 0088_merge_sorted_array/ │ │ ├── msa.go │ │ └── msa_test.go │ ├── 0092_reverse_linked_list_2/ │ │ ├── reverse_linked_list2.go │ │ └── reverse_linked_list2_test.go │ ├── 0094_binary_tree_inorder_traversal/ │ │ ├── binary_tree_inorder_traversal.go │ │ └── binary_tree_inorder_traversal_test.go │ ├── 0100_same_tree/ │ │ ├── same_tree.go │ │ └── same_tree_test.go │ ├── 0101_symmetric_tree/ │ │ ├── symmetric_tree.go │ │ └── symmetric_tree_test.go │ ├── 0102_binary_tree_level_order_traversal/ │ │ ├── binary_tree_level_order_traversal.go │ │ └── binary_tree_level_order_traversal_test.go │ ├── 0104_maximun_depth_of_binary_tree/ │ │ ├── maxdobt.go │ │ └── maxdobt_test.go │ ├── 0107_binary_tree_level_order_traversal_2/ │ │ ├── binary_tree_level_order_traversal2.go │ │ └── binary_tree_level_order_traversal2_test.go │ ├── 0111_minimum_depth_of_binary_tree/ │ │ ├── minimum_depth_of_binary_tree.go │ │ └── minimum_depth_of_binary_tree_test.go │ ├── 0112_path_sum/ │ │ ├── path_sum.go │ │ └── path_sum_test.go │ ├── 0120_triangle/ │ │ ├── triangle.go │ │ └── triangle_test.go │ ├── 0121_best_time_to_buy_and_sell_stock/ │ │ ├── maxprofit.go │ │ └── maxprofit_test.go │ ├── 0122_best_time_to_buy_and_sell_stock_2/ │ │ ├── maxprofit.go │ │ └── maxprofit_test.go │ ├── 0125_valid_palindrome/ │ │ ├── valid_palindrome.go │ │ └── valid_palindrome_test.go │ ├── 0136_single_number/ │ │ ├── single_number.go │ │ └── single_number_test.go │ ├── 0144_binary_tree_preorder_traversal/ │ │ ├── binary_tree_preorder_traversal.go │ │ └── binary_tree_preorder_traversal_test.go │ ├── 0150_evaluate_reverse_polish_notation/ │ │ ├── evaluate_reverse_polish_notation.go │ │ └── evaluate_reverse_polish_notation_test.go │ ├── 0153_find_minimum_in_rotated_sorted_array/ │ │ ├── fmirsa.go │ │ └── fmirsa_test.go │ ├── 0155_min_stack/ │ │ ├── min_stack.go │ │ └── min_stack_test.go │ ├── 0165_compare_version_numbers/ │ │ ├── compare_version_numbers.go │ │ └── compare_version_numbers_test.go │ ├── 0167_two_sum2/ │ │ ├── two_sum2.go │ │ └── two_sum2_test.go │ ├── 0179_largest_number/ │ │ ├── ln.go │ │ └── ln_test.go │ ├── 0198_house_robber/ │ │ ├── house_robber.go │ │ └── house_robber_test.go │ ├── 0200_number_of_island/ │ │ ├── number_of_island.go │ │ └── number_of_island_test.go │ ├── 0203_remove_linked_list_elements/ │ │ ├── remove_linked_list_elements.go │ │ └── remove_linked_list_elements_test.go │ ├── 0206_reverse_linked_list/ │ │ ├── reverse_linked_list.go │ │ └── reverse_linked_list_test.go │ ├── 0208_implement_trie_prefix_tree/ │ │ ├── impltrie.go │ │ └── impltrie_test.go │ ├── 0209_minimum_size_subarray_sum/ │ │ ├── minimum_size_subarray_sum.go │ │ └── minimum_size_subarray_sum_test.go │ ├── 0211_add_and_search_word/ │ │ ├── add_and_search_word.go │ │ └── add_and_search_word_test.go │ ├── 0215_kth_largest_element_in_an_array/ │ │ ├── kthleiaa.go │ │ └── kthleiaa_test.go │ ├── 0217_contains_duplicate/ │ │ ├── contains_duplicate.go │ │ └── contains_duplicate_test.go │ ├── 0219_contains_duplicate_2/ │ │ ├── contains_duplicate_2.go │ │ └── contains_duplicate_2_test.go │ ├── 0226_invert_binary_tree/ │ │ ├── invert_binary_tree.go │ │ └── invert_binary_tree_test.go │ ├── 0235_lowest_common_ancestor_of_a_binary_search_tree/ │ │ ├── lcaoabst.go │ │ └── lcaoabst_test.go │ ├── 0236_Lowest_Common_Ancestor_of_a_Binary_Tree/ │ │ ├── lca.go │ │ └── lca_test.go │ ├── 0237_delete_node_in_a_linked_list/ │ │ ├── dniall.go │ │ └── dniall_test.go │ ├── 0257_binary_tree_paths/ │ │ ├── binary_tree_paths.go │ │ └── binary_tree_paths_test.go │ ├── 0258_add_digits/ │ │ ├── add_digits.go │ │ └── add_digits_test.go │ ├── 0283_move_zeroes/ │ │ ├── move_zeroes.go │ │ ├── move_zeroes2.go │ │ ├── move_zeroes2_test.go │ │ └── move_zeroes_test.go │ ├── 0300_longest_increasing_subsequence/ │ │ ├── lis.go │ │ └── lis_test.go │ ├── 0303_range_sum_query/ │ │ ├── rsqim.go │ │ └── rsqim_test.go │ ├── 0307_Range_Sum_Query_Mutable/ │ │ ├── range_sum_query_mut.go │ │ └── range_sum_query_mut_test.go │ ├── 0328_odd_even_linked_list/ │ │ ├── odd_even_linked_list.go │ │ └── odd_even_linked_list_test.go │ ├── 0343_integer_break/ │ │ ├── integer_break.go │ │ └── integer_break_test.go │ ├── 0344_reverse_string/ │ │ ├── reverse_string.go │ │ └── reverse_string_test.go │ ├── 0345_reverse_vowels_of_a_string/ │ │ ├── reverse_vowels.go │ │ └── reverse_vowels_test.go │ ├── 0347_top_k_frequent_elements/ │ │ ├── topkfe.go │ │ └── topkfe_test.go │ ├── 0349_intersection_of_2_arrays/ │ │ ├── intersection_of_two_arrays.go │ │ └── intersection_of_two_arrays_test.go │ ├── 0350_intersection_of_two_arrays2/ │ │ ├── intersection_of_two_arrays2.go │ │ └── intersection_of_two_arrays2_test.go │ ├── 0376_wiggle_subsequence/ │ │ ├── wiggle_subsequence.go │ │ └── wiggle_subsequence_test.go │ ├── 0392_is_subsequence/ │ │ ├── is_subsequence.go │ │ └── is_subsequence_test.go │ ├── 0404_sum_of_left_leaves/ │ │ ├── sum_of_left_leaves.go │ │ └── sum_of_left_leaves_test.go │ ├── 0416_partition_equal_subset_sum/ │ │ ├── partition_equal_subset_sum.go │ │ └── partition_equal_subset_sum_test.go │ ├── 0435_non_overlapping_intervals/ │ │ ├── dp_solution.go │ │ ├── greedy_solution.go │ │ ├── interval.go │ │ └── solution_test.go │ ├── 0437_path_sum_3/ │ │ ├── path_sum_3.go │ │ └── path_sum_3_test.go │ ├── 0438_all_anagrams_in_a_string/ │ │ ├── all_anagrams_in_a_string.go │ │ └── all_anagrams_in_a_string_test.go │ ├── 0447_number_of_boomerangs/ │ │ ├── number_of_boomerangs.go │ │ └── number_of_boomerangs_test.go │ ├── 0454_4sum2/ │ │ ├── 4sum2.go │ │ └── 4sum2_test.go │ ├── 0455_assign_cookies/ │ │ ├── assign_cookies.go │ │ └── assign_cookies_test.go │ ├── 0557_reverse_words_in_a_string_3/ │ │ ├── reverse_words_in_a_string_3.go │ │ └── reverse_words_in_a_string_3_test.go │ ├── 0674_longest_continuous_increasing_subsequence/ │ │ ├── lcis.go │ │ └── lcis_test.go │ ├── 0677_map_sum_pairs/ │ │ ├── map_sum_pairs.go │ │ └── map_sum_pairs_test.go │ ├── 0704_binary_search/ │ │ ├── binary_search.go │ │ └── binary_search_test.go │ ├── 0713_subarray_product_less_than_k/ │ │ ├── spltk.go │ │ └── spltk_test.go │ ├── 0717_1_bit_and_2_bit_characters/ │ │ ├── 1bitand2bitc.go │ │ └── 1bitand2bitc_test.go │ ├── 0728_self_dividing_numbers/ │ │ ├── self_dividing_numbers.go │ │ └── self_dividing_numbers_test.go │ ├── 0735_asteroid_collision/ │ │ ├── ac.go │ │ └── ac_test.go │ ├── 0747_largest_number_at_least_twice_of_others/ │ │ ├── largest_number_at_least_twice_of_others.go │ │ └── largest_number_at_least_twice_of_others_test.go │ ├── 0872_leaf_similar_trees/ │ │ ├── leaf_similar_trees.go │ │ └── leaf_similar_trees_test.go │ ├── 1021_Remove_Outermost_Parentheses/ │ │ ├── remove_outmost_parentheses.go │ │ └── remove_outmost_parentheses_test.go │ ├── 148_Sort_List/ │ │ ├── sortlist.go │ │ └── sortlist_test.go │ ├── 304_Range_Sum_Query_2D/ │ │ ├── rsq.go │ │ └── rsq_test.go │ └── README.md ├── ut.bash └── utils/ ├── infinite.go ├── maxint.go ├── maxint_test.go ├── minint.go ├── minint_test.go ├── set.go └── set_test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .codacy.yml ================================================ --- exclude_paths: - '**/*.md' - 'README.md' ================================================ FILE: .codecov.yml ================================================ codecov: notify: require_ci_to_pass: yes coverage: round: up range: 0..10 precision: 2 status: project: yes patch: yes changes: yes comment: layout: "reach, diff, flags, files" behavior: default require_changes: false # if true: only post the comment if coverage changes require_base: yes # [yes :: must have a base report to post] require_head: yes # [yes :: must have a head report to post] branches: null ================================================ FILE: .gitignore ================================================ # Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, build with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # JetBrains .idea/ # vs code .vscode/ # mac .DS_Store ================================================ FILE: .travis.yml ================================================ language: go go: - "1.12.x" go_import_path: leetcode install: - go get -t -v ./... script: - go test ./... -race -coverprofile=coverage.txt -covermode=atomic after_success: - bash <(curl -s https://codecov.io/bash) branches: only: - master ================================================ FILE: LICENSE ================================================ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to ================================================ FILE: Makefile ================================================ # Basic go commands GOCMD=go GOBUILD=$(GOCMD) build GOCLEAN=$(GOCMD) clean GOTEST=$(GOCMD) test GOGET=$(GOCMD) get GOFMT=$(GOCMD) fmt test: @echo "unit test" $(GOTEST) ./... clean: @echo "clean test cache" $(GOCLEAN) -testcache fmt: @echo "fmt code" $(GOFMT) ./... ================================================ FILE: _config.yml ================================================ theme: jekyll-theme-architect ================================================ FILE: bak.README.md ================================================ # Go Solution for Leetcode algorithm problems [![Build Status](https://travis-ci.org/zwfang/leetcode.svg?branch=master)](https://travis-ci.org/zwfang/leetcode) [![codecov](https://codecov.io/gh/zwfang/leetcode/branch/master/graph/badge.svg)](https://codecov.io/gh/zwfang/leetcode) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/86cf2613fa544ab5b254e2a7e5d9deb8)](https://www.codacy.com/app/zwfang/leetcode?utm_source=github.com&utm_medium=referral&utm_content=zwfang/leetcode&utm_campaign=Badge_Grade) [![Go Report Card](https://goreportcard.com/badge/github.com/zwfang/leetcode)](https://goreportcard.com/report/github.com/zwfang/leetcode) continually updating 😃. ### [view by sorted](./solutions/README.md) ### Array * [1. Two Sum](solutions/0001_two_sum/twosum.go)   *`lookup table;`*  *`hash table`* * [4. Median of Two Sorted Arrays](solutions/0004_median_of_two_sorted_arrays/motsa.go)   *`binary search;`*  *`divide and conquer`* * [11. Container With Most Water](solutions/0011_container_with_most_water/container_with_most_water.go)   *`double index;`*  *`array`* * [15. 3Sum](solutions/0015_3Sum/3sum.go)   *`double index;`*  *`array`* * [26. Remove Duplicates from Sorted Array](solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go)   *`double index;`*  *`array`* * [27. Remove Element](solutions/0027_remove_element/remove_element.go)   *`double index;`*  *`array`* * [48. Rotate Image](solutions/0048_rotate_image/rotate_image.go) * [53. Maximum Subarray](solutions/0053_maximum_subarray/maximum_subarray.go)   *`dynamic programming`* * [75. Sort Colors](solutions/0075_sort_colors/sort_colors.go)   *`sort;`*  *`array`* * [80. Remove Duplicates from Sorted Array II](solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go)   *`double index;`*  *`array`* * [88. Merge Sorted Array](solutions/0088_merge_sorted_array/msa.go)   *`sort;`*  *`array`* * [121. Best Time to Buy and Sell Stock](solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go)   *`dynamic programming;`*  *`array`* * [122. Best Time to Buy and Sell Stock II](solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go)   *`greedy;`*  *`array`* * [136. Single Number](solutions/0136_single_number/single_number.go)   *`hash table;`*  *`bit manipulation`* * [167. Two Sum II - Input array is sorted](solutions/0167_two_sum2/two_sum2.go)   *`double index;`*  *`binary search`* * [179. Largest Number](solutions/0179_largest_number/ln.go)   *`sort`* * [200. Number of Islands](solutions/0200_number_of_island/number_of_island.go)   *`dfs;`*  *`bfs`* * [209. Minimum Size Subarray Sum](solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go)   *`sliding window`* * [215. Kth Largest Element in an Array](solutions/0215_kth_largest_element_in_an_array/kthleiaa.go)   *`sort`* * [217. Contains Duplicate](solutions/0217_contains_duplicate/contains_duplicate.go)   *`map`* * [219. Contains Duplicate II](solutions/0219_contains_duplicate_2/contains_duplicate_2.go)   *`map`* * [283. Move Zeroes(solution1)](solutions/0283_move_zeroes/move_zeroes.go)   *`sliding window`* * [283. Move Zeroes(solution2)](solutions/0283_move_zeroes/move_zeroes2.go)   *`sliding window`* * [303. Range Sum Query - Immutable](solutions/0303_range_sum_query/rsqim.go) * [347. Top K Frequent Elements](solutions/0347_top_k_frequent_elements/topkfe.go)   *`hash table;`*  *`heap`* * [349. Intersection of Two Arrays](solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays.go)   *`set`* * [350. Intersection of Two Arrays II](solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go)   *`hash table`* * [447. Number of Boomerangs](solutions/0447_number_of_boomerangs/number_of_boomerangs.go)   *`hash table`* * [454. 4Sum II](solutions/0454_4sum2/4sum2.go)   *`hash table`* * [674. Longest Continuous Increasing Subsequence](solutions/0674_longest_continuous_increasing_subsequence/lcis.go) * [713. Subarray Product Less Than K](solutions/0713_subarray_product_less_than_k/spltk.go)   *`sliding window`*  *`array`* * [717. 1-bit and 2-bit Characters](solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc.go) * [747. Largest Number At Least Twice of Others](solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others.go) ### Stack * [155. Min Stack](solutions/0155_min_stack/min_stack.go) * [735. Asteroid Collision](solutions/0735_asteroid_collision/ac.go) ### String * [3. Longest Substring Without Repeating Characters](solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go)   *`sliding window;`*  *`hash table`* * [14. Longest Common Prefix](solutions/0014_longest_common_prefix/lcp.go) * [17. Letter Combinations of a Phone Number](solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go)   *`tree`* * [20. Valid Parentheses](solutions/0020_valid_parentheses/valid_parentheses.go)   *`stack`* * [28. Implement strStr()](solutions/0028_implement_strstr/implement_strstr.go)   *`double index`* * [58. Length of Last Word](solutions/0058_length_of_last_word/len_of_last_word.go) * [67. Add Binary](solutions/0067_add_binary/add_binary.go)   *`brute force`* * [76. Minimum Window Substring](solutions/0076_minimum_window_substring/minimum_window_substring.go)    *`sliding window`* * [125. Valid Palindrome](solutions/0125_valid_palindrome/valid_palindrome.go)   *`string;`*  *`double index`* * [165. Compare Version Numbers](solutions/0165_compare_version_numbers/compare_version_numbers.go) * [344. Reverse String](solutions/0344_reverse_string/reverse_string.go)   *`string;`*  *`double index`* * [345. Reverse Vowels of a String](solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go)   *`string;`*  *`double index`* * [438. Find All Anagrams in a String](solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string.go)   *`sliding window`* * [557. Reverse Words in a String III](solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3.go) * [1021. Remove Outermost Parentheses](solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses.go)   *`stack`* ### Linked List * [2. Add Two Numbers](solutions/0002_add_two_numbers/add_two_numbers.go)   *`recursion;`*  *`math`* * [19. Remove Nth Node From End of List](solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go)   *`two pointers`* * [21. Merge Two Sorted Lists](solutions/0021_merge_two_sorted_lists/mergeTwoLists.go) * [23. Merge k Sorted Lists](solutions/0023_merge_k_sorted_lists/mksl.go)   *`heap`* * [24. Swap Nodes in Pairs](solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go) * [25. Reverse Nodes in k-Group](solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go) * [61. Rotate List](solutions/0061_rotate_list/rotate_list.go) * [82. Remove Duplicates from Sorted List II](solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go) * [83. Remove Duplicates from Sorted List](solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go) * [86. Partition List](solutions/0086_partition_list/partition_list.go)   *`two pointers`* * [92. Reverse Linked List II](solutions/0092_reverse_linked_list_2/reverse_linked_list2.go) * [148. Sort List](solutions/148_Sort_List/sortlist.go)   *`sort`* * [203. Remove Linked List Elements](solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go) * [206. Reverse Linked List](solutions/0206_reverse_linked_list/reverse_linked_list.go) * [237. Delete Node in a Linked List](solutions/0237_delete_node_in_a_linked_list/dniall.go) * [328. Odd Even Linked List](solutions/0328_odd_even_linked_list/odd_even_linked_list.go) ### Dynamic Programming * [62. Unique Paths](solutions/0062_unique_paths/unique_paths.go)   *`array`* * [63. Unique Paths 2](solutions/0063_unique_paths_2/unique_paths2.go)   *`array`* * [64. Minimum Path Sum](solutions/0064_minimum_path_sum/minimum_path_sum.go)   *`array`* * [70. Climbing Stairs](solutions/0070_climbing_stairs/climbing_stairs.go) * [120. Triangle](solutions/0120_triangle/triangle.go)   *`array`* * [198. House Robber](solutions/0198_house_robber/house_robber.go) * [300. Longest Increasing Subsequence](solutions/0300_longest_increasing_subsequence/lis.go) * [304. Range Sum Query 2D - Immutable](solutions/304_Range_Sum_Query_2D/rsq.go) * [343. Integer Break](solutions/0343_integer_break/integer_break.go)   *`math`* * [376. Wiggle Subsequence](solutions/0376_wiggle_subsequence/wiggle_subsequence.go)   *`greedy;`*  *`dynamic programming`* * [416. Partition Equal Subset Sum](solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum.go)  *`0-1 knapsack problem`* * [435. Non-overlapping Intervals](solutions/0435_non_overlapping_intervals/dp_solution.go)   *`greedy;`*  *`dynamic programming`*  *`0-1 knapsack problem`* ### Greedy * [392. Is Subsequence](solutions/0392_is_subsequence/is_subsequence.go) * [435. Non-overlapping Intervals](solutions/0435_non_overlapping_intervals/greedy_solution.go)   *`greedy;`*  *`dynamic programming`* * [455. Assign Cookies](solutions/0455_assign_cookies/assign_cookies.go) ### Backtracking * [77. Combinations](solutions/0077_combinations/combinations.go)   *`combine`* * [79. Word Search](solutions/0079_word_search/word_search.go)   *`array`* ### Tree * [94. Binary Tree Inorder Traversal](solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go)   *`binary tree;`*   *`stack`* * [100. Same Tree](solutions/0100_same_tree/same_tree.go)   *`binary tree;`*   *`dfs`* * [101. Symmetric Tree](solutions/0101_symmetric_tree/symmetric_tree.go)   *`binary tree;`*   *`dfs;`*  *`bfs;`* * [102. Binary Tree Level Order Traversal](solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go)   *`binary tree;`*   *`dfs`* * [104. Maximum Depth of Binary Tree](solutions/0104_maximun_depth_of_binary_tree/maxdobt.go)   *`binary tree depth`* * [107. Binary Tree Level Order Traversal II](solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go)   *`binary tree;`*   *`bfs`* * [111. Minimum Depth of Binary Tree](solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go)   *`binary tree;`*   *`dfs`* * [112. Path Sum](solutions/0112_path_sum/path_sum.go)   *`binary tree;`*   *`dfs`* * [144. Binary Tree Preorder Traversal](solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go)   *`binary tree;`*   *`pre-order traversal`* * [208. Implement Trie (Prefix Tree)](solutions/0208_implement_trie_prefix_tree/impltrie.go)   *`trie`* * [226. Invert Binary Tree](solutions/0226_invert_binary_tree/invert_binary_tree.go)   *`binary tree`* * [211. Add and Search Word - Data structure design](solutions/0211_add_and_search_word/add_and_search_word.go)   *`trie`* * [235. Lowest Common Ancestor of a Binary Search Tree](solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go)   *`binary tree`* * [236. Lowest Common Ancestor of a Binary Tree](solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go)   *`binary tree`* * [257. Binary Tree Paths](solutions/0257_binary_tree_paths/binary_tree_paths.go)   *`binary tree`* * [307. Range Sum Query - Mutable](solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut.go)   *`segment tree`* * [404. Sum of Left Leaves](solutions/0404_sum_of_left_leaves/sum_of_left_leaves.go)   *`binary tree`* * [437. Path Sum III](solutions/0437_path_sum_3/path_sum_3.go)   *`binary tree`* * [677. Map Sum Pairs](solutions/0677_map_sum_pairs/map_sum_pairs.go)   *`trie`* * [872. Leaf-Similar Trees](solutions/0872_leaf_similar_trees/leaf_similar_trees.go)   *`binary tree`* ### Binary Search * [33. Search in Rotated Sorted Array](solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go)   *`array;`*  *`binary search`* * [34. Find First and Last Position of Element in Sorted Array](solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go)   *`array;`*  *`binary search`* * [35. Search Insert Position](solutions/0035_search_insert_position/search_insert_position.go)   *`array;`*  *`binary search`* * [69. Sqrt(x)](solutions/0069_sqrtx/sqrtx.go)   *`math;`*  *`binary search`* * [153. Find Minimum in Rotated Sorted Array](solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go) * [704. Binary Search](solutions/0704_binary_search/binary_search.go) ### Math * [7. Reverse Integer](solutions/0007_reverse_integer/reverse_integer.go) * [9. Palindrome Number](solutions/0009_palindrome_number/palindrome_number.go) * [13. Roman to Integer](solutions/0013_roman_to_integer/roman_to_integer.go)   *`string`* * [66. Plus One](solutions/0066_plus_one/plus_one.go)   *`array`* * [150. Evaluate Reverse Polish Notation](solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go)   *`stack`* * [258. Add Digits](solutions/0258_add_digits/add_digits.go) ================================================ FILE: docs/_config.yml ================================================ theme: jekyll-theme-hacker ================================================ FILE: docs/index.md ================================================ ## Welcome to GitHub Pages You can use the [editor on GitHub](https://github.com/keep-in-practice/leetcode-go/edit/master/docs/index.md) to maintain and preview the content for your website in Markdown files. Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files. ### Markdown Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for ```markdown Syntax highlighted code block # Header 1 ## Header 2 ### Header 3 - Bulleted - List 1. Numbered 2. List **Bold** and _Italic_ and `Code` text [Link](url) and ![Image](src) ``` For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/). ### Jekyll Themes Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/keep-in-practice/leetcode-go/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file. ### Support or Contact Having trouble with Pages? Check out our [documentation](https://docs.github.com/categories/github-pages-basics/) or [contact support](https://github.com/contact) and we’ll help you sort it out. ================================================ FILE: go.mod ================================================ module leetcode go 1.13 ================================================ FILE: solutions/0001_two_sum/twosum.go ================================================ /* 1. Two Sum Source: https://leetcode.com/problems/two-sum/ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. */ package twosum // Time complexity: O(n) // Space complexity: O(n) func twoSum(nums []int, target int) []int { record := make(map[int]int) for i, j := range nums { complement := target - j if res, ok := record[complement]; ok { return []int{res, i} } record[j] = i } return []int{} } // brute force // Time complexity: O(n^2) // Space complexity: O(1) func twoSum1(nums []int, target int) []int { for i, j := range nums { for k := i + 1; k < len(nums); k++ { if nums[k]+j == target { return []int{i, k} } } } return []int{} } ================================================ FILE: solutions/0001_two_sum/twosum_test.go ================================================ package twosum import ( "reflect" "testing" ) func TestTwoSum(t *testing.T) { nums := []int{2, 7, 11, 15} funcs := []func([]int, int) []int{twoSum, twoSum1} for _, testFunc := range funcs { if res := testFunc(nums, 9); !reflect.DeepEqual(res, []int{0, 1}) { t.Error("Failed, two sum") } if res := testFunc(nums, 6); !reflect.DeepEqual(res, []int{}) { t.Error("Failed, two sum") } } } ================================================ FILE: solutions/0002_add_two_numbers/add_two_numbers.go ================================================ /* 2. Add Two Numbers Source: https://leetcode.com/problems/add-two-numbers/ You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ package addtwonumbers // ListNode is node of linked list type ListNode struct { Val int Next *ListNode } // 解法一,暴力解法 func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode { head := ListNode{Val: -1} cur := &head carry := 0 for l1 != nil && l2 != nil { sum := l1.Val + l2.Val + carry val := sum % 10 carry = sum / 10 node := ListNode{Val: val} cur.Next = &node cur = cur.Next l1 = l1.Next l2 = l2.Next } if carry == 0 { if l1 != nil { cur.Next = l1 } if l2 != nil { cur.Next = l2 } return head.Next } for l1 != nil { sum := l1.Val + carry val := sum % 10 carry = sum / 10 node := ListNode{Val: val} cur.Next = &node cur = cur.Next l1 = l1.Next } for l2 != nil { sum := l2.Val + carry val := sum % 10 carry = sum / 10 node := ListNode{Val: val} cur.Next = &node cur = cur.Next l2 = l2.Next } for carry != 0 { val := carry % 10 carry = carry / 10 node := ListNode{Val: val} cur.Next = &node cur = cur.Next } return head.Next } // 解法二,递归 func addTwoNumbers2(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil && l2 == nil { return nil } else if l1 == nil && l2 != nil { return l2 } else if l1 != nil && l2 == nil { return l1 } sum := l1.Val + l2.Val next := addTwoNumbers2(l1.Next, l2.Next) if sum >= 10 { carry := sum / 10 sum %= 10 next = addTwoNumbers2(next, &ListNode{Val: carry}) } return &ListNode{Val: sum, Next: next} } ================================================ FILE: solutions/0002_add_two_numbers/add_two_numbers_test.go ================================================ package addtwonumbers import ( "os" "reflect" "testing" ) func createSingleLinkedList(arr []int) *ListNode { head := &ListNode{} cur := head for _, j := range arr { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } func TestAddTwoNumbers1(t *testing.T) { testDatas := []struct { name string arg1 *ListNode arg2 *ListNode expected *ListNode }{ { name: "one", arg1: createSingleLinkedList([]int{2, 4, 3}), arg2: createSingleLinkedList([]int{5, 6, 4}), expected: createSingleLinkedList([]int{7, 0, 8}), }, { name: "two", arg1: createSingleLinkedList([]int{5}), arg2: createSingleLinkedList([]int{5}), expected: createSingleLinkedList([]int{0, 1}), }, { name: "three", arg1: createSingleLinkedList([]int{1}), arg2: createSingleLinkedList([]int{9, 9, 9}), expected: createSingleLinkedList([]int{0, 0, 0, 1}), }, { name: "four", arg1: createSingleLinkedList([]int{9, 9, 9}), arg2: createSingleLinkedList([]int{1}), expected: createSingleLinkedList([]int{0, 0, 0, 1}), }, { name: "five", arg1: createSingleLinkedList([]int{4, 3, 1}), arg2: createSingleLinkedList([]int{1}), expected: createSingleLinkedList([]int{5, 3, 1}), }, { name: "six", arg1: createSingleLinkedList([]int{1}), arg2: createSingleLinkedList([]int{4, 3, 1}), expected: createSingleLinkedList([]int{5, 3, 1}), }, } for _, testData := range testDatas { t.Run(testData.name, func(t *testing.T) { if result := addTwoNumbers1(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) { t.Errorf("expected %v, got %v", testData.expected, result) } }) } } func TestAddTwoNumbers2(t *testing.T) { testDatas := []struct { name string arg1 *ListNode arg2 *ListNode expected *ListNode }{ { name: "one", arg1: createSingleLinkedList([]int{2, 4, 3}), arg2: createSingleLinkedList([]int{5, 6, 4}), expected: createSingleLinkedList([]int{7, 0, 8}), }, { name: "two", arg1: createSingleLinkedList([]int{5}), arg2: createSingleLinkedList([]int{5}), expected: createSingleLinkedList([]int{0, 1}), }, { name: "three", arg1: createSingleLinkedList([]int{1}), arg2: createSingleLinkedList([]int{9, 9, 9}), expected: createSingleLinkedList([]int{0, 0, 0, 1}), }, { name: "four", arg1: createSingleLinkedList([]int{9, 9, 9}), arg2: createSingleLinkedList([]int{1}), expected: createSingleLinkedList([]int{0, 0, 0, 1}), }, { name: "five", arg1: createSingleLinkedList([]int{4, 3, 1}), arg2: createSingleLinkedList([]int{1}), expected: createSingleLinkedList([]int{5, 3, 1}), }, { name: "six", arg1: createSingleLinkedList([]int{1}), arg2: createSingleLinkedList([]int{4, 3, 1}), expected: createSingleLinkedList([]int{5, 3, 1}), }, } for _, testData := range testDatas { t.Run(testData.name, func(t *testing.T) { if result := addTwoNumbers2(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) { t.Errorf("expected %v, got %v", testData.expected, result) } }) } } func TestMain(m *testing.M) { os.Exit(m.Run()) } ================================================ FILE: solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go ================================================ /* 3. Longest Substring Without Repeating Characters Source: https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ package longestsubstringwithoutrepeatingcharacters // Time complexity: O(n) // Space complexity: O(n) func lengthOfLongestSubstring(s string) int { var ( start = 0 res = 0 lastOccurredRecord = make(map[rune]int) ) for i, ch := range []rune(s) { if lastIndex, ok := lastOccurredRecord[ch]; ok && lastIndex >= start { start = lastIndex + 1 } if i-start+1 > res { res = i - start + 1 } lastOccurredRecord[ch] = i } return res } ================================================ FILE: solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters_test.go ================================================ package longestsubstringwithoutrepeatingcharacters import "testing" func TestLengthOfLongestSubstring(t *testing.T) { testData := []string{ "abcabcbb", "bbbbb", "pwwkew", } expectedData := []int{3, 1, 3} for index, data := range testData { if res := lengthOfLongestSubstring(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0004_median_of_two_sorted_arrays/motsa.go ================================================ /* 4. Median of Two Sorted Arrays https://leetcode.com/problems/median-of-two-sorted-arrays/ There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. */ // time: 2018-12-29 package motsa import "leetcode/utils" // binary search // time complexity: O(log(m+n)), where m is nums1's length, n is nums2's length. // space complexity: O(log(m+n)) func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { var ( m = len(nums1) n = len(nums2) ) if 0 == m && 0 == n { panic("nums1 and nums2 cannot be both empty.") } if 0 == m { return float64(nums2[n>>1]+nums2[n>>1-(n+1)%2]) / 2 } if 0 == n { return float64(nums1[m>>1]+nums1[m>>1-(m+1)%2]) / 2 } var ( left = (m + n + 1) >> 1 right = (m + n + 2) >> 1 ) return float64(findKth(nums1, 0, nums2, 0, left)+findKth(nums1, 0, nums2, 0, right)) / 2 } /* 使用二分法, 在两个有序数组中找到第k个元素。 使用两个变量i和j分别来标记数组nums1和nums2的起始位置。 1. 当某一个数组的起始位置大于等于其数组长度时,说明其所有数字均已经被淘汰了, 相当于一个空数组了,那么实际上就变成了在另一个数组中找数字,直接就可以找出来了 2. 如果K=1的话,那么我们只要比较nums1和nums2的起始位置i和j上的数字就可以了。 3. 对K二分,分别在nums1和nums2中查找第K/2个元素,注意这里由于两个数组的长度不定,所以有可能某个数组没有第K/2个数字, 需要先检查一下,数组中到底存不存在第k/2个数字,如果存在就取出来,反之赋值为整型最大值, 比较两个数组的第k/2个数字,如果第一个数组的第k/2个数字小的话,说明我们要找的数字肯定不再第一个数组的前k/2个数字中, 所以舍弃掉,将第一个数组的起始位置移动k/2,并且此时k也减去k/2(舍弃了k/2个之后,只需要在剩下的里面寻找k-k/2就可以了) */ func findKth(nums1 []int, i int, nums2 []int, j int, k int) int { if i >= len(nums1) { return nums2[j+k-1] } if j >= len(nums2) { return nums1[i+k-1] } if 1 == k { if nums1[i] < nums2[j] { return nums1[i] } return nums2[j] } var ( midVal1, midVal2 int ) if i+k/2-1 < len(nums1) { midVal1 = nums1[i+k/2-1] } else { midVal1 = utils.MaxInt } if j+k/2-1 < len(nums2) { midVal2 = nums2[j+k/2-1] } else { midVal2 = utils.MaxInt } if midVal1 < midVal2 { return findKth(nums1, i+k/2, nums2, j, k-k/2) } return findKth(nums1, i, nums2, j+k/2, k-k/2) } ================================================ FILE: solutions/0004_median_of_two_sorted_arrays/motsa_test.go ================================================ package motsa import ( "testing" ) func TestFindMedianSortedArrays(t *testing.T) { type arg struct { nums1 []int nums2 []int } testCases := []arg{ {nums1: []int{1, 3}, nums2: []int{2}}, {nums1: []int{1, 2}, nums2: []int{3, 4}}, {nums1: []int{}, nums2: []int{3, 4, 5}}, {nums1: []int{4, 5, 6}, nums2: []int{}}, {nums1: []int{2, 3, 4, 5}, nums2: []int{1}}, {nums1: []int{1}, nums2: []int{2, 3, 4, 5, 6, 7}}, {nums1: []int{1, 2, 3, 4, 5, 6, 8, 9, 23, 34}, nums2: []int{7}}, } expected := []float64{2, 2.5, 4, 5, 3, 4, 6} for index, data := range testCases { if res := findMedianSortedArrays(data.nums1, data.nums2); res != expected[index] { t.Errorf("expected %f, got %f", expected[index], res) } } defer func() { if err := recover(); err == nil || err != "nums1 and nums2 cannot be both empty." { t.Errorf("expected err: nums1 and nums2 cannot be both empty.") } }() findMedianSortedArrays([]int{}, []int{}) } ================================================ FILE: solutions/0007_reverse_integer/reverse_integer.go ================================================ /* 7. Reverse Integer https://leetcode.com/problems/reverse-integer/ Given a 32-bit signed integer, reverse digits of an integer. */ // time: 2018-12-29 package reverseinteger // time complexity: O(log 10 x ) = O(log x) // space complexity: O(1) func reverse(x int) int { if 0 == x { return x } isPositive := true if x < 0 { isPositive = false x *= -1 } res := 0 for x > 0 { res = res*10 + x%10 x /= 10 } if !isPositive { res *= -1 } if res < -1<<31 || res > (1<<31)-1 { return 0 } return res } ================================================ FILE: solutions/0007_reverse_integer/reverse_integer_test.go ================================================ package reverseinteger import "testing" func TestReverse(t *testing.T) { testCases := []int{ 123, -123, 10, 0, 12239999999999, } expected := []int{321, -321, 1, 0, 0} for index, data := range testCases { if res := reverse(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0009_palindrome_number/palindrome_number.go ================================================ /* 9. Palindrome Number https://leetcode.com/problems/palindrome-number/ Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. */ // time: 2018-12-30 package palindromenumber // Time complexity: O(log 10 (n)) // Space complexity : O(1) func isPalindrome(x int) bool { var ( y int z = x ) for x > 0 { y = y*10 + x%10 x /= 10 } return y == z } ================================================ FILE: solutions/0009_palindrome_number/palindrome_number_test.go ================================================ package palindromenumber import "testing" func TestIsPalindrome(t *testing.T) { testCases := []int{121, -121, 10, 0} expected := []bool{true, false, false, true} for index, data := range testCases { if res := isPalindrome(data); res != expected[index] { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/0011_container_with_most_water/container_with_most_water.go ================================================ /* 11. Container With Most Water https://leetcode.com/problems/container-with-most-water/ 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. Note: You may not slant the container and n is at least 2. */ // time: 2018-12-26 package containerwithmostwater import "leetcode/utils" // time complexity: O(n) // space complexity: O(1) func maxArea(height []int) int { var ( water int l int r = len(height) - 1 ) for l < r { h := utils.CalcMinInt(height[l], height[r]) water = utils.CalcMaxInt(water, (r-l)*h) for height[l] <= h && l < r { l++ } for height[r] <= h && l < r { r-- } } return water } // time complexity: O(n^2) // space complexity: O(n) func maxArea1(height []int) int { n := len(height) if n >= 0 && n < 2 { return 0 } memo := make([]int, n) memo[1] = 1 * utils.CalcMinInt(height[0], height[1]) for i := 2; i < n; i++ { for j := i - 1; j >= 0; j-- { memo[i] = utils.CalcMaxInt(memo[i], (i-j)*utils.CalcMinInt(height[i], height[j])) } } return utils.CalcMaxInt(memo...) } // time complexity: O(n^2) // space complexity: O(1) func maxArea2(height []int) int { res := 0 for i := 0; i < len(height); i++ { for j := i + 1; j < len(height); j++ { tmp := (j - i) * utils.CalcMinInt(height[i], height[j]) if tmp > res { res = tmp } } } return res } ================================================ FILE: solutions/0011_container_with_most_water/container_with_most_water_test.go ================================================ package containerwithmostwater import "testing" func TestMaxArea(t *testing.T) { testCases := [][]int{ {1, 8, 6, 2, 5, 4, 8, 3, 7}, {}, {1}, {1, 2}, {2, 3, 5, 7, 8, 9, 5, 3, 2}, } expected := []int{49, 0, 0, 1, 20} for index, data := range testCases { if res := maxArea(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } func TestMaxArea1(t *testing.T) { testCases := [][]int{ {1, 8, 6, 2, 5, 4, 8, 3, 7}, {}, {1}, {1, 2}, {2, 3, 5, 7, 8, 9, 5, 3, 2}, } expected := []int{49, 0, 0, 1, 20} for index, data := range testCases { if res := maxArea1(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } func TestMaxArea2(t *testing.T) { testCases := [][]int{ {1, 8, 6, 2, 5, 4, 8, 3, 7}, {}, {1}, {1, 2}, {2, 3, 5, 7, 8, 9, 5, 3, 2}, } expected := []int{49, 0, 0, 1, 20} for index, data := range testCases { if res := maxArea2(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0013_roman_to_integer/roman_to_integer.go ================================================ /* 13. Roman to Integer https://leetcode.com/problems/roman-to-integer/ */ // time: 2018-12-31 package rti // time complexity: O(n) // space complexity: O(1) func romanToInt(s string) int { if 0 == len(s) { return 0 } digits := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} sum := digits[s[len(s)-1]] for i := len(s) - 1; i > 0; i-- { cur := digits[s[i]] pre := digits[s[i-1]] if cur > pre { sum -= pre } else { sum += pre } } return sum } ================================================ FILE: solutions/0013_roman_to_integer/roman_to_integer_test.go ================================================ package rti import "testing" func TestRomanToInt(t *testing.T) { testCases := []string{ "III", "IV", "IX", "LVIII", "MCMXCIV", "", } expected := []int{3, 4, 9, 58, 1994, 0} for index, s := range testCases { if res := romanToInt(s); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0014_longest_common_prefix/lcp.go ================================================ /* 14. Longest Common Prefix https://leetcode.com/problems/longest-common-prefix/ Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". */ // time: 2018-12-31 package lcp // time complexity: O(len(strs) * max len of string) // space complexity: O(1) func longestCommonPrefix(strs []string) string { if 0 == len(strs) { return "" } res := "" for i := 0; i < len(strs[0]); i++ { c := strs[0][i] for j := 1; j < len(strs); j++ { if i >= len(strs[j]) || strs[j][i] != c { return res } } res += string(c) } return res } ================================================ FILE: solutions/0014_longest_common_prefix/lcp_test.go ================================================ package lcp import "testing" func TestLongestCommonPrefix(t *testing.T) { testCases := [][]string{ {"flower", "flow", "flight"}, {"dog", "racecar", "car"}, {}, {""}, } expected := []string{ "fl", "", "", "", } for index, strs := range testCases { if res := longestCommonPrefix(strs); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } ================================================ FILE: solutions/0015_3Sum/3sum.go ================================================ /* 15. 3Sum https://leetcode.com/problems/3sum/ */ // time: 2019-03-01 package threesum import "sort" // time complexity: O(n^2) func threeSum(nums []int) [][]int { sort.Ints(nums) var res [][]int for i := 0; i < len(nums)-2; i++ { if nums[i] > 0 { break } if i > 0 && nums[i] == nums[i-1] { continue } for l, r := i+1, len(nums)-1; l < r; { if l > i+1 && nums[l] == nums[l-1] { l++ continue } if r < len(nums)-1 && nums[r] == nums[r+1] { r-- continue } switch sum := nums[i] + nums[l] + nums[r]; { case sum < 0: l++ case sum > 0: r-- default: res = append(res, []int{nums[i], nums[l], nums[r]}) l++ r-- } } } return res } ================================================ FILE: solutions/0015_3Sum/3sum_test.go ================================================ package threesum import ( "reflect" "testing" ) func TestThreeSum(t *testing.T) { testData := [][]int{ {-1, 0, 1, 2, -6, -4}, {-7, 3, -7, 3, 4, 5, 6, 6, 4}, } expected := [][][]int{ {{-1, 0, 1}}, {{-7, 3, 4}}, } for index, nums := range testData { if res := threeSum(nums); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go ================================================ /* 17. Letter Combinations of a Phone Number Source: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want. */ package lettercombinationsofaphonenumber var ( letterMap = []string{ " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", } res []string ) // Time complexity: O(2^n) // Space complexity: O(n) func letterCombinations(digits string) []string { res = []string{} if digits == "" { return res } findCombinations(digits, 0, "") return res } func findCombinations(digits string, index int, s string) { if index == len(digits) { res = append(res, s) return } ch := digits[index] letters := letterMap[ch-'0'] for _, i := range letters { findCombinations(digits, index+1, s+string(i)) } return } ================================================ FILE: solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number_test.go ================================================ package lettercombinationsofaphonenumber import ( "reflect" "testing" ) func TestLetterCombinations(t *testing.T) { testData := []string{ "23", "", } expectedData := [][]string{ {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}, {}, } for index, digits := range testData { if res := letterCombinations(digits); !reflect.DeepEqual(res, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], res) } } } ================================================ FILE: solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go ================================================ /* 19. Remove Nth Node From End of List https://leetcode.com/problems/remove-nth-node-from-end-of-list/ Given a linked list, remove the n-th node from the end of list and return its head. */ // time: 2018-12-31 package rnthnfeol // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n) // space complexity: O(1) func removeNthFromEnd(head *ListNode, n int) *ListNode { if n <= 0 { return head } dummy := &ListNode{} dummy.Next = head var ( p = dummy q = dummy ) for i := 0; i < n; i++ { q = q.Next } for q.Next != nil { p = p.Next q = q.Next } p.Next = p.Next.Next return dummy.Next } ================================================ FILE: solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list_test.go ================================================ package rnthnfeol import ( "reflect" "testing" ) func TestRemoveNthFromEnd(t *testing.T) { type arg struct { head *ListNode n int } testCase := []arg{ {head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), n: 2}, {head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), n: 0}, } expected := []*ListNode{ createSingleLinkedList([]int{1, 2, 3, 5}), createSingleLinkedList([]int{1, 2, 3, 4, 5}), } for index, data := range testCase { if res := removeNthFromEnd(data.head, data.n); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected") } } } func createSingleLinkedList(arr []int) *ListNode { head := &ListNode{} cur := head for _, j := range arr { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } ================================================ FILE: solutions/0020_valid_parentheses/valid_parentheses.go ================================================ /* 20. Valid Parentheses Source: https://leetcode.com/problems/valid-parentheses/ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true */ package validparentheses // Time complexity: O(n) // Space complexity: O(n) func isValid(s string) bool { var ( stacks []rune mapping = map[rune]rune{')': '(', ']': '[', '}': '{'} ) for _, char := range s { if char == ')' || char == '}' || char == ']' { var topElement rune if len(stacks) > 0 { topElement = stacks[len(stacks)-1] stacks = stacks[:len(stacks)-1] } else { topElement = '#' } if mapping[char] != topElement { return false } } else { stacks = append(stacks, char) } } return len(stacks) == 0 } ================================================ FILE: solutions/0020_valid_parentheses/valid_parentheses_test.go ================================================ package validparentheses import "testing" func TestIsValid(t *testing.T) { testData := []string{"()", "(((((())))))", "()()()()", "(((((((()", "((()(())))", "", ")(", "}{", "][", "(][)"} expectedData := []bool{true, true, true, false, true, true, false, false, false, false} for i, s := range testData { result := isValid(s) if result != expectedData[i] { t.Error("测试不通过") } } } ================================================ FILE: solutions/0021_merge_two_sorted_lists/mergeTwoLists.go ================================================ /* 21. Merge Two Sorted Lists Source: https://leetcode.com/problems/merge-two-sorted-lists/ 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. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 */ package mergetwolists // ListNode is node of linked list type ListNode struct { Val int Next *ListNode } // Recursion // Time complexity: O(len(l1)+len(l2)) // Space complexity: O(len(l1)+len(l2)) func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil && l2 == nil { return nil } if l1 == nil { return l2 } if l2 == nil { return l1 } if l1.Val < l2.Val { l1.Next = mergeTwoLists(l1.Next, l2) return l1 } l2.Next = mergeTwoLists(l1, l2.Next) return l2 } ================================================ FILE: solutions/0021_merge_two_sorted_lists/mergeTwoLists_test.go ================================================ package mergetwolists import ( "reflect" "testing" ) func createSingleLinkedList(arr []int) *ListNode { head := &ListNode{} cur := head for _, j := range arr { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } func TestMergeTwoLists(t *testing.T) { testDatas := []struct { name string arg1 *ListNode arg2 *ListNode expected *ListNode }{ { name: "one", arg1: createSingleLinkedList([]int{1, 3, 5}), arg2: createSingleLinkedList([]int{2, 4, 6}), expected: createSingleLinkedList([]int{1, 2, 3, 4, 5, 6}), }, { name: "two", arg1: createSingleLinkedList([]int{1}), arg2: createSingleLinkedList([]int{2, 4, 6}), expected: createSingleLinkedList([]int{1, 2, 4, 6}), }, { name: "three", arg1: nil, arg2: nil, expected: nil, }, { name: "four", arg1: createSingleLinkedList([]int{2, 4, 6}), arg2: createSingleLinkedList([]int{1}), expected: createSingleLinkedList([]int{1, 2, 4, 6}), }, } for _, testData := range testDatas { t.Run(testData.name, func(t *testing.T) { if result := mergeTwoLists(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) { t.Errorf("mergeTwoLists() = %v, expected %v", result, testData.expected) } }) } } ================================================ FILE: solutions/0023_merge_k_sorted_lists/mksl.go ================================================ /* 23. Merge k Sorted Lists https://leetcode.com/problems/merge-k-sorted-lists/ Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. */ // time: 2019-01-02 package mksl import ( "sort" ) // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // heap // time complexity: O(n log n), where n is len of all lists, the main complexity is sort. // space complexity: O(n), where n is len of all lists. func mergeKLists(lists []*ListNode) *ListNode { for i := 0; i < len(lists); { if lists[i] == nil { lists = append(lists[0:i], lists[i+1:]...) } else { i++ } } if 0 == len(lists) { return nil } head := &ListNode{} cur := head for len(lists) > 0 { for i := (len(lists) - 1) / 2; i >= 0; i-- { siftUp(lists, len(lists), i) } cur.Next = &ListNode{Val: lists[0].Val} cur = cur.Next lists[0] = lists[0].Next if lists[0] == nil { lists = lists[1:] } } return head.Next } // build heap func siftUp(lists []*ListNode, n int, k int) { for 2*k+1 < n { j := 2*k + 1 if j+1 < n && lists[j+1].Val < lists[j].Val { j = j + 1 } if lists[k].Val < lists[j].Val { break } lists[j], lists[k] = lists[k], lists[j] k = j } } // brute force // time complexity: O(n log n), where n is len of all lists, the main complexity is sort. // space complexity: O(2n), where n is len of all lists. func mergeKLists1(lists []*ListNode) *ListNode { nodes := make([]int, 0) head := &ListNode{} pointer := head for _, j := range lists { for { if j != nil { nodes = append(nodes, j.Val) j = j.Next } else { break } } } sort.Ints(nodes) for _, j := range nodes { pointer.Next = &ListNode{Val: j} pointer = pointer.Next } return head.Next } ================================================ FILE: solutions/0023_merge_k_sorted_lists/mksl_test.go ================================================ package mksl import ( "reflect" "testing" ) func TestMergeKLists(t *testing.T) { testCases := [][]*ListNode{ { createSingleList([]int{1, 4, 5}), createSingleList([]int{2, 3, 4}), createSingleList([]int{4, 6}), }, { createSingleList([]int{}), createSingleList([]int{4, 5}), createSingleList([]int{}), }, { createSingleList([]int{}), createSingleList([]int{}), createSingleList([]int{}), }, { createSingleList([]int{1, 4, 5}), createSingleList([]int{1, 3, 4}), createSingleList([]int{2, 6}), }, } expected := []*ListNode{ createSingleList([]int{1, 2, 3, 4, 4, 4, 5, 6}), createSingleList([]int{4, 5}), nil, createSingleList([]int{1, 1, 2, 3, 4, 4, 5, 6}), } for index, lists := range testCases { if res := mergeKLists(lists); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } func TestMergeKLists1(t *testing.T) { testCases := [][]*ListNode{ { createSingleList([]int{1, 4, 5}), createSingleList([]int{1, 3, 4}), createSingleList([]int{2, 6}), }, { createSingleList([]int{}), createSingleList([]int{4, 5}), createSingleList([]int{}), }, { createSingleList([]int{}), createSingleList([]int{}), createSingleList([]int{}), }, } expected := []*ListNode{ createSingleList([]int{1, 1, 2, 3, 4, 4, 5, 6}), createSingleList([]int{4, 5}), nil, } for index, lists := range testCases { if res := mergeKLists1(lists); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } func createSingleList(nums []int) *ListNode { head := &ListNode{} cur := head for _, j := range nums { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } ================================================ FILE: solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go ================================================ /* 24. Swap Nodes in Pairs https://leetcode.com/problems/swap-nodes-in-pairs/ Given a linked list, swap every two adjacent nodes and return its head. */ // time: 2019-01-02 package swapnodesinpairs // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n/2), where n is len of linked list. // space complexity: O(1) func swapPairs(head *ListNode) *ListNode { dummy := &ListNode{} dummy.Next = head cur := dummy for cur.Next != nil && cur.Next.Next != nil { node1 := cur.Next node2 := node1.Next node3 := node2.Next node2.Next = node1 node1.Next = node3 cur.Next = node2 cur = node1 } return dummy.Next } ================================================ FILE: solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs_test.go ================================================ package swapnodesinpairs import ( "reflect" "testing" ) func TestSwapPairs(t *testing.T) { head := createSingleList([]int{1, 2, 3, 4}) expected := createSingleList([]int{2, 1, 4, 3}) if res := swapPairs(head); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } func createSingleList(nums []int) *ListNode { head := &ListNode{} cur := head for _, j := range nums { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } ================================================ FILE: solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go ================================================ /* 25. Reverse Nodes in k-Group Source: https://leetcode.com/problems/reverse-nodes-in-k-group/ Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 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. Example: Given this linked list: 1->2->3->4->5 For k = 2, you should return: 2->1->4->3->5 For k = 3, you should return: 3->2->1->4->5 Note: Only constant extra memory is allowed. You may not alter the values in the list's nodes, only nodes itself may be changed. */ package reversenodesinkgroup // ListNode is node of linked list type ListNode struct { Val int Next *ListNode } func reverseKGroup(head *ListNode, k int) *ListNode { if head == nil || head.Next == nil || k < 2 { return head } p := new(ListNode) s := new(ListNode) l := k p.Next = head head = p s = p for s != nil && k != 0 { s = s.Next k-- } for s != nil { reverse(&p, &s) k = l for s != nil && k != 0 { s = s.Next k-- } } return head.Next } func reverse(p **ListNode, s **ListNode) { var tmp *ListNode prev := (*p).Next tail := (*p).Next flag := (*s).Next (*p).Next = nil for prev != flag { tmp = (*p).Next (*p).Next = prev prev = prev.Next (*p).Next.Next = tmp } tail.Next = prev *p = tail *s = tail } ================================================ FILE: solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group_test.go ================================================ package reversenodesinkgroup import ( "reflect" "testing" ) func createSingleLinkedList(arr []int) *ListNode { head := &ListNode{} cur := head for _, j := range arr { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } func TestReverseKGroup(t *testing.T) { type args struct { head *ListNode k int } tests := []struct { name string args args expected *ListNode }{ { name: "one", args: args{ head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), k: 2, }, expected: createSingleLinkedList([]int{2, 1, 4, 3, 5}), }, { name: "two", args: args{ head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), k: 3, }, expected: createSingleLinkedList([]int{3, 2, 1, 4, 5}), }, { name: "three", args: args{ head: createSingleLinkedList([]int{1}), k: 2, }, expected: createSingleLinkedList([]int{1}), }, } for _, data := range tests { t.Run(data.name, func(t *testing.T) { if result := reverseKGroup(data.args.head, data.args.k); !reflect.DeepEqual(result, data.expected) { t.Errorf("reverseKGroup() = %v, expected %v", result, data.expected) } }) } } ================================================ FILE: solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go ================================================ /* 26. Remove Duplicates from Sorted Array https://leetcode.com/problems/remove-duplicates-from-sorted-array/ Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. */ // time: 2018-12-20 package rdfsa // double index // time complexity: O(n) // space complexity: O(1) func removeDuplicates(nums []int) int { n := len(nums) if 0 == n { return n } var ( res = 1 i = 1 index = nextDifferentCharacterIndex(nums, 1) // 下一个不重复的地址 ) for index < n { res++ nums[i] = nums[index] i++ index = nextDifferentCharacterIndex(nums, index+1) } return res } func nextDifferentCharacterIndex(nums []int, p int) int { for ; p < len(nums); p++ { if nums[p] != nums[p-1] { break } } return p } ================================================ FILE: solutions/0026_remove_duplicates_from_sorted_array/rdfsa_test.go ================================================ package rdfsa import "testing" func TestRemoveDuplicates(t *testing.T) { // removeDuplicates([]int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}) testCases := [][]int{ {1, 1, 2}, {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}, {}, } expected := []int{2, 5, 0} for index, data := range testCases { if res := removeDuplicates(data); expected[index] != res { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0027_remove_element/remove_element.go ================================================ /* 27. Remove Element https://leetcode.com/problems/remove-element/ Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. */ // time: 2018-12-20 package removeelement // two pointers // time complexity: O(n) // space complexity: O(1) func removeElement(nums []int, val int) int { x := 0 for j := 0; j < len(nums); j++ { if nums[j] != val { if x != j { nums[x] = nums[j] } x++ } } return x } /* func removeElement1(nums []int, val int) int { var ( l int r = len(nums) ) for l < r { if nums[l] == val { r-- nums[l] = nums[r] } else { l++ } } return r } */ ================================================ FILE: solutions/0027_remove_element/remove_element_test.go ================================================ package removeelement import "testing" func TestRemoveElement(t *testing.T) { nums := []int{0, 1, 2, 2, 3, 0, 4, 2} val := 2 expected := 5 if res := removeElement(nums, val); res != expected { t.Errorf("expected %d, got %d", expected, res) } } ================================================ FILE: solutions/0028_implement_strstr/implement_strstr.go ================================================ /* 28. Implement strStr() https://leetcode.com/problems/implement-strstr/ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. clarification: For the purpose of this problem, we will return 0 when needle is an empty string. */ // time: 2019-01-02 package implstr // time complexity: O( (m-n+1)*n ), where m is len(haystack), n is len(needle) // space complexity: O(1) func strStr(haystack string, needle string) int { if 0 == len(needle) { return 0 } for i, j := 0, 0; i <= len(haystack)-len(needle); i++ { for j = 0; j < len(needle); j++ { if haystack[i+j] != needle[j] { break } } if len(needle) == j { return i } } return -1 } ================================================ FILE: solutions/0028_implement_strstr/implement_strstr_test.go ================================================ package implstr import "testing" func TestStrStr(t *testing.T) { type arg struct { haystack string needle string } testCases := []arg{ {haystack: "hello", needle: "ll"}, {haystack: "aaaaa", needle: "bba"}, {haystack: "hello"}, } expected := []int{2, -1, 0} for index, data := range testCases { if res := strStr(data.haystack, data.needle); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go ================================================ /* 33. Search in Rotated Sorted Array https://leetcode.com/problems/search-in-rotated-sorted-array/ Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). */ // time: 2018-12-20 package searchinrotatedsortedarray // binary search /* 问题分析: 二分情况分为三种: 1.mid在pivot左边,即mid左边部分是有序的。 nums[mid] >= nums[l] && nums[mid] > nums[r] 此时,只需要比较target是否在左边有序部分。 2.mid在pivot右边,并且包含pivot,即mid右边是有序的。 nums[mid] < nums[l] && nums[mid] <= nums[r], 此时,只需要比较target是否在右边有序部分。 3. 整个array是有序的, nums[mid] >= nums[l] &&nums[mid] <= nums[r] 放在第一和第二中情况中处理都可以。 */ // time complexity: O(logn) // space complexity: O(1) func search(nums []int, target int) int { var ( l int r = len(nums) - 1 ) for l <= r { mid := l + (r-l)/2 if target == nums[mid] { return mid } if nums[mid] >= nums[l] && nums[mid] > nums[r] { if target >= nums[l] && target < nums[mid] { r = mid - 1 } else { l = mid + 1 } } else { if target > nums[mid] && target <= nums[r] { l = mid + 1 } else { r = mid - 1 } } } return -1 } ================================================ FILE: solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array_test.go ================================================ package searchinrotatedsortedarray import "testing" func TestSearch(t *testing.T) { type arg struct { nums []int target int } testCases := []arg{ {nums: []int{4, 5, 6, 7, 0, 1, 2}, target: 0}, {nums: []int{4, 5, 6, 7, 0, 1, 2}, target: 3}, {nums: []int{}, target: 2}, {nums: []int{4}, target: 4}, {nums: []int{4, 5, 6, 7, 0}, target: 0}, {nums: []int{9, 7}, target: 7}, {nums: []int{1, 3}, target: 3}, {nums: []int{4, 5, 6, 7, 8, 1, 2}, target: 5}, } expected := []int{4, -1, -1, 0, 4, 1, 1, 1} for index, data := range testCases { if res := search(data.nums, data.target); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go ================================================ /* 34. Find First and Last Position of Element in Sorted Array https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. */ // time: 2018-12-20 package findfirstandlastpositionofelementinsortedarray // binary search // time complexity: O(logn) // space complexity: O(1) func searchRange(nums []int, target int) []int { lowerIndex := firstOccurance(nums, target) first := -1 if lowerIndex != len(nums) && target == nums[lowerIndex] { first = lowerIndex } upperIndex := lastOccurance(nums, target) last := -1 if upperIndex == len(nums) && len(nums) > 0 && target == nums[len(nums)-1] { last = len(nums) - 1 } else if upperIndex != len(nums) && upperIndex > 0 && target == nums[upperIndex-1] { last = upperIndex - 1 } return []int{first, last} } func firstOccurance(nums []int, target int) int { var ( l int r = len(nums) ) for l != r { // 夹逼思想 mid := l + (r-l)/2 if nums[mid] < target { l = mid + 1 } else { r = mid } } return l } func lastOccurance(nums []int, target int) int { var ( l int r = len(nums) ) for l != r { mid := l + (r-l)/2 if nums[mid] <= target { l = mid + 1 } else { r = mid } } return l } // double index scan // Time complexity: O(n) // Space complexity: O(1) func searchRange1(nums []int, target int) []int { var ( l int r = len(nums) - 1 ) for l <= r { flag := false if nums[l] != target { l++ flag = true } if nums[r] != target { r-- flag = true } if !flag { break } } if r < l { return []int{-1, -1} } return []int{l, r} } // binary search + linear scan // Time complexity: O(logn) ~ O(n) // Space complexity: O(1) func searchRange2(nums []int, target int) []int { var ( l int r = len(nums) - 1 tmp = -1 ) for l <= r { mid := l + (r-l)/2 if nums[mid] == target { tmp = mid break } if nums[mid] < target { l = mid + 1 } else { r = mid - 1 } } if -1 == tmp { return []int{-1, -1} } l = tmp r = tmp for true { if l > 0 && nums[l-1] == target { l-- } else { break } } for true { if r < len(nums)-1 && target == nums[r+1] { r++ } else { break } } return []int{l, r} } ================================================ FILE: solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array_test.go ================================================ package findfirstandlastpositionofelementinsortedarray import ( "reflect" "runtime" "testing" ) func TestSearchRange(t *testing.T) { type arg struct { nums []int target int } testCases := []arg{ { nums: []int{5, 7, 7, 8, 8, 10}, target: 8, }, { nums: []int{5, 7, 7, 8, 8, 10}, target: 6, }, { nums: []int{1}, target: 1, }, { nums: []int{}, target: 0, }, { nums: []int{2, 2}, target: 2, }, { nums: []int{1}, target: 0, }, } expected := [][]int{ {3, 4}, {-1, -1}, {0, 0}, {-1, -1}, {0, 1}, {-1, -1}, } testFuncs := []func([]int, int) []int{ searchRange, searchRange1, searchRange2, } for _, testFunc := range testFuncs { for index, testData := range testCases { if res := testFunc(testData.nums, testData.target); !reflect.DeepEqual(res, expected[index]) { t.Errorf("function %s, expected %v, got %v", runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name(), expected[index], res) } } } } ================================================ FILE: solutions/0035_search_insert_position/search_insert_position.go ================================================ /* 35. Search Insert Position https://leetcode.com/problems/search-insert-position/ 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. You may assume no duplicates in the array. */ // time: 2019-01-02 package sip // binary search // time complexity: O( log n ) // space complexity: O(1) func searchInsert(nums []int, target int) int { var ( l int r = len(nums) - 1 ) for l <= r { mid := l + (r-l)/2 if target == nums[mid] { return mid } if target < nums[mid] { r = mid - 1 } else { l = mid + 1 } } return l } ================================================ FILE: solutions/0035_search_insert_position/search_insert_position_test.go ================================================ package sip import "testing" func TestSearchInsert(t *testing.T) { testCases := [][]int{ {1, 3, 5, 6}, {1, 3, 5, 6}, {1, 3, 5, 6}, {1, 3, 5, 6}, } targets := []int{5, 2, 7, 0} expected := []int{2, 1, 4, 0} for index, nums := range testCases { if res := searchInsert(nums, targets[index]); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0048_rotate_image/rotate_image.go ================================================ /* 48. Rotate Image https://leetcode.com/problems/rotate-image/ You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. */ // time: 2019-01-02 package ri // time complexity: O(n^2) // space complexity: O(1) func rotate(matrix [][]int) { /* [ [1,2,3], [4,5,6], [7,8,9] ] */ n := len(matrix) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] } } /* [ [1,4,7], [2,5,8], [3,6,9] ] */ for i := 0; i < n; i++ { for j := 0; j < n/2; j++ { matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j] } } /* [ [7,4,1], [8,5,2], [9,6,3] ] */ } ================================================ FILE: solutions/0048_rotate_image/rotate_image_test.go ================================================ package ri import ( "reflect" "testing" ) func TestRotate(t *testing.T) { matrix := [][]int{ {5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}, } expected := [][]int{ {15, 13, 2, 5}, {14, 3, 4, 1}, {12, 6, 8, 9}, {16, 7, 10, 11}, } if rotate(matrix); !reflect.DeepEqual(matrix, expected) { t.Errorf("expected %v, got %v", expected, matrix) } } ================================================ FILE: solutions/0053_maximum_subarray/maximum_subarray.go ================================================ /* 53. Maximum Subarray https://leetcode.com/problems/maximum-subarray/ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. */ // time: 2019-01-02 package maximumsubarray import ( "fmt" "math" ) // time complexity: O(n) // space complexity: O(1) func maxSubArray(nums []int) int { var ( max = math.MinInt32 sum int start, end, f int ) for i, j := range nums { sum += j if sum > max { if f != 0 { start = f + 1 f = 0 } max = sum end = i } if sum < 0 { f = i sum = 0 } } fmt.Printf("start index is %d, end index is %d\n", start, end) return max } ================================================ FILE: solutions/0053_maximum_subarray/maximum_subarray_test.go ================================================ package maximumsubarray import "testing" func TestMaxSubarray(t *testing.T) { nums := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} expected := 6 if res := maxSubArray(nums); res != expected { t.Errorf("expected %d, got %d", expected, res) } } ================================================ FILE: solutions/0058_length_of_last_word/len_of_last_word.go ================================================ /* 58. Length of Last Word https://leetcode.com/problems/length-of-last-word/ Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. */ // time: 2019-01-02 package lenoflastword // time complexity: O(n) // space complexity: O(1) func lengthOfLastWord(s string) int { var ( n = len(s) cur = n - 1 ) for cur >= 0 { if n-1 == cur && s[cur] == 32 { cur-- n-- continue } if s[cur] != 32 { cur-- } else { break } } return n - cur - 1 } ================================================ FILE: solutions/0058_length_of_last_word/len_of_last_word_test.go ================================================ package lenoflastword import "testing" func TestLengthOfLastWord(t *testing.T) { s := "hello world " expected := 5 if res := lengthOfLastWord(s); res != expected { t.Errorf("expected %d, got %d", expected, res) } } ================================================ FILE: solutions/0061_rotate_list/rotate_list.go ================================================ /* 61. Rotate List Source: https://leetcode.com/problems/rotate-list/ Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL Example 2: Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL rotate 1 steps to the right: 2->0->1->NULL Explanation: rotate 2 steps to the right: 1->2->0->NULL otate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL */ package rotatelist // ListNode is node of linked list type ListNode struct { Val int Next *ListNode } func rotateRight(head *ListNode, k int) *ListNode { if k == 0 || head == nil || head.Next == nil { return head } var ( listSize int count int p = head rotateNode = head ) for p != nil && count < k { p = p.Next listSize++ count++ } if p == nil { k = k % listSize if k == 0 { return head } p = head for count = 0; count < k; count++ { p = p.Next } } for p.Next != nil { rotateNode = rotateNode.Next p = p.Next } p.Next = head head = rotateNode.Next rotateNode.Next = nil return head } ================================================ FILE: solutions/0061_rotate_list/rotate_list_test.go ================================================ package rotatelist import ( "reflect" "testing" ) func createSingleLinkedList(arr []int) *ListNode { head := &ListNode{} cur := head for _, j := range arr { cur.Next = &ListNode{Val: j} cur = cur.Next } return head.Next } func TestRotateList(t *testing.T) { testDatas := []struct { name string arg *ListNode k int expected *ListNode }{ { name: "one", arg: createSingleLinkedList([]int{1, 2, 3, 4}), k: 2, expected: createSingleLinkedList([]int{3, 4, 1, 2}), }, { name: "two", arg: createSingleLinkedList([]int{1, 2, 3}), k: 3, expected: createSingleLinkedList([]int{1, 2, 3}), }, { name: "three", arg: createSingleLinkedList([]int{1, 2, 3}), k: 5, expected: createSingleLinkedList([]int{2, 3, 1}), }, { name: "four", arg: createSingleLinkedList([]int{1, 2, 3}), k: 0, expected: createSingleLinkedList([]int{1, 2, 3}), }, { name: "five", arg: nil, k: 0, expected: nil, }, { name: "four", arg: createSingleLinkedList([]int{1}), k: 5, expected: createSingleLinkedList([]int{1}), }, } for _, testData := range testDatas { t.Run(testData.name, func(t *testing.T) { if result := rotateRight(testData.arg, testData.k); !reflect.DeepEqual(result, testData.expected) { t.Errorf("expected %v, got %v", testData.expected, result) } }) } } ================================================ FILE: solutions/0062_unique_paths/unique_paths.go ================================================ /* 62. Unique Paths Source: https://leetcode.com/problems/unique-paths/ A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 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). How many possible unique paths are there? Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 */ package uniquepaths // recursion /* func uniquePaths(m int, n int) int { if m == 1 || n == 1 { return 1 } return uniquePaths(m, n-1) + uniquePaths(m-1, n) } */ // memory search /* func uniquePaths(m int, n int) int { memo := make([][]int, m) // memo[i][j]存储(i+1)*(j+1)grid的路径数量 for i := 0; i < m; i++ { for j := 0; j < n; j++ { memo[i] = append(memo[i], -1) } } return calcPaths(m, n, memo) } func calcPaths(m int, n int, memo [][]int) int { if memo[m-1][n-1] != -1 { return memo[m-1][n-1] } if m == 1 || n == 1 { memo[m-1][n-1] = 1 return 1 } res := calcPaths(m, n-1, memo) + calcPaths(m-1, n, memo) memo[m-1][n-1] = res return res } */ func uniquePaths(m int, n int) int { memo := make([][]int, m) // memo[i][j]存储(i+1)*(j+1)grid的路径数量 for i := 0; i < m; i++ { memo[i] = append(memo[i], 1) } for i := 1; i < n; i++ { memo[0] = append(memo[0], 1) } for i := 1; i < m; i++ { for j := 1; j < n; j++ { memo[i] = append(memo[i], memo[i-1][j]+memo[i][j-1]) } } return memo[m-1][n-1] } ================================================ FILE: solutions/0062_unique_paths/unique_paths_test.go ================================================ package uniquepaths import "testing" func TestUniquePaths(t *testing.T) { testData := [][2]int{ {3, 2}, {51, 9}, {9, 9}, } expectedData := []int{3, 1916797311, 12870} for index, data := range testData { if res := uniquePaths(data[0], data[1]); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0063_unique_paths_2/unique_paths2.go ================================================ /* 63. Unique Paths II Source: https://leetcode.com/problems/unique-paths-ii/ A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 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). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. Note: m and n will be at most 100. Example 1: Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right */ package uniquepaths2 // recursion /* func uniquePathsWithObstacles(obstacleGrid [][]int) int { m := len(obstacleGrid) n := len(obstacleGrid[0]) cur := 1 if m == 1 { for i := 0; i < n; i++ { if obstacleGrid[0][i] == 1 { cur = 0 } } return cur } cur = 1 if n == 1 { for i := 0; i < m; i++ { if obstacleGrid[i][0] == 1 { cur = 0 } } return cur } if obstacleGrid[m-1][n-1] == 1 { return 0 } obstacleGridCut := make([][]int, m) for i := range obstacleGridCut { for j := 0; j < n-1; j++ { obstacleGridCut[i] = append(obstacleGridCut[i], obstacleGrid[i][j]) } } return uniquePathsWithObstacles(obstacleGrid[:m-1]) + uniquePathsWithObstacles(obstacleGridCut) } */ // memory search /* func uniquePathsWithObstacles(obstacleGrid [][]int) int { m := len(obstacleGrid) n := len(obstacleGrid[0]) memo := make([][]int, m) for i := 0; i < m; i++ { for j := 0; j < n; j++ { memo[i] = append(memo[i], -1) } } cur := 1 for i := 0; i < m; i++ { if obstacleGrid[i][0] == 1 { cur = 0 } memo[i][0] = cur } cur = 1 for j := 0; j < n; j++ { if obstacleGrid[0][j] == 1 { cur = 0 } memo[0][j] = cur } return calcUniquePaths(obstacleGrid, m-1, n-1, memo) } func calcUniquePaths(obstacleGrid [][]int, m int, n int, memo [][]int) int { if memo[m][n] != -1 { return memo[m][n] } if obstacleGrid[m][n] == 1 { return 0 } res := calcUniquePaths(obstacleGrid, m-1, n, memo) + calcUniquePaths(obstacleGrid, m, n-1, memo) memo[m][n] = res return res } */ // dynamic programming func uniquePathsWithObstacles(obstacleGrid [][]int) int { m := len(obstacleGrid) n := len(obstacleGrid[0]) memo := make([][]int, m) for i := 0; i < m; i++ { for j := 0; j < n; j++ { memo[i] = append(memo[i], -1) } } cur := 1 for i := 0; i < m; i++ { if obstacleGrid[i][0] == 1 { cur = 0 } memo[i][0] = cur } cur = 1 for j := 0; j < n; j++ { if obstacleGrid[0][j] == 1 { cur = 0 } memo[0][j] = cur } for i := 1; i < m; i++ { for j := 1; j < n; j++ { if obstacleGrid[i][j] == 1 { memo[i][j] = 0 } else { memo[i][j] = memo[i-1][j] + memo[i][j-1] } } } return memo[m-1][n-1] } ================================================ FILE: solutions/0063_unique_paths_2/unique_paths2_test.go ================================================ package uniquepaths2 import "testing" func TestUniquePaths2(t *testing.T) { testData := [][][]int{ { {0, 0, 0}, {0, 1, 0}, {0, 0, 0}, }, { {0, 0, 0}, {0, 1, 0}, {0, 0, 0}, {0, 1, 0}, }, { {1}, }, { {1, 0}, }, } expectedData := []int{2, 2, 0, 0} for index, data := range testData { if res := uniquePathsWithObstacles(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0064_minimum_path_sum/minimum_path_sum.go ================================================ /* 64. Minimum Path Sum source: https://leetcode.com/problems/minimum-path-sum/ Description 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. Note: You can only move either down or right at any point in time. Example: Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum. */ package minimumpathsum // recursion dfs /* func minPathSum(grid [][]int) int { if len(grid) == 0{ return 0 } MaxUint:= ^uint(0) MaxInt := int(MaxUint >> 1) result := MaxInt dfs(0,0,0, grid, &result) return result } func dfs(x int, y int, sum int, grid [][]int, result *int) { m := len(grid) n := len(grid[0]) sum += grid[x][y] if x+1 < m && y+1 < n { dfs(x+1, y, sum, grid, result) dfs(x, y+1, sum, grid, result) } if x +1 == m && y+1 < n { dfs(x, y+1, sum, grid, result) } if y+1 == n && x+1 < m { dfs(x+1, y, sum, grid, result) } if x+1 == m && y+1 == n { if sum < *result { *result = sum } return } }*/ // dynamic programming func minPathSum(grid [][]int) int { if len(grid) == 0 { return 0 } m := len(grid) n := len(grid[0]) dp := make([][]int, m) dp[0] = append(dp[0], grid[0][0]) for i := 1; i < m; i++ { dp[i] = append(dp[i], grid[i][0]+dp[i-1][0]) } for i := 1; i < n; i++ { dp[0] = append(dp[0], grid[0][i]+dp[0][i-1]) } for i := 1; i < m; i++ { for j := 1; j < n; j++ { if dp[i-1][j] < dp[i][j-1] { dp[i] = append(dp[i], grid[i][j]+dp[i-1][j]) } else { dp[i] = append(dp[i], grid[i][j]+dp[i][j-1]) } } } return dp[m-1][n-1] } ================================================ FILE: solutions/0064_minimum_path_sum/minimum_path_sum_test.go ================================================ package minimumpathsum import "testing" func TestMininumPathSum(t *testing.T) { testData := [][][]int{ { {1, 3, 1}, {1, 5, 1}, {4, 2, 1}, }, { {3, 8, 6, 0, 5, 9, 9, 6, 3, 4, 0, 5, 7, 3, 9, 3}, {0, 9, 2, 5, 5, 4, 9, 1, 4, 6, 9, 5, 6, 7, 3, 2}, {8, 2, 2, 3, 3, 3, 1, 6, 9, 1, 1, 6, 6, 2, 1, 9}, {1, 3, 6, 9, 9, 5, 0, 3, 4, 9, 1, 0, 9, 6, 2, 7}, {8, 6, 2, 2, 1, 3, 0, 0, 7, 2, 7, 5, 4, 8, 4, 8}, {4, 1, 9, 5, 8, 9, 9, 2, 0, 2, 5, 1, 8, 7, 0, 9}, {6, 2, 1, 7, 8, 1, 8, 5, 5, 7, 0, 2, 5, 7, 2, 1}, {8, 1, 7, 6, 2, 8, 1, 2, 2, 6, 4, 0, 5, 4, 1, 3}, {9, 2, 1, 7, 6, 1, 4, 3, 8, 6, 5, 5, 3, 9, 7, 3}, {0, 6, 0, 2, 4, 3, 7, 6, 1, 3, 8, 6, 9, 0, 0, 8}, {4, 3, 7, 2, 4, 3, 6, 4, 0, 3, 9, 5, 3, 6, 9, 3}, {2, 1, 8, 8, 4, 5, 6, 5, 8, 7, 3, 7, 7, 5, 8, 3}, {0, 7, 6, 6, 1, 2, 0, 3, 5, 0, 8, 0, 8, 7, 4, 3}, {0, 4, 3, 4, 9, 0, 1, 9, 7, 7, 8, 6, 4, 6, 9, 5}, {6, 5, 1, 9, 9, 2, 2, 7, 4, 2, 7, 2, 2, 3, 7, 2}, {7, 1, 9, 6, 1, 2, 7, 0, 9, 6, 6, 4, 4, 5, 1, 0}, {3, 4, 9, 2, 8, 3, 1, 2, 6, 9, 7, 0, 2, 4, 2, 0}, {5, 1, 8, 8, 4, 6, 8, 5, 2, 4, 1, 6, 2, 2, 9, 7}, }, {}, } expectedData := []int{7, 83, 0} for index, data := range testData { if mininumPathSum := minPathSum(data); expectedData[index] != mininumPathSum { t.Errorf("expected %d, got %d", expectedData[index], mininumPathSum) } } } ================================================ FILE: solutions/0066_plus_one/plus_one.go ================================================ /* 66. Plus One https://leetcode.com/problems/plus-one/ Given a non-empty array of digits representing a non-negative integer, plus one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. */ // time: 2019-01-02 package plusone // time complexity: O(n) // space complexity: O(1) func plusOne(digits []int) []int { var ( carry = 1 index = len(digits) - 1 ) for index >= 0 { sum := carry + digits[index] digits[index] = sum % 10 carry = sum / 10 index-- } if carry > 0 { digits = append(digits, 0) copy(digits[1:], digits[0:]) digits[0] = carry } return digits } ================================================ FILE: solutions/0066_plus_one/plus_one_test.go ================================================ package plusone import ( "reflect" "testing" ) func TestPlusOne(t *testing.T) { digits := []int{9, 9, 9, 9} expected := []int{1, 0, 0, 0, 0} if res := plusOne(digits); !reflect.DeepEqual(expected, res) { t.Errorf("expected %v, got %v", expected, res) } } ================================================ FILE: solutions/0067_add_binary/add_binary.go ================================================ /* 67. Add Binary https://leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example: Input: a = "11", b = "1" Output: "100" */ // time: 2018-12-19 package addbinary import ( "strconv" ) // Time complexity: O( max( len(a), len(b) ) ) // Space complexity: O(1) func addBinary(a string, b string) string { var ( lenA = len(a) lenB = len(b) carry int res = "" ) for lenA > 0 && lenB > 0 { tmp := int(a[lenA-1]-'0') + int(b[lenB-1]-'0') + carry res = strconv.Itoa(tmp%2) + res carry = tmp / 2 lenA-- lenB-- } if lenA == 0 { for lenB > 0 { tmp := int(b[lenB-1]-'0') + carry res = strconv.Itoa(tmp%2) + res carry = tmp / 2 lenB-- } } if lenB == 0 { for lenA > 0 { tmp := int(a[lenA-1]-'0') + carry res = strconv.Itoa(tmp%2) + res carry = tmp / 2 lenA-- } } if carry == 1 { res = strconv.Itoa(carry) + res } return res } ================================================ FILE: solutions/0067_add_binary/add_binary_test.go ================================================ package addbinary import ( "testing" ) func TestAddBinary(t *testing.T) { type arg struct { a string b string } testCases := []arg{ { a: "11", b: "1", }, { b: "11", a: "1", }, } expected := []string{ "100", "100", } for index, data := range testCases { if res := addBinary(data.a, data.b); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } ================================================ FILE: solutions/0069_sqrtx/sqrtx.go ================================================ /* 69. Sqrt(x) https://leetcode.com/problems/sqrtx/ Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. */ // time: 2018-12-20 package sqrtx // binary search // time complexity: O(logn) // space complexity: O(1) func mySqrt(x int) int { var ( l int r = x // 在0~x范围内寻找平凡根 ) for l <= r { mid := l + (r-l)>>1 //位运算更高效 if mid*mid == x { return mid } if mid*mid < x { if (mid+1)*(mid+1) > x { return mid // 返回整数部分 } l = mid + 1 } else { r = mid - 1 } } return x // 不会执行,如果x为负数,会执行到此处,但是不符合题目要求。 } ================================================ FILE: solutions/0069_sqrtx/sqrtx_test.go ================================================ package sqrtx import "testing" func TestMySqrt(t *testing.T) { testCases := []int{66, 99, 9} expected := []int{8, 9, 3} for index, data := range testCases { if res := mySqrt(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0070_climbing_stairs/climbing_stairs.go ================================================ /* 70. Climbing Stairs source:https://leetcode.com/problems/climbing-stairs/ You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step */ package climbingstairs // recursion /* func climbStairs(n int) int { // if n == 1 { // return 1 // } // if n == 2 { // return 2 // } // if n == 1 || n == 0 { return 1 } return climbStairs(n-1) + climbStairs(n-2) } */ // memory search /* func climbStairs(n int) int { var memo []int for i := 0; i <= n; i++ { memo = append(memo, -1) } return calcWays(n, memo) } func calcWays(n int, memo []int) int { if n == 0 || n == 1 { return 1 } if memo[n] == -1 { memo[n] = calcWays(n-1, memo) + calcWays(n-2, memo) } return memo[n] } */ // dynamic programming func climbStairs(n int) int { var memo = []int{1, 1} for i := 2; i <= n; i++ { memo = append(memo, memo[i-1]+memo[i-2]) } return memo[n] } ================================================ FILE: solutions/0070_climbing_stairs/climbing_stairs_test.go ================================================ package climbingstairs import "testing" func TestClimbStairs(t *testing.T) { testDatas := []int{0, 1, 2, 3, 34} expected := []int{1, 1, 2, 3, 9227465} for i, data := range testDatas { if steps := climbStairs(data); steps != expected[i] { t.Errorf("expected %d, got %d", expected[i], steps) } } } ================================================ FILE: solutions/0075_sort_colors/sort_colors.go ================================================ /* 75. Sort Colors https://leetcode.com/problems/sort-colors/ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. */ // time: 2018-12-21 package sortcolors // 计数排序 // time complexity: O(n) // space complexity: O(1) func sortColorsCountSort(nums []int) { var count = [3]int{} for _, num := range nums { count[num]++ } index := 0 for i, j := range count { for k := 0; k < j; k++ { nums[index] = i index++ } } } // quick sort 3 ways // time complexity: O(n) // space complexity: O(1) func sortColorsQuickSort3Ways(nums []int) { var ( zero = -1 two = len(nums) ) for i := 0; i < two; { if 1 == nums[i] { i++ } else if 2 == nums[i] { two-- nums[i], nums[two] = nums[two], nums[i] } else { // nums[i] == 0 zero++ nums[i], nums[zero] = nums[zero], nums[i] i++ } } } ================================================ FILE: solutions/0075_sort_colors/sort_colors_test.go ================================================ package sortcolors import ( "reflect" "testing" ) func TestSortColorsCountSort(t *testing.T) { nums := []int{2, 0, 2, 1, 1, 0} expected := []int{0, 0, 1, 1, 2, 2} sortColorsCountSort(nums) if !reflect.DeepEqual(nums, expected) { t.Errorf("expected %v, got %v", expected, nums) } } func TestSortColorsQuickSort3Ways(t *testing.T) { nums := []int{2, 0, 2, 1, 1, 0} expected := []int{0, 0, 1, 1, 2, 2} sortColorsQuickSort3Ways(nums) if !reflect.DeepEqual(nums, expected) { t.Errorf("expected %v, got %v", expected, nums) } } ================================================ FILE: solutions/0076_minimum_window_substring/minimum_window_substring.go ================================================ /* 76. Minimum Window Substring https://leetcode.com/problems/minimum-window-substring/ 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). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: 1. If there is no such window in S that covers all characters in T, return the empty string "". 2. If there is such window, you are guaranteed that there will always be only one unique minimum window in S. */ package minimumwindowsubstring import "leetcode/utils" /* 使用滑动窗口解决这一问题,使用map或者slice统计T字符串中的字母的个数,之后,开始遍历S字符串,对于S中遍历到 的每一个字母,都在map或者slice中的对应个数减一,如果减一后仍然大于等于0,说明当前遍历到的字母是T中的字母, 使用计数器count,使其加一,当count和T串字母个数相等时,说明此时的窗口已经包含了T串中的所有字母,此时记录 一下字串和字串长度, 然后开始收缩左边界,由于我们遍历的时候,对应值减了1,所以此时去除字母的时候,就要把减去的1加回来, 此时如果加1后的值大于0了,说明此时我们少了一个T中的字母,那么count值就要减1了,然后移动左边界left。 */ // sliding window // Time complexity: O(n) // Space complexity: O(128) = O(1) func minWindow(s string, t string) string { var ( res string letterCount = make([]int, 128) left int count int minLen = utils.MaxInt ) for i := 0; i < len(t); i++ { letterCount[t[i]]++ } for i := 0; i < len(s); i++ { if letterCount[s[i]]--; letterCount[s[i]] >= 0 { count++ } for count == len(t) { if minLen > i-left+1 { minLen = i - left + 1 res = s[left : minLen+left] } if letterCount[s[left]]++; letterCount[s[left]] > 0 { count-- } left++ } } return res } ================================================ FILE: solutions/0076_minimum_window_substring/minimum_window_substring_test.go ================================================ package minimumwindowsubstring import "testing" func TestMinWindow(t *testing.T) { s := "ADOBECODEBANC" l := "ABC" expected := "BANC" if res := minWindow(s, l); res != expected { t.Errorf("expected %s, got %s", expected, res) } } ================================================ FILE: solutions/0077_combinations/combinations.go ================================================ /* 77. Combinations https://leetcode.com/problems/combinations/ Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. */ // time: 2019-01-04 package combinations // backtracking // time complexity: O(n^k) // space complexity: O(k) func combine(n int, k int) [][]int { if n <= 0 || k <= 0 || k > n { return [][]int{} } res := make([][]int, 0) c := make([]int, 0, k) generateCombinations(n, k, 1, c, &res) return res } // 求解C(n,k), 当前已经找到的组合存储在c中,需要从start开始搜索新元素。 func generateCombinations(n, k, start int, c []int, res *[][]int) { if len(c) == k { cpy := make([]int, k) copy(cpy, c) *res = append(*res, cpy) return } // 回朔法剪枝。 // 还有k - len(c)个空位,所以, [i...n]中至少要有k - len(c)个元素 // i最多为n-(k-len(c))+1 for i := start; i <= n-(k-len(c))+1; i++ { c = append(c, i) generateCombinations(n, k, i+1, c, res) c = c[:len(c)-1] } } ================================================ FILE: solutions/0077_combinations/combinations_test.go ================================================ package combinations import ( "reflect" "testing" ) func TestCombine(t *testing.T) { type arg struct { n, k int } testCases := []arg{ {n: 0, k: 2}, {n: 2, k: 0}, {n: 1, k: 5}, {n: 4, k: 2}, } expected := [][][]int{ {}, {}, {}, {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}, } for index, data := range testCases { if res := combine(data.n, data.k); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0079_word_search/word_search.go ================================================ /* 79. Word Search https://leetcode.com/problems/word-search/ Given a 2D board and a word, find if the word exists in the grid. 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. */ // 2019-01-04 package wordsearch var ( d = [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} m, n int visited [][]bool ) // backtracking // time complexity: O(m*n*m*n) // space complexity: O(m*n) func exist(board [][]byte, word string) bool { m = len(board) n = len(board[0]) visited = make([][]bool, m) for i := 0; i < m; i++ { visited[i] = make([]bool, n) } for i := 0; i < len(board); i++ { for j := 0; j < len(board[i]); j++ { if searchWord(board, word, 0, i, j) { return true } } } return false } func searchWord(board [][]byte, word string, index, startX, startY int) bool { if len(word)-1 == index { return board[startX][startY] == word[index] } if board[startX][startY] == word[index] { visited[startX][startY] = true // 从startX, startY开始,向四个方向寻找 for i := 0; i < 4; i++ { newX := startX + d[i][0] newY := startY + d[i][1] if inArea(newX, newY) && !visited[newX][newY] && searchWord(board, word, index+1, newX, newY) { return true } } visited[startX][startY] = false } return false } func inArea(x, y int) bool { return x >= 0 && x < m && y >= 0 && y < n } ================================================ FILE: solutions/0079_word_search/word_search_test.go ================================================ package wordsearch import "testing" func TestExist(t *testing.T) { board := [][]byte{ {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}, } testCases := []string{ "ABCCED", "SEE", "ABCB", } expected := []bool{true, true, false} for index, word := range testCases { if res := exist(board, word); res != expected[index] { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go ================================================ /* 80. Remove Duplicates from Sorted Array II https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. */ // time: 2018-12-21 package rdfsa2 // double index // time complexity: O(n) // space complexity: O(1) func removeDuplicates(nums []int) int { n := len(nums) if 0 == n || 1 == n { return n } var ( res = 2 i = 2 index = nextDifferentCharacterIndex(nums, i, 2) // 寻找下一个满足条件的下标 ) for index < n { res++ nums[i] = nums[index] i++ index = nextDifferentCharacterIndex(nums, i, index+1) } return res } func nextDifferentCharacterIndex(nums []int, j int, p int) int { for ; p < len(nums); p++ { if nums[j-1] == nums[j-2] && nums[p] != nums[j-1] || nums[j-1] != nums[j-2] { break } } return p } ================================================ FILE: solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2_test.go ================================================ package rdfsa2 import "testing" func TestRemoveDuplicates(t *testing.T) { testCases := [][]int{ {1, 1, 1, 2, 2, 3}, {1, 2, 2}, {0, 0, 1, 1, 1, 1, 2, 3, 3}, {}, {1}, {2, 2}, {2, 2, 2}, } expected := []int{5, 3, 7, 0, 1, 2, 2} for index, data := range testCases { if res := removeDuplicates(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go ================================================ /* 82. Remove Duplicates from Sorted List II https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. */ // time: 2019-01-04 package rdfsl // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n) // space complexity: O(1) func deleteDuplicates(head *ListNode) *ListNode { dummyHead := &ListNode{} dummyHead.Next = head pre := dummyHead cur := head for cur != nil && cur.Next != nil { if cur.Val == cur.Next.Val { num := cur.Val for cur != nil && cur.Val == num { cur = cur.Next } pre.Next = cur } else { pre = cur cur = cur.Next } } return dummyHead.Next } ================================================ FILE: solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl_test.go ================================================ package rdfsl import ( "reflect" "testing" ) func TestDeleteDuplicates(t *testing.T) { testCases := []*ListNode{ createSingleLinkedList([]int{1, 2, 3, 3, 4, 4, 5}), createSingleLinkedList([]int{1, 1, 1, 2, 3}), } expected := []*ListNode{ createSingleLinkedList([]int{1, 2, 5}), createSingleLinkedList([]int{2, 3}), } for index, head := range testCases { if res := deleteDuplicates(head); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } func createSingleLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } ================================================ FILE: solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go ================================================ /* 83. Remove Duplicates from Sorted List https://leetcode.com/problems/remove-duplicates-from-sorted-list/ Given a sorted linked list, delete all duplicates such that each element appear only once. */ package rdfsl // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n) // space complexity: O(1) func deleteDuplicates(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } var ( pre = head cur = head.Next ) for cur != nil { if cur.Val == pre.Val { pre.Next = cur.Next cur = cur.Next } else { pre = cur cur = cur.Next } } return head } ================================================ FILE: solutions/0083_remove_duplicates_from_sorted_list/rdfsl_test.go ================================================ package rdfsl import ( "reflect" "testing" ) func createSingleLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } func TestDeleteDuplicates(t *testing.T) { testCases := []*ListNode{ createSingleLinkedList([]int{1, 1, 2}), createSingleLinkedList([]int{1, 1, 2, 3, 3}), nil, } expected := []*ListNode{ createSingleLinkedList([]int{1, 2}), createSingleLinkedList([]int{1, 2, 3}), nil, } for index, head := range testCases { if res := deleteDuplicates(head); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0086_partition_list/partition_list.go ================================================ /* 86. Partition List https://leetcode.com/problems/partition-list/ 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. You should preserve the original relative order of the nodes in each of the two partitions. */ // time: 2019-01-04 package partitionlist // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n) // space complexity: O(1) func partition(head *ListNode, x int) *ListNode { var ( dummyHead1 = &ListNode{} dummyHead2 = &ListNode{} cur1 = dummyHead1 cur2 = dummyHead2 ) for cur := head; cur != nil; { if cur.Val < x { cur1.Next = cur cur1 = cur1.Next cur = cur.Next cur1.Next = nil } else { cur2.Next = cur cur2 = cur2.Next cur = cur.Next cur2.Next = nil } } cur1.Next = dummyHead2.Next return dummyHead1.Next } ================================================ FILE: solutions/0086_partition_list/partition_list_test.go ================================================ package partitionlist import ( "reflect" "testing" ) func createSingleLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } func TestDeleteDuplicates(t *testing.T) { testCase := createSingleLinkedList([]int{1, 4, 3, 2, 5, 2}) expected := createSingleLinkedList([]int{1, 2, 2, 4, 3, 5}) x := 3 if res := partition(testCase, x); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } ================================================ FILE: solutions/0088_merge_sorted_array/msa.go ================================================ /* 88. Merge Sorted Array https://leetcode.com/problems/merge-sorted-array/ Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: 1. The number of elements initialized in nums1 and nums2 are m and n respectively. 2. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. */ // time: 2018-12-21 package msa // standard merge process in merge sort // time complexity: O(n+m) // space complexity: O(1) func merge(nums1 []int, m int, nums2 []int, n int) { for i := n + m - 1; i >= n; i-- { nums1[i] = nums1[i-n] } var ( i = n // pointer for nums1 [n, n+m) j = 0 // pointer for nums2 [0, n) k = 0 // pointer for merged nums1 [0, n+m) ) for k < n+m { if i >= n+m { nums1[k] = nums2[j] k++ j++ } else if j >= n { break // nums1[k] = nums1[i] // k++ // i++ } else if nums1[i] < nums2[j] { nums1[k] = nums1[i] i++ k++ } else { //nums1[i] >= nums2[j] nums1[k] = nums2[j] k++ j++ } } } ================================================ FILE: solutions/0088_merge_sorted_array/msa_test.go ================================================ package msa import ( "reflect" "testing" ) func TestMerge(t *testing.T) { type arg struct { nums1 []int m int nums2 []int n int } testCases := []arg{ {nums1: []int{1, 2, 3, 7, 0, 0, 0}, m: 4, nums2: []int{2, 5, 6}, n: 3}, {nums1: []int{2, 5, 6, 0, 0, 0}, m: 3, nums2: []int{7, 8, 9}, n: 3}, } expected := [][]int{{1, 2, 2, 3, 5, 6, 7}, {2, 5, 6, 7, 8, 9}} for index, data := range testCases { if merge(data.nums1, data.m, data.nums2, data.n); !reflect.DeepEqual(expected[index], data.nums1) { t.Errorf("expected %v, got %v", expected[index], data.nums1) } } } ================================================ FILE: solutions/0092_reverse_linked_list_2/reverse_linked_list2.go ================================================ /* 92. Reverse Linked List II https://leetcode.com/problems/reverse-linked-list-ii/ Reverse a linked list from position m to n. Do it in one-pass. Note: 1 ≤ m ≤ n ≤ length of list. */ // time: 2019-01-04 package reverselinkedlist2 // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n-m) // space complexity: O(1) func reverseBetween(head *ListNode, m, n int) *ListNode { var ( dummy = &ListNode{} p = dummy s = p ) dummy.Next = head // 1 ≤ m ≤ n ≤ length of list. for s != nil && n > 0 { s = s.Next n-- } for s != nil && m > 1 { p = p.Next m-- } reverse(&p, &s) return dummy.Next } func reverse(p, s **ListNode) { var ( tmp *ListNode prev = (*p).Next tail = (*p).Next flag = (*s).Next ) (*p).Next = nil for prev != flag { tmp = (*p).Next (*p).Next = prev prev = prev.Next (*p).Next.Next = tmp } tail.Next = prev /* 1->2->3->4->5 1->3->2->4->5 1->4->3->2->5 1->5->4->3->2 */ } ================================================ FILE: solutions/0092_reverse_linked_list_2/reverse_linked_list2_test.go ================================================ package reverselinkedlist2 import ( "reflect" "testing" ) func createSingleList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } func TestReverseBetween(t *testing.T) { head := createSingleList([]int{1, 2, 3, 4, 5}) m := 2 n := 4 expected := createSingleList([]int{1, 4, 3, 2, 5}) if res := reverseBetween(head, m, n); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } ================================================ FILE: solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go ================================================ /* 94. Binary Tree Inorder Traversal source: https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively? */ package binarytreeinordertraversal // TreeNode binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func inorderTraversal(root *TreeNode) []int { res := make([]int, 0, 1) inorderTraversalHelp(root, &res) return res } func inorderTraversalHelp(root *TreeNode, res *[]int) { if root == nil { return } inorderTraversalHelp(root.Left, res) *res = append(*res, root.Val) inorderTraversalHelp(root.Right, res) } ================================================ FILE: solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal_test.go ================================================ package binarytreeinordertraversal import ( "reflect" "testing" ) func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestInorderTraversal(t *testing.T) { testData := [][]int{ {1, 2, 3}, } expectedData := [][]int{ {2, 1, 3}, } for index, data := range testData { if res := inorderTraversal(createBinaryTree(data)); !reflect.DeepEqual(res, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], res) } } } ================================================ FILE: solutions/0100_same_tree/same_tree.go ================================================ /* 100. Same Tree https://leetcode.com/problems/same-tree/ Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. */ package sametree // TreeNode binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func isSameTree(p *TreeNode, q *TreeNode) bool { if p == nil { return q == nil } if q == nil { return p == nil } if p.Val == q.Val { return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) } return false } ================================================ FILE: solutions/0100_same_tree/same_tree_test.go ================================================ package sametree import "testing" type arg struct { p []int q []int } func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestSameTree(t *testing.T) { testData := []arg{ {p: []int{1, 2, 3}, q: []int{1, 2, 3}}, {p: []int{1, 2, 3}, q: []int{1, 2}}, {p: []int{1, 2, 3}, q: []int{1, 2, 4}}, } expectedData := []bool{true, false, false} for index, data := range testData { if res := isSameTree(createBinaryTree(data.p), createBinaryTree(data.q)); res != expectedData[index] { t.Errorf("expected %t, got %t", expectedData[index], res) } } } ================================================ FILE: solutions/0101_symmetric_tree/symmetric_tree.go ================================================ /* 101. Symmetric Tree https://leetcode.com/problems/symmetric-tree/ Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). */ package symmetrictree // TreeNode binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func isSymmetric(root *TreeNode) bool { if root == nil { return true } return symmetric(root.Left, root.Right) } func symmetric(left *TreeNode, right *TreeNode) bool { if left == nil && right == nil { return true } if left == nil || right == nil { return false } return left.Val == right.Val && symmetric(left.Left, right.Right) && symmetric(left.Right, right.Left) } ================================================ FILE: solutions/0101_symmetric_tree/symmetric_tree_test.go ================================================ package symmetrictree import ( "testing" ) func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestIsSymmetric(t *testing.T) { testData := [][]int{ {1, 2, 2, 3, 4, 4, 3}, {1, 2, 2, 3, 3}, {}, } expectedData := []bool{true, false, true} for index, data := range testData { if res := isSymmetric(createBinaryTree(data)); res != expectedData[index] { t.Errorf("expected %t, got %t", expectedData[index], res) } } } ================================================ FILE: solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go ================================================ /* 102. Binary Tree Level Order Traversal https://leetcode.com/problems/binary-tree-level-order-traversal/ Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). */ // time: 2019-01-04 package btlot // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } type queueEle struct { Level int Ele *TreeNode } // bfs // time complexity: O(n), where n is number of tree nodes. // space complexity: O(n) func levelOrder(root *TreeNode) [][]int { if root == nil { return [][]int{} } var ( queue []queueEle res = make([][]int, 0) ) queue = append(queue, queueEle{Level: 0, Ele: root}) for len(queue) > 0 { node := queue[0].Ele level := queue[0].Level queue = queue[1:] if len(res) > level { res[level] = append(res[level], node.Val) } else { res = append(res, []int{node.Val}) } if node.Left != nil { queue = append(queue, queueEle{Level: level + 1, Ele: node.Left}) } if node.Right != nil { queue = append(queue, queueEle{Level: level + 1, Ele: node.Right}) } } return res } ================================================ FILE: solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal_test.go ================================================ package btlot import ( "reflect" "testing" ) func TestLevelOrder(t *testing.T) { testCases := []*TreeNode{ createBinaryTree([]int{1, 2, 3, 4, 5}), nil, } expected := [][][]int{ {{1}, {2, 3}, {4, 5}}, {}, } for index, root := range testCases { if res := levelOrder(root); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } ================================================ FILE: solutions/0104_maximun_depth_of_binary_tree/maxdobt.go ================================================ /* 104. Maximum Depth of Binary Tree https://leetcode.com/problems/maximum-depth-of-binary-tree/ Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. */ // time: 2019-01-06 package maxdobt // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // Recursive // time complexity: O(n), where n is the nodes number in the tree. // space complexity: O(h), where h is the height of the tree. func maxDepth(root *TreeNode) int { if root == nil { return 0 } left := maxDepth(root.Left) right := maxDepth(root.Right) var max int if left > right { max = left } else { max = right } return max + 1 } ================================================ FILE: solutions/0104_maximun_depth_of_binary_tree/maxdobt_test.go ================================================ package maxdobt import "testing" func TestMaxDepth(t *testing.T) { root := createBinaryTree([]int{1, 2, 3, 4, 5}) expected := 3 if res := maxDepth(root); res != expected { t.Errorf("expected %d, got %d", expected, res) } } func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := &TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return tree } ================================================ FILE: solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go ================================================ /* 107. Binary Tree Level Order Traversal II https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ 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). */ package binarytreelevelordertraversal2 // TreeNode binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func levelOrderBottom(root *TreeNode) [][]int { var record [][]int traversal(root, 0, &record) var reversed [][]int for i := len(record) - 1; i >= 0; i-- { reversed = append(reversed, record[i]) } return reversed } func traversal(root *TreeNode, index int, record *[][]int) { if root == nil { return } if len(*record) == index { *record = append(*record, make([]int, 0)) } (*record)[index] = append((*record)[index], root.Val) traversal(root.Left, index+1, record) traversal(root.Right, index+1, record) // (*record)[len(*record)-1-index] = append((*record)[len(*record)-1-index], root.Val) // 这个方法用java可以实现,go不行,猜测可能跟java的递归实现有关。 } ================================================ FILE: solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2_test.go ================================================ package binarytreelevelordertraversal2 import ( "reflect" "testing" ) func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestBinaryTreeLevelOrderTraversal2(t *testing.T) { testData := [][]int{ {3, 9, 20, 15, 17}, } expectedData := [][][]int{ { {15, 17}, {9, 20}, {3}, }, } for index, data := range testData { if res := levelOrderBottom(createBinaryTree(data)); !reflect.DeepEqual(res, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], res) } } } ================================================ FILE: solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go ================================================ /* 111. Minimum Depth of Binary Tree https://leetcode.com/problems/minimum-depth-of-binary-tree/ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. */ package minimumdepthofbinarytree import "leetcode/utils" // TreeNode binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func minDepth(root *TreeNode) int { if root == nil { return 0 } left := minDepth(root.Left) right := minDepth(root.Right) if left == 0 || right == 0 { return utils.CalcMaxInt(left, right) + 1 } return utils.CalcMinInt(left, right) + 1 } ================================================ FILE: solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree_test.go ================================================ package minimumdepthofbinarytree import "testing" func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestMinDepth(t *testing.T) { testData := [][]int{ {3, 9, 20, 15, 7}, } expectedData := []int{2} for index, data := range testData { if res := minDepth(createBinaryTree(data)); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0112_path_sum/path_sum.go ================================================ /* 112. Path Sum https://leetcode.com/problems/path-sum/ 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. Note: A leaf is a node with no children. */ package pathsum // TreeNode binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func hasPathSum(root *TreeNode, sum int) bool { if root == nil { return false } if root.Left == nil && root.Right == nil { return root.Val == sum } return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val) } ================================================ FILE: solutions/0112_path_sum/path_sum_test.go ================================================ package pathsum import ( "os" "testing" ) func createBinaryTree(nums []interface{}) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []interface{}, index int) *TreeNode { if !(index < len(nums)) || nums[index] == nil { return nil } tree := TreeNode{} if num, ok := nums[index].(int); ok { // type assertion tree.Val = num } tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } type arg struct { nums []interface{} sum int } func TestHasPathSum(t *testing.T) { testData := []arg{ {nums: []interface{}{5, 4, 8, 11, nil, 13, 4, 7, 2, nil, nil, nil, 1}, sum: 22}, {nums: []interface{}{}, sum: 0}, } expectedData := []bool{true, false} for index, data := range testData { if res := hasPathSum(createBinaryTree(data.nums), data.sum); res != expectedData[index] { t.Errorf("expected %t, got %t", expectedData[index], res) } } } func TestMain(m *testing.M) { os.Exit(m.Run()) } ================================================ FILE: solutions/0120_triangle/triangle.go ================================================ /* 120. Triangle https://leetcode.com/problems/triangle/ Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. */ package triangle import "leetcode/utils" // dfs /* func minimumTotal(triangle [][]int) int { if len(triangle) == 0 { return 0 } result := utils.MaxInt dfs(0, 0, 0, triangle, &result) return result } func dfs(x int, y int, sum int, triangle [][]int, result *int) { if len(triangle) == x { if sum < *result { *result = sum } return } sum += triangle[x][y] dfs(x+1, y, sum, triangle, result) dfs(x+1, y+1, sum, triangle, result) } */ // dynamic programming func minimumTotal(triangle [][]int) int { m := len(triangle) if m == 0 { return 0 } dp := make([][]int, m) dp[0] = append(dp[0], triangle[0][0]) for i := 1; i < m; i++ { for j, num := range triangle[i] { if j >= len(dp[i-1]) { dp[i] = append(dp[i], num+dp[i-1][j-1]) } else { if j-1 >= 0 && dp[i-1][j-1] < dp[i-1][j] { dp[i] = append(dp[i], num+dp[i-1][j-1]) } else { dp[i] = append(dp[i], num+dp[i-1][j]) } } } } var mininum = utils.MaxInt for _, num := range dp[m-1] { if num < mininum { mininum = num } } return mininum } ================================================ FILE: solutions/0120_triangle/triangle_test.go ================================================ package triangle import ( "testing" ) func TestTriangle(t *testing.T) { testData := [][][]int{ {{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}, {}, {{-1}, {2, 3}, {1, -1, -3}}, } expectedData := []int{11, 0, -1} for index, data := range testData { if mininum := minimumTotal(data); mininum != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], mininum) } } } ================================================ FILE: solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go ================================================ /* 121. Best Time to Buy and Sell Stock https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. */ // time: 2018-12-28 package maxprofit // dynamic programming // for every price, find the max profit, then record the current minimum price. // time complexity: O(n) // space complexity: O(1) func maxProfit(prices []int) int { n := len(prices) if 0 == n || 1 == n { return 0 } var ( res int minPrice = prices[0] ) for _, price := range prices { if price-minPrice > res { res = price - minPrice } if price < minPrice { minPrice = price } } return res } // brute force // time complexity: O(n^2) // space complexity: O(1) func maxProfit1(prices []int) int { n := len(prices) if 0 == n || 1 == n { return 0 } res := 0 for i := 1; i < n; i++ { for j := 0; j < i; j++ { if prices[i]-prices[j] > res { res = prices[i] - prices[j] } } } return res } ================================================ FILE: solutions/0121_best_time_to_buy_and_sell_stock/maxprofit_test.go ================================================ package maxprofit import "testing" func TestMaxProfit(t *testing.T) { testCases := [][]int{ {7, 1, 5, 3, 6, 4}, {5, 3, 2, 2, 5, 7, 9, 4}, {}, {3}, {5, 3, 2, 2, 5, 7, 9, 4, 5, 3, 2, 2, 5, 7, 9, 4}, {2, 4, 1, 11, 7}, } expected := []int{5, 7, 0, 0, 7, 10} for index, data := range testCases { if res := maxProfit(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } func TestMaxProfit1(t *testing.T) { testCases := [][]int{ {7, 1, 5, 3, 6, 4}, {5, 3, 2, 2, 5, 7, 9, 4}, {}, {3}, } expected := []int{5, 7, 0, 0} for index, data := range testCases { if res := maxProfit1(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go ================================================ /* 122. Best Time to Buy and Sell Stock II https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). */ // time: 2018-12-28 package maxprofit // greedy // time complexity: O(n) // space complexity: O(1) func maxProfit(prices []int) int { n := len(prices) if 0 == n || 1 == n { return 0 } var ( res int minPrice = prices[0] ) for i := 1; i < n; i++ { if prices[i] < prices[i-1] { res += prices[i-1] - minPrice minPrice = prices[i] } if i == n-1 { res += prices[i] - minPrice } } return res } ================================================ FILE: solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit_test.go ================================================ package maxprofit import "testing" func TestMaxProfit(t *testing.T) { testCases := [][]int{ {7, 1, 5, 3, 6, 4}, {1, 2, 3, 4, 5}, {7, 6, 4, 3, 1}, {}, {1}, } expected := []int{7, 4, 0, 0, 0} for index, data := range testCases { if res := maxProfit(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0125_valid_palindrome/valid_palindrome.go ================================================ /* 125. Valid Palindrome https://leetcode.com/problems/valid-palindrome/ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. */ // time: 2018-12-26 package validpalindrome // double index // time complexity: O(n) // space complexity: O(n) func isPalindrome(s string) bool { chars := make([]uint8, 0) for i := 0; i < len(s); i++ { if s[i] >= 65 && s[i] <= 90 { chars = append(chars, s[i]) } if s[i] >= 97 && s[i] <= 122 { chars = append(chars, s[i]-32) } if s[i] >= 48 && s[i] <= 57 { chars = append(chars, s[i]) } } var ( l int r = len(chars) - 1 ) for r >= l { if chars[r] != chars[l] { return false } r-- l++ } return true } ================================================ FILE: solutions/0125_valid_palindrome/valid_palindrome_test.go ================================================ package validpalindrome import "testing" func TestIsPalindrome(t *testing.T) { testCases := []string{ "A man, a plan, a canal: Panama", "race a car", "0P", "", } expected := []bool{true, false, false, true} for index, data := range testCases { if res := isPalindrome(data); res != expected[index] { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/0136_single_number/single_number.go ================================================ /* 136. Single Number https://leetcode.com/problems/single-number/ Given a non-empty array of integers, every element appears twice except for one. Find that single one. */ // time: 2019-02-01 package sn // time complexity: O(n) // space complexity: O(n) func singleNumber(nums []int) int { record := make(map[int]int) for _, num := range nums { if _, ok := record[num]; ok { delete(record, num) } else { record[num] = 1 } } var res int for key := range record { res = key } return res } // time complexity: O(n) // space complexity: O(1) func singleNumber1(nums []int) int { res := 0 for _, num := range nums { res ^= num } return res } ================================================ FILE: solutions/0136_single_number/single_number_test.go ================================================ package sn import "testing" func TestSingleNumber(t *testing.T) { testCases := [][]int{ {2, 2, 1}, {4, 1, 2, 1, 2}, } expected := []int{1, 4} testFuncs := []func([]int) int{ singleNumber, singleNumber1, } for _, testFunc := range testFuncs { for index, nums := range testCases { if res := testFunc(nums); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } } ================================================ FILE: solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go ================================================ /* 144. Binary Tree Preorder Traversal https://leetcode.com/problems/binary-tree-preorder-traversal/ Given a binary tree, return the preorder traversal of its nodes' values. */ // time: 2019-01-06 package btpot // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // recursive // time complexity: O(n), where n is nodes numbers in the tree. // space complexity: O(h), where h is the height of the tree. func preorderTraversal(root *TreeNode) []int { if root == nil { return []int{} } if root.Left == nil && root.Right == nil { return []int{root.Val} } left := preorderTraversal(root.Left) right := preorderTraversal(root.Right) res := []int{root.Val} res = append(res, left...) res = append(res, right...) return res } // iterative // time complexity: O(n), where n is nodes numbers in the tree. // space complexity: O(h), where h is the height of the tree. func preorderTraversal1(root *TreeNode) []int { if root == nil { return []int{} } var stack []*TreeNode var res []int stack = append(stack, root) for len(stack) > 0 { node := stack[len(stack)-1] stack = stack[:len(stack)-1] res = append(res, node.Val) if node.Right != nil { stack = append(stack, node.Right) } if node.Left != nil { stack = append(stack, node.Left) } } return res } ================================================ FILE: solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal_test.go ================================================ package btpot import ( "reflect" "testing" ) func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestPreorderTraversal(t *testing.T) { testCases := []*TreeNode{ nil, createBinaryTree([]int{1, 2, 3, 4, 5, 6, 7, 8}), } expected := [][]int{ {}, {1, 2, 4, 8, 5, 3, 6, 7}, } testFuncs := []func(node *TreeNode) []int{ preorderTraversal, preorderTraversal1, } for _, testFunc := range testFuncs { for index, root := range testCases { if res := testFunc(root); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } } ================================================ FILE: solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go ================================================ /* 150. Evaluate Reverse Polish Notation https://leetcode.com/problems/evaluate-reverse-polish-notation/ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. */ // time: 2019-01-07 package evaluatereversepolishnotation import "strconv" // stack // time complexity: O(n) // space complexity: O(n) func evalRPN(tokens []string) int { stack := make([]int, len(tokens)) top := -1 for i := 0; i < len(tokens); i++ { switch ch := tokens[i]; ch { case "+": stack[top-1] += stack[top] top-- case "-": stack[top-1] -= stack[top] top-- case "*": stack[top-1] *= stack[top] top-- case "/": stack[top-1] /= stack[top] top-- default: top++ stack[top], _ = strconv.Atoi(ch) } } return stack[0] } ================================================ FILE: solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation_test.go ================================================ package evaluatereversepolishnotation import "testing" func TestEvalRPN(t *testing.T) { testCases := [][]string{ {"2", "1", "+", "3", "*"}, {"4", "13", "5", "/", "+"}, {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}, {"4", "3", "-"}, } expected := []int{9, 6, 22, 1} for index, tokens := range testCases { if res := evalRPN(tokens); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go ================================================ /* 153. Find Minimum in Rotated Sorted Array https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. You may assume no duplicate exists in the array. */ // time: 2019-01-07 package fmirsa // binary search // time complexity: O( log n) // space complexity: O(1) func findMin(nums []int) int { var ( low int high = len(nums) - 1 mid int ) for low < high { mid = low + (high-low)>>1 if nums[high] < nums[mid] { low = mid + 1 } else { high = mid } } return nums[low] } ================================================ FILE: solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa_test.go ================================================ package fmirsa import "testing" func TestFindMin(t *testing.T) { nums := []int{3, 4, 5, 1, 2} expected := 1 if res := findMin(nums); res != expected { t.Errorf("expected %d, got %d", expected, res) } } ================================================ FILE: solutions/0155_min_stack/min_stack.go ================================================ /* 155. Min Stack https://leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. */ // time: 2019-01-10 package minstack // MinStack a stack that supports push, pop, top, and retrieving the minimum element in constant time. type MinStack struct { data []int } // Constructor initialize your data structure here. func Constructor() MinStack { return MinStack{} } // Push element x onto stack. func (s *MinStack) Push(x int) { s.data = append(s.data, x) } // Pop Removes the element on top of the stack. func (s *MinStack) Pop() { if !s.IsEmpty() { s.data = s.data[:s.GetSize()-1] } } // Top Get the top element. func (s *MinStack) Top() int { //if s.IsEmpty(){ // return 0 //} // stack must have element. return s.data[s.GetSize()-1] } // GetMin retrieving the minimum element in constant time. // time complexity: O(n) func (s *MinStack) GetMin() int { //if s.IsEmpty() { // return 0 //} // stack must have element. stackSize := s.GetSize() ret := s.data[stackSize-1] for i := stackSize - 2; i >= 0; i-- { if s.data[i] < ret { ret = s.data[i] } } return ret } // GetSize get size of the stack. func (s MinStack) GetSize() int { return len(s.data) } func (s MinStack) IsEmpty() bool { return s.GetSize() == 0 } ================================================ FILE: solutions/0155_min_stack/min_stack_test.go ================================================ package minstack import "testing" func TestMinStack(t *testing.T) { obj := Constructor() obj.Push(-2) obj.Push(0) obj.Push(-3) if res := obj.GetMin(); res != -3 { t.Errorf("expected %d, got %d", -3, res) } obj.Pop() if res := obj.Top(); res != 0 { t.Errorf("expected %d, got %d", 0, res) } if res := obj.GetMin(); res != -2 { t.Errorf("expected %d, got %d", -2, res) } } ================================================ FILE: solutions/0165_compare_version_numbers/compare_version_numbers.go ================================================ /* 165. Compare Version Numbers https://leetcode.com/problems/compare-version-numbers/ Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. Note: Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. Version strings do not start or end with dots, and they will not be two consecutive dots. */ // time: 2019-01-07 package compareversionnumbers import ( "strconv" "strings" ) // time complexity: O( max n, m ) // space complexity: O(n+m) func compareVersion(version1 string, version2 string) int { var ( v1 = strings.Split(version1, ".") v2 = strings.Split(version2, ".") ) for i := 0; i < len(v1) || i < len(v2); i++ { var v1N, v2N int if i < len(v1) { v1N, _ = strconv.Atoi(v1[i]) } if i < len(v2) { v2N, _ = strconv.Atoi(v2[i]) } if v1N > v2N { return 1 } else if v1N < v2N { return -1 } } return 0 } ================================================ FILE: solutions/0165_compare_version_numbers/compare_version_numbers_test.go ================================================ package compareversionnumbers import "testing" func TestCompareVersion(t *testing.T) { type arg struct { version1 string version2 string } testCases := []arg{ {version1: "0.1", version2: "1.1"}, {version1: "1.0.1", version2: "1"}, {version1: "1.01", version2: "1.001"}, } expected := []int{-1, 1, 0} for index, data := range testCases { if res := compareVersion(data.version1, data.version2); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0167_two_sum2/two_sum2.go ================================================ /* 167. Two Sum II - Input array is sorted https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 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. 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. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. */ package twosum2 func twoSum2(numbers []int, target int) []int { n := len(numbers) var ( l = 0 r = n - 1 ) for l < r { if numbers[l]+numbers[r] == target { return []int{l + 1, r + 1} } else if numbers[l]+numbers[r] < target { l++ } else { r-- } } panic("The input has no solution.") } ================================================ FILE: solutions/0167_two_sum2/two_sum2_test.go ================================================ package twosum2 import ( "reflect" "testing" ) type arg struct { numbers []int target int } func TestTwoSum2(t *testing.T) { testData := []arg{ { numbers: []int{2, 7, 11, 15}, target: 9, }, } expectedData := [][]int{ {1, 2}, } for index, data := range testData { if res := twoSum2(data.numbers, data.target); !reflect.DeepEqual(res, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], res) } } defer func() { if err := recover(); err == nil { t.Errorf("there should throw a panic") } }() twoSum2([]int{2, 7, 11, 15}, 90) } ================================================ FILE: solutions/0179_largest_number/ln.go ================================================ /* 179. Largest Number https://leetcode.com/problems/largest-number/ Given a list of non negative integers, arrange them such that they form the largest number. Note: The result may be very large, so you need to return a string instead of an integer. */ // time: 2019-01-14 package ln import ( "sort" "strconv" "strings" ) type sliceString []string // Len is the number of elements in the collection. func (s sliceString) Len() int { return len(s) } // Swap swaps the elements with indexes i and j. func (s sliceString) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // Less reports whether the element with // index i should sort before the element with index j. func (s sliceString) Less(i, j int) bool { return (s[i] + s[j]) > (s[j] + s[i]) } // time complexity: O(n log n), dominated by the complexity of sort. // space complexity: O(n) func largestNumber(nums []int) string { numsString := make([]string, 0) for _, num := range nums { numsString = append(numsString, strconv.Itoa(num)) } sort.Sort(sliceString(numsString)) numStr := strings.Join(numsString, "") if strings.HasPrefix(numStr, "0") { return "0" } return numStr } ================================================ FILE: solutions/0179_largest_number/ln_test.go ================================================ package ln import "testing" func TestLargestNumber(t *testing.T) { testCases := [][]int{ {10, 2}, {3, 30, 34, 5, 9}, {0}, } expected := []string{ "210", "9534330", "0", } for index, nums := range testCases { if res := largestNumber(nums); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } ================================================ FILE: solutions/0198_house_robber/house_robber.go ================================================ /* 198. House Robber https://leetcode.com/problems/house-robber/ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. */ package houserobber import "leetcode/utils" /* func rob(nums []int) int { return tryRob(nums, 0) } func tryRob(nums []int, index int) int { if index >= len(nums) { return 0 } var res int for i := index; i < len(nums); i++ { res, _ = utils.CalcMaxInt(res, nums[i]+tryRob(nums, i+2)) } return res } */ // memory search /* func rob(nums []int) int { memo := make([]int, len(nums)) for i := 0; i < len(nums); i++ { memo[i] = -1 } return tryRob(nums, 0, memo) } func tryRob(nums []int, index int, memo []int) int { if index >= len(nums) { return 0 } if memo[index] != -1 { return memo[index] } var res int for i := index; i < len(nums); i++ { res, _ = utils.CalcMaxInt(res, nums[i]+tryRob(nums, i+2, memo)) } memo[index] = res return res }*/ // dynamic programming func rob(nums []int) int { n := len(nums) if n == 0 { return 0 } memo := make([]int, n) for i := 0; i < n; i++ { memo[i] = -1 } memo[n-1] = nums[n-1] for i := n - 2; i >= 0; i-- { for j := i; j < n; j++ { if j+2 < n { memo[i] = utils.CalcMaxInt(memo[i], nums[j]+memo[j+2]) } else { memo[i] = utils.CalcMaxInt(memo[i], nums[j]) } } } return memo[0] } ================================================ FILE: solutions/0198_house_robber/house_robber_test.go ================================================ package houserobber import "testing" func TestHouseRobber(t *testing.T) { testData := [][]int{ {1, 2, 3, 1}, {9, 1, 293, 5986, 81, 384}, {1, 2}, {}, } expectedData := []int{4, 6379, 2, 0} for index, data := range testData { if res := rob(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0200_number_of_island/number_of_island.go ================================================ /* 200. Number of Islands https://leetcode.com/problems/number-of-islands/ Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. */ // time: 2019-01-07 package noi var ( d = [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} m, n int visited [][]bool ) // flood-fill // time complexity: O(n*m) // space complexity: O(n*m) func numIslands(grid [][]byte) int { m = len(grid) if m <= 0 { return 0 } n = len(grid[0]) visited = make([][]bool, m) for i := 0; i < m; i++ { visited[i] = make([]bool, n) } var res int for i := 0; i < m; i++ { for j := 0; j < n; j++ { if grid[i][j] == '1' && !visited[i][j] { res++ dfs(grid, i, j) } } } return res } // 从grid[x][y]的位置开始,进行floodfill。 func dfs(grid [][]byte, x, y int) { visited[x][y] = true for i := 0; i < len(d); i++ { newX := x + d[i][0] newY := y + d[i][1] if inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1' { dfs(grid, newX, newY) } } } func inArea(x, y int) bool { return x >= 0 && x < m && y >= 0 && y < n } ================================================ FILE: solutions/0200_number_of_island/number_of_island_test.go ================================================ package noi import "testing" func TestNumIslands(t *testing.T) { grids := [][][]byte{ { {'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}, }, {}, } expected := []int{3, 0} for index, grid := range grids { if res := numIslands(grid); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go ================================================ /* 203. Remove Linked List Elements https://leetcode.com/problems/remove-linked-list-elements/ Remove all elements from a linked list of integers that have value val. */ // time: 2019-01-07 package rlle // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n) // space complexity: O(1) func removeElements(head *ListNode, val int) *ListNode { dummyHead := &ListNode{} dummyHead.Next = head cur := dummyHead for cur.Next != nil { if val == cur.Next.Val { cur.Next = cur.Next.Next } else { cur = cur.Next } } return dummyHead.Next } // recursive // time complexity: O(n) // space complexity: O(n) func removeElements1(head *ListNode, val int) *ListNode { if head == nil { return head } head.Next = removeElements1(head.Next, val) if head.Val == val { return head.Next } return head } ================================================ FILE: solutions/0203_remove_linked_list_elements/remove_linked_list_elements_test.go ================================================ package rlle import ( "reflect" "testing" ) func TestRemoveElements(t *testing.T) { head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6}) val := 6 expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) if res := removeElements(head, val); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } func TestRemoveElements1(t *testing.T) { head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6}) val := 6 expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) if res := removeElements1(head, val); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } func createSinglyLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } ================================================ FILE: solutions/0206_reverse_linked_list/reverse_linked_list.go ================================================ /* 206. Reverse Linked List https://leetcode.com/problems/reverse-linked-list/ Reverse a singly linked list. */ // time: 2019-01-07 package rll // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // recursive // time complexity: O(n) // space complexity: O(n) func reverseList(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } tail := reverseList(head.Next) head.Next.Next = head head.Next = nil return tail } // iterative // time complexity: O(n) // space complexity: O(1) func reverseList1(head *ListNode) *ListNode { var ( pre *ListNode cur = head ) for cur != nil { next := cur.Next cur.Next = pre pre = cur cur = next } return pre } ================================================ FILE: solutions/0206_reverse_linked_list/reverse_linked_list_test.go ================================================ package rll import ( "reflect" "testing" ) func TestReverseList(t *testing.T) { head := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) expected := createSinglyLinkedList([]int{5, 4, 3, 2, 1}) if res := reverseList(head); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } func TestReverseList1(t *testing.T) { head := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) expected := createSinglyLinkedList([]int{5, 4, 3, 2, 1}) if res := reverseList1(head); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } func createSinglyLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } ================================================ FILE: solutions/0208_implement_trie_prefix_tree/impltrie.go ================================================ /* 208. Implement Trie (Prefix Tree) https://leetcode.com/problems/implement-trie-prefix-tree/ Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings. */ // time: 2019-01-31 package impltree type node struct { isWord bool next map[byte]*node } // Trie prefix tree type Trie struct { root *node size int } // Constructor initialize data structure here. func Constructor() Trie { return Trie{root: &node{next: make(map[byte]*node)}} } // Insert inserts a word into the trie. func (trie *Trie) Insert(word string) { cur := trie.root for i := 0; i < len(word); i++ { if _, ok := cur.next[word[i]]; !ok { cur.next[word[i]] = &node{next: make(map[byte]*node)} } cur = cur.next[word[i]] } if !cur.isWord { cur.isWord = true trie.size++ } } // Search returns if the word is the trie. func (trie *Trie) Search(word string) bool { cur := trie.root for i := 0; i < len(word); i++ { if _, ok := cur.next[word[i]]; !ok { return false } cur = cur.next[word[i]] } return cur.isWord } // StartsWith returns if there is any word in the trie that starts with the given prefix. func (trie *Trie) StartsWith(prefix string) bool { cur := trie.root for i := 0; i < len(prefix); i++ { if _, ok := cur.next[prefix[i]]; !ok { return false } cur = cur.next[prefix[i]] } return true } ================================================ FILE: solutions/0208_implement_trie_prefix_tree/impltrie_test.go ================================================ package impltree import "testing" func TestImplTrie(t *testing.T) { trie := Constructor() trie.Insert("apple") for i, j := range map[string]bool{"apple": true, "app": false, "hello": false} { if res := trie.Search(i); res != j { t.Errorf("expected %t, got %t", j, res) } } for i, j := range map[string]bool{"app": true, "as": false} { if res := trie.StartsWith(i); res != j { t.Errorf("expected %t, got %t", j, res) } } trie.Insert("app") if res := trie.Search("app"); res != true { t.Errorf("expected %t, got %t", true, res) } } ================================================ FILE: solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go ================================================ /* 209. Minimum Size Subarray Sum https://leetcode.com/problems/minimum-size-subarray-sum/ 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. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint. Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). */ package minimumsizesubarraysum func minSubArrayLen(s int, nums []int) int { var ( l = 0 r = -1 res = len(nums) + 1 sum = 0 ) for l < len(nums) { if sum < s && r+1 < len(nums) { r++ sum += nums[r] } else { sum -= nums[l] l++ } if sum >= s && res > r-l+1 { res = r - l + 1 } } if res == len(nums)+1 { return 0 } return res } ================================================ FILE: solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum_test.go ================================================ package minimumsizesubarraysum import "testing" func TestMinSubArrayLen(t *testing.T) { type arg struct { s int nums []int } testData := []arg{ { s: 7, nums: []int{2, 3, 1, 2, 4, 3}, }, { s: 7, nums: []int{7, 4, 3, 2}, }, { s: 66, nums: []int{7, 4, 3, 2}, }, } expectedData := []int{2, 1, 0} for index, data := range testData { if res := minSubArrayLen(data.s, data.nums); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0211_add_and_search_word/add_and_search_word.go ================================================ /* 211. Add and Search Word - Data structure design https://leetcode.com/problems/add-and-search-word-data-structure-design/ */ // time: 2019-01-31 package aasw type node struct { isWord bool next map[byte]*node } // WordDictionary supports two operations(addWord, search) type WordDictionary struct { root *node } // Constructor initialize data structure here. func Constructor() WordDictionary { return WordDictionary{&node{next: make(map[byte]*node)}} } // AddWord adds a word into the trie. func (trie *WordDictionary) AddWord(word string) { cur := trie.root for i := 0; i < len(word); i++ { if _, ok := cur.next[word[i]]; !ok { cur.next[word[i]] = &node{next: make(map[byte]*node)} } cur = cur.next[word[i]] } if !cur.isWord { cur.isWord = true } } // Search returns if the word is in the trie. // a word could contain the dot character '.' to represent any ont letter. func (trie *WordDictionary) Search(word string) bool { return match(trie.root, word, 0) } func match(n *node, word string, index int) bool { if index == len(word) { return n.isWord } if word[index] != '.' { if _, ok := n.next[word[index]]; !ok { return false } return match(n.next[word[index]], word, index+1) } else { for _, nextNode := range n.next { if match(nextNode, word, index+1) { return true } } return false } } ================================================ FILE: solutions/0211_add_and_search_word/add_and_search_word_test.go ================================================ package aasw import "testing" func TestAddAndSearchWord(t *testing.T) { obj := Constructor() for _, word := range []string{"bad", "dad", "mad"} { obj.AddWord(word) } for i, j := range map[string]bool{"pad": false, "bad": true, ".ad": true, "b..": true, "b..d": false} { if res := obj.Search(i); res != j { t.Errorf("expected %t, got %t", j, res) } } } ================================================ FILE: solutions/0215_kth_largest_element_in_an_array/kthleiaa.go ================================================ /* 215. Kth Largest Element in an Array https://leetcode.com/problems/kth-largest-element-in-an-array/ Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. You may assume k is always valid, 1 ≤ k ≤ array's length. */ // time: 2018-12-22 package kthleiaa // heap sort // time complexity: O(k * logn) // sapce complexity: O(1) func findKthLargest(nums []int, k int) int { // heapify for i := (len(nums) - 1) / 2; i >= 0; i-- { siftDown(nums, len(nums), i) } for i := len(nums) - 1; i >= len(nums)-k; i-- { nums[i], nums[0] = nums[0], nums[i] siftDown(nums, i, 0) } return nums[len(nums)-k] } func siftDown(nums []int, n int, i int) { for 2*i+1 < n { j := 2*i + 1 if j+1 < n && nums[j+1] > nums[j] { j++ } if nums[i] >= nums[j] { break } nums[j], nums[i] = nums[i], nums[j] i = j } } ================================================ FILE: solutions/0215_kth_largest_element_in_an_array/kthleiaa_test.go ================================================ package kthleiaa import "testing" func TestFindKthLargest(t *testing.T) { type arg struct { nums []int k int } testCases := []arg{ {nums: []int{3, 2, 1, 5, 6, 4}, k: 2}, {nums: []int{3, 2, 3, 1, 2, 4, 5, 5, 6}, k: 4}, } expected := []int{5, 4} for index, data := range testCases { if res := findKthLargest(data.nums, data.k); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0217_contains_duplicate/contains_duplicate.go ================================================ /* 217. Contains Duplicate https://leetcode.com/problems/contains-duplicate/ 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. */ // time: 2019-01-07 package cd // using HashTable // time complexity: O(n) // space complexity: O(n) func containsDuplicate(nums []int) bool { record := make(map[int]int) for _, num := range nums { if _, ok := record[num]; !ok { record[num] = 1 } else { return true } } return false } ================================================ FILE: solutions/0217_contains_duplicate/contains_duplicate_test.go ================================================ package cd import "testing" func TestContainsDuplicate(t *testing.T) { testCases := [][]int{ {1, 2, 3, 1}, {1, 2, 3, 4}, } expected := []bool{true, false} for index, nums := range testCases { if res := containsDuplicate(nums); res != expected[index] { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/0219_contains_duplicate_2/contains_duplicate_2.go ================================================ /* 219. Contains Duplicate II https://leetcode.com/problems/contains-duplicate-ii/ 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. */ // time: 2019-01-07 package cond // using hash table // time complexity: O(n) // space complexity: O(n) func containsNearbyDuplicate(nums []int, k int) bool { record := make(map[int]int, len(nums)) for i, v := range nums { if j, ok := record[v]; ok { if i-j <= k { return true } } record[v] = i } return false } ================================================ FILE: solutions/0219_contains_duplicate_2/contains_duplicate_2_test.go ================================================ package cond import "testing" func TestContainsNearbyDuplicate(t *testing.T) { testCases := [][]int{ {1, 2, 3, 1}, {1, 0, 1, 1}, {1, 2, 3, 1, 2, 3}, } ks := []int{3, 1, 2} expected := []bool{true, true, false} for index, nums := range testCases { if res := containsNearbyDuplicate(nums, ks[index]); res != expected[index] { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/0226_invert_binary_tree/invert_binary_tree.go ================================================ /* 226. Invert Binary Tree https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. */ package invertbinarytree // TreeNode binary tree node type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // Recursion // Time complexity: O(n), where n is the node's number of the tree. // Space complexity: O(h), where h is the height of the tree. func invertTree(root *TreeNode) *TreeNode { if root == nil { return nil } root.Right, root.Left = root.Left, root.Right invertTree(root.Left) invertTree(root.Right) return root } ================================================ FILE: solutions/0226_invert_binary_tree/invert_binary_tree_test.go ================================================ package invertbinarytree import ( "reflect" "testing" ) func createBinaryTree(nums []interface{}) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []interface{}, index int) *TreeNode { if !(index < len(nums)) || nums[index] == nil { return nil } tree := TreeNode{} if num, ok := nums[index].(int); ok { // type assertion tree.Val = num } tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func levelOrderTraversal(root *TreeNode) []interface{} { res := make([]interface{}, 0) queue := make([]*TreeNode, 0) queue = append(queue, root) for len(queue) > 0 { node := queue[0] queue = queue[1:] res = append(res, node.Val) if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } } return res } func TestInvertTree(t *testing.T) { testData := [][]interface{}{ {4, 2, 7, 1, 3, 6, 9}, } expectedData := [][]interface{}{ {4, 7, 2, 9, 6, 3, 1}, } for index, data := range testData { tree := createBinaryTree(data) if res := levelOrderTraversal(invertTree(tree)); !reflect.DeepEqual(res, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], res) } } } ================================================ FILE: solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go ================================================ /* 235. Lowest Common Ancestor of a Binary Search Tree https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Note: All of the nodes' values will be unique. p and q are different and both values will exist in the BST. */ // time: 2019-01-07 package lcaoabst // TreeNode Definition for TreeNode. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // recursive // time complexity: O(log n), where n is the nodes number of the tree. // space complexity: O(h), where h is the height of the tree. func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if root == nil { return root } if root.Val > p.Val && root.Val > q.Val { return lowestCommonAncestor(root.Left, p, q) } if root.Val < p.Val && root.Val < q.Val { return lowestCommonAncestor(root.Right, p, q) } return root } ================================================ FILE: solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst_test.go ================================================ package lcaoabst import ( "testing" ) func TestLowestCommonAncestor(t *testing.T) { type arg struct { root, p, q *TreeNode } testCases := []arg{ {root: createBinaryTree([]int{6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5}), p: &TreeNode{Val: 3}, q: &TreeNode{Val: 5}}, {p: &TreeNode{Val: 2}, q: &TreeNode{Val: 8}}, } expected := []*TreeNode{{Val: 4}, nil} for index, data := range testCases { if res := lowestCommonAncestor(data.root, data.p, data.q); res != nil && res.Val != expected[index].Val { t.Errorf("expected %v, got %v", expected[index], res) } else if res == nil && res != expected[index] { t.Errorf("expected %v, got %v", expected[index], res) } } } func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } root := &TreeNode{Val: nums[index]} root.Left = performCreate(nums, 2*index+1) root.Right = performCreate(nums, 2*index+2) return root } ================================================ FILE: solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go ================================================ /* 236. Lowest Common Ancestor of a Binary Tree https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ */ // 2019-02-21 package lca // TreeNode Definition for TreeNode. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if root == nil || root == p || root == q { return root } left := lowestCommonAncestor(root.Left, p, q) right := lowestCommonAncestor(root.Right, p, q) if left != nil && right != nil { return root } if left != nil { return left } return right } ================================================ FILE: solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca_test.go ================================================ package lca import "testing" func TestLCA(t *testing.T) { type arg struct { root, p, q *TreeNode } tree := createBinaryTree([]int{6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5}) testCases := []arg{ {root: tree, p: tree.Left.Right.Left, q: tree.Left.Right.Right}, {p: &TreeNode{Val: 2}, q: &TreeNode{Val: 8}}, } expected := []*TreeNode{{Val: 4}, nil} for index, data := range testCases { if res := lowestCommonAncestor(data.root, data.p, data.q); res != nil && res.Val != expected[index].Val { t.Errorf("expected %v, got %v", expected[index], res) } else if res == nil && res != expected[index] { t.Errorf("expected %v, got %v", expected[index], res) } } } func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } root := &TreeNode{Val: nums[index]} root.Left = performCreate(nums, 2*index+1) root.Right = performCreate(nums, 2*index+2) return root } ================================================ FILE: solutions/0237_delete_node_in_a_linked_list/dniall.go ================================================ /* 237. Delete Node in a Linked List https://leetcode.com/problems/delete-node-in-a-linked-list/ Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Note: The linked list will have at least two elements. All of the nodes' values will be unique. The given node will not be the tail and it will always be a valid node of the linked list. Do not return anything from your function. */ // time: 2019-01-07 package dniall // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(1) // space complexity: O(1) func deleteNode(node *ListNode) { // The linked list will have at least two elements. // All the nodes' values will be unique. // The given node will not be the tail and it will always be a valid node of the linked list. node.Val = node.Next.Val node.Next = node.Next.Next } ================================================ FILE: solutions/0237_delete_node_in_a_linked_list/dniall_test.go ================================================ package dniall import ( "reflect" "testing" ) func createSinglyLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } func TestDeleteNode(t *testing.T) { root := createSinglyLinkedList([]int{4, 5, 1, 9}) node := root.Next expected := createSinglyLinkedList([]int{4, 1, 9}) if deleteNode(node); !reflect.DeepEqual(expected, root) { t.Errorf("expected %v, got %v", expected, root) } } ================================================ FILE: solutions/0257_binary_tree_paths/binary_tree_paths.go ================================================ /* 257. Binary Tree Paths https://leetcode.com/problems/binary-tree-paths/ Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. */ // time: 2019-01-07 package btp import "strconv" // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // recursive // time complexity: O(n), where n is the nodes number in the tree. // space complexity: O(h), where h is the height of the tree. func binaryTreePaths(root *TreeNode) []string { if root == nil { return []string{} } var res []string if root.Left == nil && root.Right == nil { return append(res, strconv.Itoa(root.Val)) } if root.Left != nil { for _, i := range binaryTreePaths(root.Left) { res = append(res, strconv.Itoa(root.Val)+"->"+i) } } if root.Right != nil { for _, i := range binaryTreePaths(root.Right) { res = append(res, strconv.Itoa(root.Val)+"->"+i) } } return res } ================================================ FILE: solutions/0257_binary_tree_paths/binary_tree_paths_test.go ================================================ package btp import ( "reflect" "testing" ) func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestBinaryTreePaths(t *testing.T) { testCases := []*TreeNode{ createBinaryTree([]int{1, 2, 3, 4, 5}), nil, } expected := [][]string{ {"1->2->4", "1->2->5", "1->3"}, {}, } for index, root := range testCases { if res := binaryTreePaths(root); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0258_add_digits/add_digits.go ================================================ /* 258. Add Digits https://leetcode.com/problems/add-digits/ Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. */ // time: 2019-01-07 package ad // time complexity: O( log num ) // space complexity: O(1) func addDigits(num int) int { // num is a non-negative integer for num > 9 { num = performAdd(num) } return num } func performAdd(num int) (res int) { for num > 0 { res += num % 10 num /= 10 } return } // time complexity: O(1) // space complexity: O(1) func addDigits1(num int) int { /* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 1 2 3 4 5 6 7 8 9 10/1 20 21 22 23 24 25 26 27 28 29 2 3 4 5 6 7 8 9 10/1 11/2 */ return (num-1)%9 + 1 } ================================================ FILE: solutions/0258_add_digits/add_digits_test.go ================================================ package ad import "testing" func TestAddDigits(t *testing.T) { num := 38 expected := 2 testFuncs := []func(int) int{ addDigits, addDigits1, } for _, function := range testFuncs { if res := function(num); res != expected { t.Errorf("expected %d, got %d", expected, res) } } } ================================================ FILE: solutions/0283_move_zeroes/move_zeroes.go ================================================ /* 283. Move Zeroes https://leetcode.com/problems/move-zeroes/ 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. */ package movezeroes // Time complexity: O(n) // Space complexity: O(1) func moveZeroes(nums []int) { var k int for i := range nums { if nums[i] != 0 { if k != i { nums[i], nums[k] = nums[k], nums[i] } k++ } } } ================================================ FILE: solutions/0283_move_zeroes/move_zeroes2.go ================================================ /* 283. Move Zeroes https://leetcode.com/problems/move-zeroes/ 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. */ package movezeroes // Time complexity: O(n) // Space complexity: O(1) func moveZeroes2(nums []int) { var k int for i := range nums { if nums[i] != 0 { if k != i { nums[k] = nums[i] } k++ } } for i := k; i < len(nums); i++ { nums[i] = 0 } } ================================================ FILE: solutions/0283_move_zeroes/move_zeroes2_test.go ================================================ package movezeroes import ( "reflect" "testing" ) func TestMoveZeroes2(t *testing.T) { testData := [][]int{ {0, 1, 0, 3, 12}, } expectedData := [][]int{ {1, 3, 12, 0, 0}, } for index, data := range testData { if moveZeroes2(data); !reflect.DeepEqual(data, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], data) } } } ================================================ FILE: solutions/0283_move_zeroes/move_zeroes_test.go ================================================ package movezeroes import ( "reflect" "testing" ) func TestMoveZeroes(t *testing.T) { testData := [][]int{ {0, 1, 0, 3, 12}, } expectedData := [][]int{ {1, 3, 12, 0, 0}, } for index, data := range testData { if moveZeroes(data); !reflect.DeepEqual(data, expectedData[index]) { t.Errorf("expected %v, got %v", expectedData[index], data) } } } ================================================ FILE: solutions/0300_longest_increasing_subsequence/lis.go ================================================ /* 300. Longest Increasing Subsequence https://leetcode.com/problems/longest-increasing-subsequence/ Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may be more than one LIS combination, it is only necessary for you to return the length. Your algorithm should run in O(n2) complexity. Follow up: Could you improve it to O(n log n) time complexity? */ package lis import "leetcode/utils" // Dynamic Programming // TIme complexity: O(n^2) // Space Complexity: O(n) func lengthOfLIS(nums []int) int { n := len(nums) if n == 0 { return 0 } memo := make([]int, n) for i := 0; i < n; i++ { memo[i] = 1 } for i := 1; i < n; i++ { for j := 0; j < i; j++ { if nums[j] < nums[i] { memo[i] = utils.CalcMaxInt(memo[i], 1+memo[j]) } } } return utils.CalcMaxInt(memo...) } ================================================ FILE: solutions/0300_longest_increasing_subsequence/lis_test.go ================================================ package lis import ( "os" "testing" ) func TestLIS(t *testing.T) { testData := [][]int{ {10, 9, 2, 5, 3, 7, 101, 18}, {}, } expectedData := []int{4, 0} for index, data := range testData { if res := lengthOfLIS(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } func TestMain(m *testing.M) { os.Exit(m.Run()) } ================================================ FILE: solutions/0303_range_sum_query/rsqim.go ================================================ /* 303. Range Sum Query - Immutable https://leetcode.com/problems/range-sum-query-immutable/ Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. */ // time: 2018-12-28 package rsqim // NumArray store sum of nums sub-list. type NumArray struct { sum []int } // Constructor make NumArray instance. func Constructor(nums []int) NumArray { nA := NumArray{sum: make([]int, 1)} for _, num := range nums { nA.sum = append(nA.sum, nA.sum[len(nA.sum)-1]+num) } return nA } // SumRange find the sum of the elements between indices i and j(i <= j), inclusive. func (na *NumArray) SumRange(i int, j int) int { j++ return na.sum[j] - na.sum[i] } ================================================ FILE: solutions/0303_range_sum_query/rsqim_test.go ================================================ package rsqim import "testing" func TestSumRange(t *testing.T) { nums := []int{-2, 0, 3, -5, 2, -1} ranges := [][]int{ {0, 2}, {2, 5}, {0, 5}, } expected := []int{1, -1, -3} obj := Constructor(nums) for index, section := range ranges { if res := obj.SumRange(section[0], section[1]); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut.go ================================================ /* 307. Range Sum Query - Mutable https://leetcode.com/problems/range-sum-query-mutable/ Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Note: The array is only modifiable by the update function. You may assume the number of calls to update and sumRange function is distributed evenly. */ // time: 2019-01-29 // 线段树时间复杂度为:O(log n) package rsqm // NumArray 线段树 type NumArray struct { segmentTree []int data []int } // Constructor 线段树生成函数 func Constructor(nums []int) NumArray { na := NumArray{segmentTree: make([]int, len(nums)*4), data: nums[:]} na.buildSegmentTree(0, 0, len(na.data)-1) return na } func (na *NumArray) buildSegmentTree(treeIndex, left, right int) { // 线段树处理的数据不能为空。 //if right < left { // return //} if left == right { na.segmentTree[treeIndex] = na.data[left] return } mid := left + (right-left)>>1 leftTreeIndex := 2*treeIndex + 1 rightTreeIndex := 2*treeIndex + 2 na.buildSegmentTree(leftTreeIndex, left, mid) na.buildSegmentTree(rightTreeIndex, mid+1, right) na.segmentTree[treeIndex] = na.segmentTree[leftTreeIndex] + na.segmentTree[rightTreeIndex] } // Update 线段树更新操作。 func (na *NumArray) Update(i int, val int) { na.setter(0, 0, len(na.data)-1, i, val) } func (na *NumArray) setter(treeIndex, left, right, index, val int) { if left == right { na.segmentTree[treeIndex] = val return } mid := left + (right-left)>>1 leftTreeIndex := 2*treeIndex + 1 rightTreeIndex := 2*treeIndex + 2 if index >= mid+1 { na.setter(rightTreeIndex, mid+1, right, index, val) } else { na.setter(leftTreeIndex, left, mid, index, val) } na.segmentTree[treeIndex] = na.segmentTree[leftTreeIndex] + na.segmentTree[rightTreeIndex] } // SumRange 线段树查询 func (na *NumArray) SumRange(i int, j int) int { return na.query(0, 0, len(na.data)-1, i, j) } func (na *NumArray) query(treeIndex, left, right, queryL, queryR int) int { if left == queryL && right == queryR { return na.segmentTree[treeIndex] } mid := left + (right-left)>>1 leftTreeIndex := 2*treeIndex + 1 rightTreeIndex := 2*treeIndex + 2 if queryL >= mid+1 { return na.query(rightTreeIndex, mid+1, right, queryL, queryR) } else if queryR <= mid { return na.query(leftTreeIndex, left, mid, queryL, queryR) } else { return na.query(leftTreeIndex, left, mid, queryL, mid) + na.query(rightTreeIndex, mid+1, right, mid+1, queryR) } } ================================================ FILE: solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut_test.go ================================================ package rsqm import "testing" func TestNumArray(t *testing.T) { nums := []int{1, 2, 3, 6, 7, 8, 9, 3, 4, 2, 5} na := Constructor(nums) if res := na.SumRange(4, 9); res != 33 { t.Errorf("expected %d, got %d", 43, res) } na.Update(6, 10) if res := na.SumRange(4, 9); res != 34 { t.Errorf("expected %d, got %d", 44, res) } } ================================================ FILE: solutions/0328_odd_even_linked_list/odd_even_linked_list.go ================================================ /* 328. Odd Even Linked List https://leetcode.com/problems/odd-even-linked-list/ Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ... */ // time: 2019-01-07 package oddevenlinkedlist // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // time complexity: O(n) // space complexity: O(1) func oddEvenList(head *ListNode) *ListNode { if head == nil { return head } var ( odd = head evenHead = head.Next even = evenHead ) for even != nil && even.Next != nil { odd.Next = even.Next odd = odd.Next even.Next = odd.Next even = even.Next } odd.Next = evenHead return head } ================================================ FILE: solutions/0328_odd_even_linked_list/odd_even_linked_list_test.go ================================================ package oddevenlinkedlist import ( "reflect" "testing" ) func createSinglyLinkedList(nums []int) *ListNode { head := &ListNode{} cur := head for _, num := range nums { cur.Next = &ListNode{Val: num} cur = cur.Next } return head.Next } func TestOddEvenList(t *testing.T) { testCases := []*ListNode{ createSinglyLinkedList([]int{2, 1, 3, 5, 6, 4, 7}), nil, } expected := []*ListNode{ createSinglyLinkedList([]int{2, 3, 6, 7, 1, 5, 4}), nil, } for index, head := range testCases { if res := oddEvenList(head); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0343_integer_break/integer_break.go ================================================ /* 343. Integer Break https://leetcode.com/problems/integer-break Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. Example 1: Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. Note: You may assume that n is not less than 2 and not larger than 58. */ package integerbreak import "leetcode/utils" // recursion /* func integerBreak(n int) int { if n == 1 { return 1 } res := utils.MinInt for i := 1; i < n; i++ { res, _ = utils.CalcMaxInt(res, i*(n-i), i*integerBreak(n-i)) } return res } */ // memory search /* func integerBreak(n int) int { memo := make([]int, n+1) for i := 0; i <= n; i++ { memo[i] = -1 } return breakInt(n, memo) } func breakInt(n int, memo []int) int { if n == 1 { return 1 } if memo[n] != -1 { return memo[n] } res := utils.MinInt for i := 1; i < n; i++ { res, _ = utils.CalcMaxInt(res, i*(n-i), i*breakInt(n-i, memo)) } memo[n] = res return res } */ // dynamic programming // Time complexity: O(n^2) // Space complexity: O(n+1) func integerBreak(n int) int { // memo[i]表示将数字i分割(至少分割成两部分)后得到的最大乘积. memo := make([]int, n+1) memo[1] = 1 for i := 2; i <= n; i++ { // 求解memo[i] for j := 1; j <= i-1; j++ { memo[i] = utils.CalcMaxInt(memo[i], j*(i-j), j*memo[i-j]) } } return memo[n] } ================================================ FILE: solutions/0343_integer_break/integer_break_test.go ================================================ package integerbreak import "testing" func TestIntegerBreak(t *testing.T) { testData := []int{2, 10, 34} expectedData := []int{1, 36, 236196} for index, data := range testData { if res := integerBreak(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0344_reverse_string/reverse_string.go ================================================ /* 344. Reverse String https://leetcode.com/problems/reverse-string/ Write a function that takes a string as input and returns the string reversed. */ // time: 2018-12-26 package reversestring // double index // time complexity: O(n) // space complexity: O(1) func reverseString(s string) string { var ( l int r = len(s) - 1 ) for r > l { charL := s[l] charR := s[r] s = s[:r] + string(charL) + s[r+1:] s = s[:l] + string(charR) + s[l+1:] r-- l++ } return s } // double index // time complexity: O(n) // space complexity: O(n) func reverseString1(s string) string { sLen := len(s) bytes := []byte(s) for i := 0; i < sLen/2; i++ { bytes[i], bytes[sLen-i-1] = bytes[sLen-i-1], bytes[i] } return string(bytes) } ================================================ FILE: solutions/0344_reverse_string/reverse_string_test.go ================================================ package reversestring import "testing" func TestReverseString(t *testing.T) { testCases := []string{ "hello", "A man, a plan, a canal: Panama", "", "ab", } expected := []string{ "olleh", "amanaP :lanac a ,nalp a ,nam A", "", "ba", } for index, data := range testCases { if res := reverseString(data); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } func TestReverseString1(t *testing.T) { testCases := []string{ "hello", "A man, a plan, a canal: Panama", "", "ab", } expected := []string{ "olleh", "amanaP :lanac a ,nalp a ,nam A", "", "ba", } for index, data := range testCases { if res := reverseString1(data); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } ================================================ FILE: solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go ================================================ /* 345. Reverse Vowels of a String https://leetcode.com/problems/reverse-vowels-of-a-string/ Write a function that takes a string as input and reverse only the vowels of a string. */ // time: 2018-12-26 package reversevowels // time complexity: O(n) // space complexity: O(1) func reverseVowels(s string) string { var ( l int r = len(s) - 1 ) for r > l { for r >= 0 && !isVowel(s[r]) { r-- } for l < len(s) && !isVowel(s[l]) { l++ } if l >= r { break } charL := s[l] charR := s[r] s = s[:r] + string(charL) + s[r+1:] s = s[:l] + string(charR) + s[l+1:] r-- l++ } return s } // time complexity: O(n) // space complexity: O(n) func reverseVowels1(s string) string { bytes := []byte(s) var ( l int r = len(bytes) - 1 ) for r > l { for r >= 0 && !isVowel(s[r]) { r-- } for l < len(bytes) && !isVowel(s[l]) { l++ } if l >= r { break } bytes[l], bytes[r] = bytes[r], bytes[l] l++ r-- } return string(bytes) } func isVowel(char byte) bool { vowels := [...]byte{'a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U'} for _, k := range vowels { if char == k { return true } } return false } ================================================ FILE: solutions/0345_reverse_vowels_of_a_string/reverse_vowels_test.go ================================================ package reversevowels import "testing" func TestReverseVowels(t *testing.T) { testCases := []string{ "hello", "leetcode", "aA", "a.b,.", } expected := []string{ "holle", "leotcede", "Aa", "a.b,.", } for index, data := range testCases { if res := reverseVowels(data); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } func TestReverseVowels1(t *testing.T) { testCases := []string{ "hello", "leetcode", "aA", "a.b,.", } expected := []string{ "holle", "leotcede", "Aa", "a.b,.", } for index, data := range testCases { if res := reverseVowels1(data); res != expected[index] { t.Errorf("expected %s, got %s", expected[index], res) } } } ================================================ FILE: solutions/0347_top_k_frequent_elements/topkfe.go ================================================ /* 347. Top K Frequent Elements https://leetcode.com/problems/top-k-frequent-elements/ Given a non-empty array of integers, return the k most frequent elements. Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. */ // time: 2019-01-08 package topkfe import "container/heap" // using priority // time complexity: O(n log n) // space complexity: O(n) func topKFrequent(nums []int, k int) []int { count := make(map[int]int) for _, num := range nums { if _, ok := count[num]; !ok { count[num] = 1 } else { count[num]++ } } nums_ := make(Nums, 0) for num, cnt := range count { nums_ = append(nums_, Num{Val: num, Count: cnt}) } heap.Init(&nums_) var res []int for i := 0; i < k; i++ { num := heap.Pop(&nums_).(Num) res = append(res, num.Val) } return res } // Num stores its value and frequency as Count. type Num struct { Val int Count int } // Nums struct for impl Interface type Nums []Num // Len sort Interface func (n Nums) Len() int { return len(n) } // Swap sort Interface func (n Nums) Swap(i, j int) { n[i], n[j] = n[j], n[i] } // Less sort Interface func (n Nums) Less(i, j int) bool { return n[i].Count >= n[j].Count } // Push heap Interface func (n *Nums) Push(num interface{}) { m := num.(Num) *n = append(*n, m) } // Pop heap Interface func (n *Nums) Pop() interface{} { res := (*n)[len(*n)-1] *n = (*n)[:len(*n)-1] return res } ================================================ FILE: solutions/0347_top_k_frequent_elements/topkfe_test.go ================================================ package topkfe import ( "reflect" "testing" ) func TestTopKFrequent(t *testing.T) { nums := []int{1, 1, 1, 2, 2, 3} k := 2 expected := []int{1, 2} if res := topKFrequent(nums, k); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } ================================================ FILE: solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays.go ================================================ /* 349. Intersection of Two Arrays https://leetcode.com/problems/intersection-of-two-arrays Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must be unique. The result can be in any order. */ package intersectionof2arrays import "leetcode/utils" func intersection(nums1 []int, nums2 []int) []int { set1 := utils.NewSet() for _, num := range nums1 { set1.Add(num) } set2 := utils.NewSet() for _, num := range nums2 { set2.Add(num) } var res []int for item := range set1 { if set2.Contains(item) { if value, ok := item.(int); ok { res = append(res, value) } } } return res } ================================================ FILE: solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays_test.go ================================================ package intersectionof2arrays import ( "reflect" "testing" ) func TestIntersection(t *testing.T) { nums1 := []int{1, 2, 2, 1} nums2 := []int{2, 2} expectedData := []int{2} if res := intersection(nums1, nums2); !reflect.DeepEqual(res, expectedData) { t.Errorf("expected %v, got %v", expectedData, res) } } ================================================ FILE: solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go ================================================ /* 350. Intersection of Two Arrays II https://leetcode.com/problems/intersection-of-two-arrays-ii/ */ package intersectionof2arrays2 func intersect(nums1 []int, nums2 []int) []int { record := make(map[int]int) res := make([]int, 0) for _, num := range nums1 { if _, ok := record[num]; !ok { record[num] = 1 } else { record[num]++ } } for _, num := range nums2 { if count, ok := record[num]; ok && count > 0 { res = append(res, num) record[num]-- } } return res } ================================================ FILE: solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2_test.go ================================================ package intersectionof2arrays2 import ( "reflect" "testing" ) func TestInteract(t *testing.T) { nums1 := []int{1, 2, 2, 1} nums2 := []int{2, 2} expectedData := []int{2, 2} if res := intersect(nums1, nums2); !reflect.DeepEqual(res, expectedData) { t.Errorf("expected %v, got %v", expectedData, res) } } ================================================ FILE: solutions/0376_wiggle_subsequence/wiggle_subsequence.go ================================================ /* 376. Wiggle Subsequence https://leetcode.com/problems/wiggle-subsequence/ A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero. Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. Example 1: Input: [1,7,4,9,2,5] Output: 6 Explanation: The entire sequence is a wiggle sequence. Example 2: Input: [1,17,5,10,13,15,10,5,16,8] Output: 7 Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. Example 3: Input: [1,2,3,4,5,6,7,8,9] Output: 2 Follow up: Can you do it in O(n) time? */ package wigglesubsequence import "leetcode/utils" /* * 用up[i]和down[i]分别记录到第i个元素为止以上升沿和下降沿结束的最长“摆动” * 序列长度,遍历数组,如果nums[i]>nums[i-1],表明第i-1到第i个元素是上升的, * 因此up[i]只需在down[i-1]的基础上加1即可,而down[i]保持down[i-1]不变; * 如果nums[i] O(n) func wiggleMaxLength(nums []int) int { n := len(nums) if n == 1 || n == 0 { return n } up := make([]int, n) for i := 0; i < n; i++ { up[i] = 1 } down := make([]int, n) copy(down, up) for i := 1; i < n; i++ { for j := 0; j < i; j++ { if nums[i] > nums[j] { up[i] = utils.CalcMaxInt(up[i], down[j]+1) } else if nums[i] < nums[j] { down[i] = utils.CalcMaxInt(down[i], up[j]+1) } } } return utils.CalcMaxInt(up[n-1], down[n-1]) } ================================================ FILE: solutions/0376_wiggle_subsequence/wiggle_subsequence_test.go ================================================ package wigglesubsequence import "testing" func TestWiggleSubsequence(t *testing.T) { testData := [][]int{ {1, 17, 5, 10, 13, 15, 10, 5, 16, 8}, {1, 7, 4, 9, 2, 5}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {}, {2}, {3, 4}, {3, 3, 3, 2, 5}, { 372, 492, 288, 399, 81, 2, 320, 94, 416, 469, 427, 117, 265, 357, 399, 456, 496, 337, 355, 219, 475, 295, 457, 350, 490, 470, 281, 127, 131, 36, 430, 412, 442, 174, 128, 253, 1, 56, 306, 295, 340, 73, 253, 130, 259, 223, 14, 79, 409, 384, 209, 151, 317, 441, 156, 275, 140, 224, 128, 250, 290, 191, 161, 472, 477, 125, 470, 230, 321, 5, 311, 23, 27, 248, 138, 284, 215, 356, 320, 194, 434, 136, 221, 273, 450, 440, 28, 179, 36, 386, 482, 203, 24, 8, 391, 21, 500, 484, 135, 348, 292, 396, 145, 443, 406, 61, 212, 480, 455, 78, 309, 318, 84, 474, 209, 225, 177, 356, 227, 263, 181, 476, 478, 151, 494, 395, 23, 114, 395, 429, 450, 247, 245, 150, 354, 230, 100, 172, 454, 155, 189, 33, 290, 187, 443, 123, 59, 358, 241, 141, 39, 196, 491, 381, 157, 157, 134, 431, 295, 20, 123, 118, 207, 199, 317, 188, 267, 335, 315, 308, 115, 321, 56, 52, 253, 492, 97, 374, 398, 272, 74, 206, 109, 172, 471, 55, 452, 452, 329, 367, 372, 252, 99, 62, 122, 287, 320, 325, 307, 481, 316, 378, 87, 97, 457, 21, 312, 249, 354, 286, 196, 43, 170, 500, 265, 253, 19, 480, 438, 113, 473, 247, 257, 33, 395, 456, 246, 310, 469, 408, 112, 385, 53, 449, 117, 122, 210, 286, 149, 20, 364, 372, 71, 26, 155, 292, 16, 72, 384, 160, 79, 241, 346, 230, 15, 427, 96, 95, 59, 151, 325, 490, 223, 131, 81, 294, 18, 70, 171, 339, 14, 40, 463, 421, 355, 123, 408, 357, 202, 235, 390, 344, 198, 98, 361, 434, 174, 216, 197, 274, 231, 85, 494, 57, 136, 258, 134, 441, 477, 456, 318, 155, 138, 461, 65, 426, 162, 90, 342, 284, 374, 204, 464, 9, 280, 391, 491, 231, 298, 284, 82, 417, 355, 356, 207, 367, 262, 244, 283, 489, 477, 143, 495, 472, 372, 447, 322, 399, 239, 450, 168, 202, 89, 333, 276, 199, 416, 490, 494, 488, 137, 327, 113, 189, 430, 320, 197, 120, 71, 262, 31, 295, 218, 74, 238, 169, 489, 308, 300, 260, 397, 308, 328, 267, 419, 84, 357, 486, 289, 312, 230, 64, 468, 227, 268, 28, 243, 267, 254, 153, 407, 399, 346, 385, 77, 297, 273, 484, 366, 482, 491, 368, 221, 423, 107, 272, 98, 309, 426, 181, 320, 77, 185, 382, 478, 398, 476, 22, 328, 450, 299, 211, 285, 62, 344, 484, 395, 466, 291, 487, 301, 407, 28, 295, 36, 429, 99, 462, 240, 124, 261, 387, 30, 362, 161, 156, 184, 188, 99, 377, 392, 442, 300, 98, 285, 312, 312, 365, 415, 367, 105, 81, 378, 413, 43, 326, 490, 320, 266, 390, 53, 327, 75, 332, 454, 29, 370, 392, 360, 1, 335, 355, 344, 120, 417, 455, 93, 60, 256, 451, 188, 161, 388, 338, 238, 26, 275, 340, 109, 185, }, } expectedData := []int{ 7, 6, 2, 0, 1, 2, 3, 334, } for index, data := range testData { if res := wiggleMaxLength(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0392_is_subsequence/is_subsequence.go ================================================ /* 392. Is Subsequence https://leetcode.com/problems/is-subsequence/ Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). 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). Example 1: s = "abc", t = "ahbgdc" Return true. Example 2: s = "axc", t = "ahbgdc" Return false. Follow up: If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? Credits: Special thanks to @pbrother for adding this problem and creating all test cases. */ package issubsequence // greedy // Time complexity: O(n), where n is min( len(s), len(t) ) // Space complexity: O(1) func isSubsequence(s string, t string) bool { var si, ti int for si < len(s) && ti < len(t) { if s[si] == t[ti] { si++ ti++ } else { ti++ } } return si == len(s) } ================================================ FILE: solutions/0392_is_subsequence/is_subsequence_test.go ================================================ package issubsequence import "testing" type args struct { s string t string } func TestAssignCookies(t *testing.T) { testData := []args{ { s: "abc", t: "ahbgdc", }, { s: "acb", t: "ahbgdc", }, } expectedData := []bool{true, false} for index, data := range testData { if res := isSubsequence(data.s, data.t); res != expectedData[index] { t.Errorf("expected %t, got %t", expectedData[index], res) } } } ================================================ FILE: solutions/0404_sum_of_left_leaves/sum_of_left_leaves.go ================================================ /* 404. Sum of Left Leaves https://leetcode.com/problems/sum-of-left-leaves/ Find the sum of all left leaves in a given binary tree. */ // time: 2019-01-07 package soll // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // time complexity: O(n), where n is nodes number in the tree. // space complexity: O(h), where h is height of the tree. func sumOfLeftLeaves(root *TreeNode) int { return performSum(root, false) } func performSum(root *TreeNode, isLeft bool) int { if root == nil { return 0 } if root.Left == nil && root.Right == nil && isLeft { return root.Val } return performSum(root.Left, true) + performSum(root.Right, false) } ================================================ FILE: solutions/0404_sum_of_left_leaves/sum_of_left_leaves_test.go ================================================ package soll import "testing" func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestSumOfLeftLeaves(t *testing.T) { root := createBinaryTree([]int{3, 9, 20, 15, 7, 2}) expected := 17 if res := sumOfLeftLeaves(root); res != expected { t.Errorf("expected %d, got %d", expected, res) } } ================================================ FILE: solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum.go ================================================ /* 416. Partition Equal Subset Sum https://leetcode.com/problems/partition-equal-subset-sum/ Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: 1. Each of the array element will not exceed 100. 2. The array size will not exceed 200. */ package partitionequalsubsetsum /* 此问题可以使用0-1背包问题的思路求解 c是数组和的一半。 状态定义:F(n c) 状态转移方程:F(n c) = max( F(n-1, c) , n + F(n-1, c-n) ) */ func canPartition(nums []int) bool { var sum int for _, num := range nums { sum += num } if sum%2 != 0 { return false } c := sum / 2 n := len(nums) memo := make([]bool, c+1) for i := 0; i <= c; i++ { memo[i] = nums[0] == i } for i := 0; i < n; i++ { for j := c; j >= nums[i]; j-- { memo[j] = memo[j] || memo[j-nums[i]] } } return memo[c] } ================================================ FILE: solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum_test.go ================================================ package partitionequalsubsetsum import "testing" func TestPartitionEqualSubsetSum(t *testing.T) { testData := [][]int{ {1, 5, 11, 5}, {1, 2, 3, 5}, } expectedData := []bool{true, false} for index, data := range testData { if res := canPartition(data); res != expectedData[index] { t.Errorf("expected %t, got %t", expectedData[index], res) } } } ================================================ FILE: solutions/0435_non_overlapping_intervals/dp_solution.go ================================================ /* 435. Non-overlapping Intervals https://leetcode.com/problems/non-overlapping-intervals/ Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note: 1. You may assume the interval's end point is always bigger than its start point. 2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. */ package nonoverlappingintervals import ( "leetcode/utils" "sort" ) func eraseOverlapIntervalsDp(intervals []Interval) int { n := len(intervals) if n == 0 { return 0 } sort.Sort(IntervalSliceCompareWithStart(intervals)) // memo[i]表示使用intervals[0...i]的区间能构成的最长不重叠区间序列 memo := make([]int, n) for i := 0; i < n; i++ { memo[i] = 1 } for i := 1; i < n; i++ { // memo[i] for j := 0; j < i; j++ { if intervals[i].Start >= intervals[j].End { memo[i] = utils.CalcMaxInt(memo[i], 1+memo[j]) } } } var res int for i := 0; i < n; i++ { res = utils.CalcMaxInt(res, memo[i]) } return n - res } ================================================ FILE: solutions/0435_non_overlapping_intervals/greedy_solution.go ================================================ /* 435. Non-overlapping Intervals https://leetcode.com/problems/non-overlapping-intervals/ Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note: 1. You may assume the interval's end point is always bigger than its start point. 2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. */ package nonoverlappingintervals import "sort" func eraseOverlapIntervalsGreedy(intervals []Interval) int { n := len(intervals) if n == 0 { return 0 } sort.Sort(IntervalSliceCompareWithEnd(intervals)) var ( res = 1 pre = 0 ) for i := 1; i < n; i++ { if intervals[i].Start >= intervals[pre].End { res++ pre = i } } return n - res } ================================================ FILE: solutions/0435_non_overlapping_intervals/interval.go ================================================ package nonoverlappingintervals // Interval Definition for an interval. type Interval struct { Start int End int } // IntervalSliceCompareWithStart slice of Interval sort with start type IntervalSliceCompareWithStart []Interval // Len is the number of elements in the collection. func (i IntervalSliceCompareWithStart) Len() int { return len(i) } // Less compare Interval with start func (i IntervalSliceCompareWithStart) Less(j, k int) bool { if i[j].Start != i[k].Start { return i[j].Start < i[k].Start } return i[j].End < i[k].End } func (i IntervalSliceCompareWithStart) Swap(j, k int) { i[j], i[k] = i[k], i[j] } // IntervalSliceCompareWithEnd slice of Interval sort with end type IntervalSliceCompareWithEnd []Interval // Len is the number of elements in the collection. func (i IntervalSliceCompareWithEnd) Len() int { return len(i) } // Less compare Interval with end func (i IntervalSliceCompareWithEnd) Less(j, k int) bool { if i[j].End != i[k].End { return i[j].End < i[k].End } return i[j].Start < i[k].Start } func (i IntervalSliceCompareWithEnd) Swap(j, k int) { i[j], i[k] = i[k], i[j] } ================================================ FILE: solutions/0435_non_overlapping_intervals/solution_test.go ================================================ package nonoverlappingintervals import "testing" func TestEraseOverlapIntervals(t *testing.T) { testData := [][]Interval{ { Interval{Start: 1, End: 2}, Interval{Start: 1, End: 2}, Interval{Start: 1, End: 2}, }, { Interval{Start: 1, End: 2}, Interval{Start: 2, End: 3}, }, { Interval{Start: 1, End: 2}, Interval{Start: 2, End: 3}, Interval{Start: 3, End: 4}, Interval{Start: 1, End: 3}, }, } expectedData := []int{2, 0, 1} testFuncs := []func([]Interval) int{ eraseOverlapIntervalsGreedy, eraseOverlapIntervalsDp, } for index, data := range testData { for _, testFunc := range testFuncs { if res := testFunc(data); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } } ================================================ FILE: solutions/0437_path_sum_3/path_sum_3.go ================================================ /* 437. Path Sum III https://leetcode.com/problems/path-sum-iii/ You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. */ // 2019-01-08 package ps3 // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // recursive // time complexity: O(n), where n is the nodes number of the tree. // space complexity: O(h), where h is the height of the tree. func pathSum(root *TreeNode, sum int) int { if nil == root { return 0 } return findPath(root, sum) + pathSum(root.Left, sum) + pathSum(root.Right, sum) } func findPath(node *TreeNode, val int) int { if node == nil { return 0 } res := 0 if val == node.Val { res += 1 } res += findPath(node.Left, val-node.Val) res += findPath(node.Right, val-node.Val) return res } ================================================ FILE: solutions/0437_path_sum_3/path_sum_3_test.go ================================================ package ps3 import "testing" func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestPathSum(t *testing.T) { root := createBinaryTree([]int{10, 5, -3, 3, 2, 9, 11, 3, -2, 3, 1}) sum := 8 expected := 3 if res := pathSum(root, sum); res != expected { t.Errorf("expected %d, got %d", expected, res) } } ================================================ FILE: solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string.go ================================================ /* 438. Find All Anagrams in a String Source: https://leetcode.com/problems/find-all-anagrams-in-a-string/submissions/ Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". Time: 2018-12-17 */ package allanagramsinastring // Sliding Window // Time complexity: O(len(p) + len(s)) = O(n) // Space complexity: O(1) func findAnagrams(s string, p string) []int { var ( lenS = len(s) lenP = len(p) res = []int{} freqP = make([]int, 26) freqS = make([]int, 26) left int right = -1 // Sliding window: s[left, right] ) if lenS < lenP { return res } for i := 0; i < lenP; i++ { freqP[p[i]-'a']++ } for right+1 < lenS { right++ freqS[s[right]-'a']++ if right-left+1 > lenP { freqS[s[left]-'a']-- left++ } if right-left+1 == lenP && isSame(freqP, freqS) { res = append(res, left) } } return res } func isSame(p []int, q []int) bool { for i := 0; i < 26; i++ { if p[i] != q[i] { return false } } return true } ================================================ FILE: solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string_test.go ================================================ package allanagramsinastring import ( "reflect" "testing" ) func TestFindAnagrams(t *testing.T) { type arg struct { s string p string } cases := []arg{ { s: "cbaebabacd", p: "abc", }, { s: "abab", p: "ab", }, { p: "abab", s: "ab", }, } expected := [][]int{ {0, 6}, {0, 1, 2}, {}, } for index, args := range cases { if res := findAnagrams(args.s, args.p); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0447_number_of_boomerangs/number_of_boomerangs.go ================================================ /* 447. Number of Boomerangs https://leetcode.com/problems/number-of-boomerangs/ Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive). */ package numberofboomerangs import ( "math" ) // Time complexity: O(n^2) // Space complexity: O(n) func numberOfBoomerangs(points [][]int) int { var ( res int n = len(points) ) for i := 0; i < n; i++ { record := make(map[int]int) for j := 0; j < n; j++ { if j != i { dis := dis(points[i], points[j]) record[dis]++ } } for _, j := range record { res += j * (j - 1) } } return res } func dis(point1 []int, point2 []int) int { return int(math.Pow(float64(point1[0]-point2[0]), float64(2)) + math.Pow(float64(point1[1]-point2[1]), float64(2))) } ================================================ FILE: solutions/0447_number_of_boomerangs/number_of_boomerangs_test.go ================================================ package numberofboomerangs import "testing" func TestNumberOfBoomerangs(t *testing.T) { testData := [][]int{ {489, 238}, {323, 460}, {853, 965}, {327, 426}, {264, 871}, {580, 947}, {362, 275}, {241, 772}, {967, 240}, {68, 847}, {825, 703}, {922, 898}, {769, 217}, {23, 160}, {472, 802}, {755, 313}, {40, 78}, {125, 246}, {396, 452}, {672, 660}, {323, 253}, {607, 37}, {880, 201}, {161, 847}, {441, 229}, {46, 266}, {284, 320}, {516, 53}, {889, 539}, {565, 713}, {341, 320}, {26, 381}, {751, 504}, {979, 147}, {956, 652}, {807, 632}, {257, 767}, {669, 489}, {968, 831}, {336, 409}, {60, 734}, {27, 697}, {54, 543}, {750, 944}, {82, 668}, {657, 423}, {988, 36}, {156, 91}, {540, 136}, {238, 496}, {140, 398}, {128, 397}, {165, 150}, {238, 133}, {981, 926}, {894, 393}, {660, 921}, {90, 66}, {464, 193}, {10, 898}, {861, 20}, {321, 201}, {408, 829}, {293, 948}, {965, 531}, {796, 457}, {929, 277}, {206, 446}, {427, 444}, {931, 760}, {370, 825}, {153, 30}, {98, 244}, {449, 914}, {789, 811}, {812, 650}, {831, 485}, {203, 239}, {315, 496}, {539, 632}, {380, 336}, {442, 661}, {613, 648}, {108, 392}, {93, 391}, {152, 815}, {217, 305}, {198, 667}, {901, 647}, {934, 690}, {458, 746}, {692, 642}, {584, 896}, {233, 251}, {744, 773}, {235, 124}, {109, 677}, {786, 74}, {326, 246}, {466, 771}, {989, 618}, {586, 558}, {923, 136}, {226, 177}, {783, 160}, {867, 594}, {258, 912}, {236, 842}, {808, 469}, {445, 552}, {242, 681}, {29, 703}, {358, 167}, {777, 36}, {765, 595}, {807, 754}, {213, 746}, {313, 489}, {882, 539}, {666, 18}, {51, 885}, {612, 309}, {149, 200}, {504, 957}, {669, 949}, {862, 264}, {630, 891}, {319, 341}, {410, 449}, {377, 175}, {44, 537}, {929, 610}, {635, 242}, {99, 869}, {133, 117}, {887, 184}, {354, 851}, {846, 504}, {51, 350}, {813, 73}, {651, 675}, {337, 634}, {918, 656}, {975, 328}, {105, 704}, {503, 502}, {241, 785}, {112, 876}, {27, 211}, {98, 513}, {680, 985}, {697, 386}, {189, 895}, {890, 240}, {245, 56}, {313, 897}, {83, 2}, {531, 2}, {659, 858}, {682, 116}, {562, 538}, {618, 804}, {323, 730}, {32, 702}, {293, 482}, {215, 325}, {468, 265}, {64, 657}, {160, 306}, {249, 406}, {362, 915}, {655, 446}, {917, 538}, {800, 576}, {396, 482}, {45, 310}, {20, 15}, {466, 343}, {98, 851}, {46, 743}, {333, 261}, {421, 801}, {878, 485}, {810, 39}, {791, 412}, {797, 154}, {327, 452}, {600, 244}, {342, 400}, {173, 90}, {234, 570}, {400, 255}, {585, 867}, {950, 683}, {718, 996}, {779, 51}, {610, 200}, {205, 488}, {685, 367}, {879, 476}, {779, 676}, {982, 458}, {128, 934}, {703, 822}, {686, 228}, {912, 921}, {798, 313}, {176, 735}, {180, 478}, {771, 898}, {475, 550}, {301, 437}, {750, 506}, {277, 787}, {226, 157}, {615, 5}, {833, 598}, {816, 314}, {532, 519}, {136, 219}, {99, 49}, {492, 249}, {362, 20}, {984, 894}, {498, 755}, {144, 325}, {657, 445}, {762, 407}, {304, 392}, {546, 530}, {549, 162}, {887, 734}, {760, 703}, {48, 644}, {574, 537}, {215, 673}, {938, 707}, {922, 652}, {727, 259}, {546, 226}, {14, 42}, {551, 24}, {487, 666}, {783, 143}, {58, 330}, {673, 959}, {492, 913}, {693, 604}, {616, 94}, {248, 191}, {631, 816}, {216, 569}, {523, 491}, {573, 603}, {750, 119}, {181, 116}, {513, 84}, {140, 0}, {750, 924}, {496, 160}, {254, 521}, {119, 98}, {434, 165}, {702, 51}, {259, 302}, {594, 242}, {118, 810}, {163, 994}, {653, 736}, {597, 403}, {207, 778}, {520, 720}, {862, 12}, {72, 965}, {936, 568}, {125, 542}, {442, 597}, {640, 876}, {762, 694}, {279, 373}, {997, 225}, {967, 467}, {388, 130}, {461, 41}, {218, 410}, {445, 425}, {540, 317}, {497, 403}, {329, 569}, {720, 266}, {490, 197}, {808, 932}, {146, 801}, {160, 260}, {495, 440}, {633, 844}, {17, 600}, {312, 405}, {82, 125}, {447, 300}, {536, 244}, {77, 76}, {561, 574}, {831, 890}, {144, 903}, {508, 986}, {101, 669}, {918, 599}, {470, 78}, {860, 965}, {870, 845}, {810, 888}, {446, 122}, {645, 880}, {599, 92}, {181, 487}, {688, 610}, {916, 249}, {185, 747}, {492, 681}, {3, 352}, {667, 456}, {21, 937}, {55, 491}, {15, 915}, {457, 238}, {761, 267}, {478, 559}, {741, 123}, {439, 692}, {568, 972}, {180, 256}, {935, 96}, {858, 120}, {195, 702}, {801, 198}, {54, 820}, {654, 76}, {757, 62}, {567, 772}, {977, 376}, {362, 90}, {995, 840}, {1, 88}, {316, 793}, {781, 884}, {765, 961}, {492, 700}, {57, 702}, {172, 604}, {404, 325}, {803, 459}, {145, 809}, {887, 902}, {871, 454}, {27, 201}, {183, 741}, {643, 178}, {582, 645}, {267, 250}, {438, 48}, {134, 555}, {361, 978}, {608, 770}, {681, 780}, {374, 437}, {106, 529}, {896, 603}, {339, 135}, {858, 562}, {590, 885}, {115, 125}, {626, 759}, {303, 560}, {404, 922}, {810, 842}, {970, 296}, {397, 683}, {627, 5}, {453, 308}, {138, 828}, {745, 596}, {709, 994}, {199, 48}, {129, 57}, {963, 71}, {294, 78}, {196, 273}, {189, 852}, {833, 593}, {774, 996}, {787, 97}, {644, 537}, {780, 271}, {894, 234}, {579, 32}, {414, 677}, {628, 123}, {23, 180}, {524, 504}, {589, 487}, {576, 884}, {917, 124}, {157, 107}, {976, 342}, {52, 103}, {690, 840}, {200, 335}, {377, 980}, {606, 271}, {566, 538}, {656, 980}, {567, 636}, {456, 590}, {168, 980}, {94, 758}, {819, 22}, {994, 88}, {147, 503}, {195, 475}, {197, 600}, {578, 888}, {792, 130}, {223, 169}, {463, 181}, {792, 29}, {719, 800}, {10, 286}, {789, 466}, {228, 957}, {798, 323}, {715, 617}, {697, 61}, {705, 196}, {564, 253}, {672, 762}, {205, 602}, {650, 997}, {85, 225}, {518, 548}, {406, 662}, {577, 478}, {463, 939}, {116, 252}, {757, 345}, {561, 555}, {20, 277}, {524, 717}, {690, 582}, {914, 255}, {187, 938}, {17, 392}, {892, 19}, {741, 977}, {596, 259}, {525, 2}, {273, 455}, {832, 736}, {394, 949}, {340, 504}, {294, 902}, {59, 314}, {531, 936}, {383, 221}, {870, 297}, {828, 57}, {587, 197}, {801, 480}, {568, 894}, {457, 164}, {153, 335}, {519, 426}, {790, 351}, {515, 536}, {652, 207}, {40, 946}, {461, 452}, {612, 344}, {388, 996}, {918, 610}, {645, 746}, {19, 233}, {296, 820}, {65, 864}, {66, 522}, {29, 219}, {209, 548}, {997, 351}, {251, 864}, {888, 904}, {72, 928}, {202, 885}, {732, 815}, {230, 472}, {163, 148}, {82, 160}, {246, 101}, {745, 542}, {273, 810}, {407, 339}, } expectedData := 1000 if res := numberOfBoomerangs(testData); res != expectedData { t.Errorf("expected %d, got %d", expectedData, res) } } ================================================ FILE: solutions/0454_4sum2/4sum2.go ================================================ /* 454. 4Sum II https://leetcode.com/problems/4sum-ii/ Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. */ package foursum2 // Time complexity: O(n^2) // Space complexity: O(n^2) func fourSumCount(A []int, B []int, C []int, D []int) int { var ( record = make(map[int]int) res int ) for _, i := range A { for _, j := range B { record[i+j]++ } } for _, i := range C { for _, j := range D { if s, ok := record[-i-j]; ok && s > 0 { res += s } } } return res } ================================================ FILE: solutions/0454_4sum2/4sum2_test.go ================================================ package foursum2 import "testing" func TestFourSumCount(t *testing.T) { A := []int{1, 2} B := []int{-2, -1} C := []int{-1, 2} D := []int{0, 2} expectedData := 2 if res := fourSumCount(A, B, C, D); res != expectedData { t.Errorf("expected %d, got %d", expectedData, res) } } ================================================ FILE: solutions/0455_assign_cookies/assign_cookies.go ================================================ /* 455. Assign Cookies https://leetcode.com/problems/assign-cookies/ Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Note: 1. You may assume the greed factor is always positive. 2. You cannot assign more than one cookie to one child. */ package assigncookies import "sort" // greedy // Time complexity: O(n), where n is min ( len(g), len(s) ) // Space complexity: O(1) func findContentChildren(g []int, s []int) int { sort.Sort(sort.Reverse(sort.IntSlice(s))) sort.Sort(sort.Reverse(sort.IntSlice(g))) var ( si, gi, res int ) for gi < len(g) && si < len(s) { if s[si] >= g[gi] { res++ gi++ si++ } else { gi++ } } return res } ================================================ FILE: solutions/0455_assign_cookies/assign_cookies_test.go ================================================ package assigncookies import "testing" type args struct { g []int s []int } func TestAssignCookies(t *testing.T) { testData := []args{ { g: []int{1, 2, 3}, s: []int{1, 1}, }, { g: []int{1, 2}, s: []int{1, 2, 3}, }, } expectedData := []int{1, 2} for index, data := range testData { if res := findContentChildren(data.g, data.s); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3.go ================================================ /* 557. Reverse Words in a String III https://leetcode.com/problems/reverse-words-in-a-string-iii/ Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Note: In the string, each word is separated by single space and there will not be any extra space in the string. */ // time: 2019-01-08 package rwias3 import "strings" // split and reverse // time complexity: O(len(s)) // space complexity: O(n) func reverseWords(s string) string { words := strings.Split(s, " ") var temp []string for _, word := range words { temp = append(temp, reverseString(word)) } return strings.Join(temp, " ") } func reverseString(s string) string { runes := []rune(s) for start, end := 0, len(runes)-1; start < end; start, end = start+1, end-1 { runes[start], runes[end] = runes[end], runes[start] } return string(runes) } ================================================ FILE: solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3_test.go ================================================ package rwias3 import "testing" func TestReverseWords(t *testing.T) { s := "Let's take LeetCode contest" expected := "s'teL ekat edoCteeL tsetnoc" if res := reverseWords(s); res != expected { t.Errorf("expected %s, got %s", expected, res) } } ================================================ FILE: solutions/0674_longest_continuous_increasing_subsequence/lcis.go ================================================ /* 674. Longest Continuous Increasing Subsequence https://leetcode.com/problems/longest-continuous-increasing-subsequence/ Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). */ // time: 2018-12-29 package lcis // time complexity: O(n), where n is nums's length. // space complexity: O(1) func findLengthOfLCIS(nums []int) int { n := len(nums) if 0 == n || 1 == n { return n } var res, l, r int for r < n { if res < r-l+1 { res = r - l + 1 } if r+1 < n && nums[r+1] <= nums[r] { l = r + 1 } r++ } return res } // time complexity: O(n), where n is nums's length. // space complexity: O(1) func findLengthOfLCIS1(nums []int) int { n := len(nums) if 0 == n || 1 == n { return n } var ( maxLen int count = 1 ) for i := 1; i < n; i++ { if nums[i] > nums[i-1] { count++ } else { count = 1 } if count > maxLen { maxLen = count } } return maxLen } ================================================ FILE: solutions/0674_longest_continuous_increasing_subsequence/lcis_test.go ================================================ package lcis import "testing" func TestFindLengthOfLCIS(t *testing.T) { testCases := [][]int{ {1, 3, 5, 4, 7}, {2, 2, 2, 2, 2}, {}, {2}, } testFuncs := []func([]int) int{ findLengthOfLCIS, findLengthOfLCIS1, } expected := []int{3, 1, 0, 1} for _, tfn := range testFuncs { for index, data := range testCases { if res := tfn(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } } ================================================ FILE: solutions/0677_map_sum_pairs/map_sum_pairs.go ================================================ /* 677. Map Sum Pairs https://leetcode.com/problems/map-sum-pairs/ Implement a MapSum class with insert, and sum methods. For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one. For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix. */ // time: 2019-02-01 package mapsumpairs type node struct { val int next map[rune]*node } // MapSum data structure for solution. type MapSum struct { root *node } // Constructor initialize data structure here. func Constructor() MapSum { return MapSum{&node{next: make(map[rune]*node)}} } // Insert inserts a word into the trie. func (ms *MapSum) Insert(key string, val int) { cur := ms.root for _, c := range key { if _, ok := cur.next[c]; !ok { cur.next[c] = &node{next: make(map[rune]*node)} } cur = cur.next[c] } cur.val = val } // Sum sum of all the pairs' value whose key starts with the prefix. func (ms *MapSum) Sum(prefix string) int { cur := ms.root for _, c := range prefix { if _, ok := cur.next[c]; !ok { return 0 } cur = cur.next[c] } return sum(cur) } func sum(n *node) int { res := n.val for _, nextNode := range n.next { res += sum(nextNode) } return res } ================================================ FILE: solutions/0677_map_sum_pairs/map_sum_pairs_test.go ================================================ package mapsumpairs import "testing" func TestMapSumPairs(t *testing.T) { obj := Constructor() obj.Insert("apple", 3) if res := obj.Sum("ap"); res != 3 { t.Errorf("expected %d, got %d", 3, res) } obj.Insert("app", 2) if res := obj.Sum("ap"); res != 5 { t.Errorf("expected %d, got %d", 5, res) } if res := obj.Sum("al"); res != 0 { t.Errorf("expected %d, got %d", 0, res) } } ================================================ FILE: solutions/0704_binary_search/binary_search.go ================================================ /* 704. Binary Search https://leetcode.com/problems/binary-search/ Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. Note: 1. You may assume that all elements in nums are unique. 2. n will be in the range [1, 10000]. 3. The value of each element in nums will be in the range [-9999, 9999]. */ // time: 2018-12-19 package binarysearch // iterative // Time complexity: O(log(n)) // Space complexity: O(1) func search(nums []int, target int) int { var ( l int r = len(nums) - 1 ) // 在[l...r]区间寻找target for l <= r { // 当l==r时,区间依然是有效的。 mid := l + (r-l)/2 // (l+r)/2 可能会整型益处 if nums[mid] == target { return mid } if nums[mid] > target { r = mid - 1 } else { l = mid + 1 } } return -1 } ================================================ FILE: solutions/0704_binary_search/binary_search_test.go ================================================ package binarysearch import "testing" func TestSearch(t *testing.T) { type arg struct { nums []int target int } testCases := []arg{ { nums: []int{-1, 0, 3, 5, 9, 12}, target: 9, }, { nums: []int{-1, 0, 3, 5, 9, 12}, target: -3, }, } expected := []int{4, -1} for index, data := range testCases { if res := search(data.nums, data.target); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0713_subarray_product_less_than_k/spltk.go ================================================ /* 713. Subarray Product Less Than K https://leetcode.com/problems/subarray-product-less-than-k/ Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. */ // time: 2018-12-27 package spltk // sliding window // time complexity: O(n), where n = len(nums) // space complexity: O(1) func numSubArrayProductLessThanK(nums []int, k int) int { if k <= 1 { return 0 } var ( n = len(nums) l, r int res int prod = 1 ) for l < n { if r < n && prod*nums[r] < k { prod *= nums[r] r++ } else if l == r { l++ r++ } else { res += r - l prod /= nums[l] l++ } } return res } // 2019-06-16 func numSubArrayProductLessThanK2(nums []int, k int) int { if k <= 1 { return 0 } var ( prod = 1 res = 0 left = 0 ) for right, val := range nums { prod *= val for prod >= k { prod /= nums[left] left++ } res += right - left + 1 } return res } ================================================ FILE: solutions/0713_subarray_product_less_than_k/spltk_test.go ================================================ package spltk import "testing" func TestNumSubArrayProductLessThanK(t *testing.T) { testCases := [][]int{ {10, 5, 2, 6}, {10, 5, 2, 6}, {10, 5, 100, 6}, } ks := []int{100, 0, 100} expected := []int{8, 0, 4} functions := []func([]int, int) int{ numSubArrayProductLessThanK, numSubArrayProductLessThanK2, } for _, testFunc := range functions { for index, data := range testCases { if res := testFunc(data, ks[index]); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } } ================================================ FILE: solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc.go ================================================ /* 717. 1-bit and 2-bit Characters https://leetcode.com/problems/1-bit-and-2-bit-characters/ We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1. */ // time: 2018-12-28 package onebitandtwobitcharacters // time complexity: O(n) // space complexity: O(1) func isOneBitCharacter(bits []int) bool { n := len(bits) if 1 == n { return true } cur := 0 flag := false for cur < n { if 0 == bits[cur] { cur++ } else { cur += 2 } if cur == n-1 { flag = true } } return flag } ================================================ FILE: solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc_test.go ================================================ package onebitandtwobitcharacters import "testing" func TestIsOneBitCharacter(t *testing.T) { testCases := [][]int{ {1, 0, 0}, {1, 1, 1, 0}, {0}, } expected := []bool{true, false, true} for index, bits := range testCases { if res := isOneBitCharacter(bits); res != expected[index] { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/0728_self_dividing_numbers/self_dividing_numbers.go ================================================ /* 728. Self Dividing Numbers Source: https://leetcode.com/problems/self-dividing-numbers/ A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. Example 1: Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] Note: The boundaries of each input argument are 1 <= left <= right <= 10000. Time: 2018-12-18 */ package selfdividingnumbers import "strconv" //Time complexity: O(right-left+1) // Space complexity: O(1) func selfDividingNumbers(left int, right int) []int { res := make([]int, 0) for num := left; num <= right; num++ { flag := true strNum := strconv.Itoa(num) for j := 0; j < len(strNum); j++ { if divisor := int(strNum[j] - '0'); divisor == 0 || num%divisor != 0 { flag = false } } if flag { res = append(res, num) } } return res } ================================================ FILE: solutions/0728_self_dividing_numbers/self_dividing_numbers_test.go ================================================ package selfdividingnumbers import ( "reflect" "testing" ) func TestSelfDividingNumbers(t *testing.T) { expected := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22} if res := selfDividingNumbers(1, 22); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } ================================================ FILE: solutions/0735_asteroid_collision/ac.go ================================================ /* 735. Asteroid Collision https://leetcode.com/problems/asteroid-collision/ We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Note: The length of asteroids will be at most 10000. Each asteroid will be a non-zero integer in the range [-1000, 1000].. */ // time: 2019-01-14 package ac // stack // time complexity: O(N), where NN is the number of asteroids. Our stack pushes and pops each asteroid at most once. // space complexity: O(N), the size of stack. func asteroidCollision(asteroids []int) []int { stack := make([]int, 0) for _, asteroid := range asteroids { flag := true for len(stack) > 0 && asteroid < 0 && stack[len(stack)-1] > 0 { if stack[len(stack)-1] == -asteroid { stack = stack[:len(stack)-1] } else if stack[len(stack)-1] < -asteroid { stack = stack[:len(stack)-1] continue } flag = false break } if flag { stack = append(stack, asteroid) } } return stack } ================================================ FILE: solutions/0735_asteroid_collision/ac_test.go ================================================ package ac import ( "reflect" "testing" ) func TestAsteroidCollision(t *testing.T) { testCases := [][]int{ {5, 10, -5}, {-2, 2, -1, -2}, {-2, -1, 1, 2}, {8, -8}, {10, 2, -5}, } expected := [][]int{ {5, 10}, {-2}, {-2, -1, 1, 2}, {}, {10}, } for index, asteroids := range testCases { if res := asteroidCollision(asteroids); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %v, got %v", expected[index], res) } } } ================================================ FILE: solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others.go ================================================ /* 747. Largest Number At Least Twice of Others Source: https://leetcode.com/problems/largest-number-at-least-twice-of-others/ In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise return -1. Example 1: Input: nums = [3, 6, 1, 0] Output: 1 Explanation: 6 is the largest integer, and for every other number in the array x, 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. Example 2: Input: nums = [1, 2, 3, 4] Output: -1 Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. Note: 1. nums will have a length in the range [1, 50]. 2. Every nums[i] will be an integer in the range [0, 99]. */ // 2018-12-18 package largestnumberatleasttwiceofothers import "leetcode/utils" // Time complexity: O(n) // Space complexity: O(1) func dominantIndex(nums []int) int { var ( maxNum = utils.MinInt res int ) for i, j := range nums { if j > maxNum { maxNum = j res = i } } for _, j := range nums { if maxNum < 2*j && j != maxNum { return -1 } } return res } ================================================ FILE: solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others_test.go ================================================ package largestnumberatleasttwiceofothers import "testing" func TestDominantIndex(t *testing.T) { testCases := [][]int{ {0, 0, 0, 1}, {0, 0, 1, 1}, {1, 2, 3, 4}, {3, 6, 1, 0}, } expected := []int{3, 2, -1, 1} for index, data := range testCases { if res := dominantIndex(data); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } } ================================================ FILE: solutions/0872_leaf_similar_trees/leaf_similar_trees.go ================================================ /* 872. Leaf-Similar Trees https://leetcode.com/problems/leaf-similar-trees/ */ // time: 2019-01-08 package lst import ( "reflect" ) // TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // time complexity: O(n1 + n2), where n is nodes number in the tree. // space complexity: O(h1 + h2), where h is height of the tree. func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { l1 := make([]int, 0) l2 := make([]int, 0) dfs(root1, &l1) dfs(root2, &l2) return reflect.DeepEqual(l1, l2) } func dfs(root *TreeNode, l *[]int) { if nil == root { return } if root.Left == nil && root.Right == nil { *l = append(*l, root.Val) } dfs(root.Left, l) dfs(root.Right, l) } ================================================ FILE: solutions/0872_leaf_similar_trees/leaf_similar_trees_test.go ================================================ package lst import ( "reflect" "testing" ) func createBinaryTree(nums []int) *TreeNode { return performCreate(nums, 0) } func performCreate(nums []int, index int) *TreeNode { if index >= len(nums) { return nil } tree := TreeNode{Val: nums[index]} tree.Left = performCreate(nums, 2*index+1) tree.Right = performCreate(nums, 2*index+2) return &tree } func TestLeafSimilar(t *testing.T) { type arg struct { root1, root2 *TreeNode } testCases := []arg{ {root1: createBinaryTree([]int{3, 5, 1, 6, 2, 9, 8}), root2: createBinaryTree([]int{6, 4, 1, 6, 2, 9, 8})}, {root1: createBinaryTree([]int{3, 5, 1, 6, 2, 9, 4}), root2: createBinaryTree([]int{6, 4, 1, 6, 2, 9, 8})}, } expected := []bool{true, false} for index, data := range testCases { if res := leafSimilar(data.root1, data.root2); !reflect.DeepEqual(res, expected[index]) { t.Errorf("expected %t, got %t", expected[index], res) } } } ================================================ FILE: solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses.go ================================================ /* 1021. Remove Outermost Parentheses A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. Example 1: Input: "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". Example 2: Input: "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". Example 3: Input: "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "". Note: S.length <= 10000 S[i] is "(" or ")" S is a valid parentheses string */ // time: 2020-05-04 package removeoutmostparentheses // time complexity: O(n), where n is length of S. // space complexity: O(1) func removeOuterParentheses(S string) string { // S is valid parentheses string, so, s is empty "" or starts with "(" if len(S) == 0 { return S } var stackLength, left int var ret string for i := 0; i < len(S); i++ { if stackLength == 0 { left = i } if S[i] == '(' { stackLength++ } else { stackLength-- } if stackLength == 0 { ret += S[left+1 : i] } } return ret } ================================================ FILE: solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses_test.go ================================================ package removeoutmostparentheses import ( "testing" ) func TestRemoveOuterParentheses(t *testing.T) { testCases := []map[string]string{ {"case": "(()())(())", "expected": "()()()"}, {"case": "(()())(())(()(()))", "expected": "()()()()(())"}, {"case": "", "expected": ""}, {"case": "()()", "expected": ""}, } for _, testCase := range testCases { if testCase["expected"] != removeOuterParentheses(testCase["case"]) { t.Errorf("hello") } } } ================================================ FILE: solutions/148_Sort_List/sortlist.go ================================================ /* 148. Sort List https://leetcode.com/problems/sort-list/ */ // time: 2019-03-04 package sortlist // ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } // merge sort // time complexity: O(n * log(n)) // using recursion, the system stack is used. func sortList(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } prev, slow, fast := head, head, head for fast != nil && fast.Next != nil { prev = slow slow = slow.Next fast = fast.Next.Next } prev.Next = nil return merge(sortList(head), sortList(slow)) } func merge(headA, headB *ListNode) *ListNode { dummy := &ListNode{} tail := dummy for headA != nil && headB != nil { if headA.Val > headB.Val { tail.Next = headB headB = headB.Next } else { tail.Next = headA headA = headA.Next } tail = tail.Next } if headA != nil { tail.Next = headA } else { tail.Next = headB } return dummy.Next } ================================================ FILE: solutions/148_Sort_List/sortlist_test.go ================================================ package sortlist import ( "reflect" "testing" ) func TestSortList(t *testing.T) { head := createSingleLinkedList([]int{-1, 5, 3, 4, 0}) expected := createSingleLinkedList([]int{-1, 0, 3, 4, 5}) if res := sortList(head); !reflect.DeepEqual(res, expected) { t.Errorf("expected %v, got %v", expected, res) } } func createSingleLinkedList(nums []int) *ListNode { dummy := ListNode{} cur := &dummy for _, val := range nums { cur.Next = &ListNode{Val: val} cur = cur.Next } return dummy.Next } ================================================ FILE: solutions/304_Range_Sum_Query_2D/rsq.go ================================================ /* 304. Range Sum Query 2D - Immutable https://leetcode.com/problems/range-sum-query-2d-immutable/ */ // 2019-02-27 package rsq // NumMatrix 累计区域和的数组 type NumMatrix struct { dp [][]int } // Constructor 初始化构造函数 func Constructor(matrix [][]int) NumMatrix { if len(matrix) == 0 || len(matrix[0]) == 0 { return NumMatrix{} } numMatrix := NumMatrix{dp: make([][]int, len(matrix)+1)} for i := 0; i < len(numMatrix.dp); i++ { numMatrix.dp[i] = make([]int, len(matrix[0])+1) } for i := 1; i <= len(matrix); i++ { for j := 1; j <= len(matrix[0]); j++ { numMatrix.dp[i][j] = numMatrix.dp[i-1][j] + numMatrix.dp[i][j-1] - numMatrix.dp[i-1][j-1] + matrix[i-1][j-1] } } return numMatrix } // SumRegion 求区域和 func (nm *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { return nm.dp[row2+1][col2+1] - nm.dp[row1][col2+1] - nm.dp[row2+1][col1] + nm.dp[row1][col1] } ================================================ FILE: solutions/304_Range_Sum_Query_2D/rsq_test.go ================================================ package rsq import "testing" func TestSunRegion(t *testing.T) { matrix := [][]int{ {3, 0, 1, 4, 2}, {5, 6, 3, 2, 1}, {1, 2, 0, 1, 5}, {4, 1, 0, 1, 7}, {1, 0, 3, 0, 5}, } obj := Constructor(matrix) testData := [][]int{ {2, 1, 4, 3}, {1, 1, 2, 2}, {1, 2, 2, 4}, } expected := []int{8, 11, 12} for index, data := range testData { if res := obj.SumRegion(data[0], data[1], data[2], data[3]); res != expected[index] { t.Errorf("expected %d, got %d", expected[index], res) } } if res := Constructor([][]int{}); res.dp != nil { t.Errorf("expected nil, got %v", res.dp) } if res := Constructor(make([][]int, 3)); res.dp != nil { t.Errorf("expected nil, got %v", res.dp) } } ================================================ FILE: solutions/README.md ================================================ ### Solutions for LeetCode algorithm problems, continually updating. |ID|Title && solution|Coefficient of difficulty|remarks| |:---:|:---|:---:|:---:| |0001|[Two Sum](0001_two_sum/twosum.go)|Easy|*`array;`* *`lookup table`*| |0002|[Add Two Numbers](0002_add_two_numbers/add_two_numbers.go)|Medium|*`linked list`*| |0003|[Longest Substring Without Repeating Characters](0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go)|Medium|*`sliding window`*| |0004|[4. Median of Two Sorted Arrays](0004_median_of_two_sorted_arrays/motsa.go)|Hard|*`binary search`*| |0007|[7. Reverse Integer](0007_reverse_integer/reverse_integer.go)|Easy|*`math`*| |0009|[9. Palindrome Number](0009_palindrome_number/palindrome_number.go)|Easy|*`math`*| |0011|[11. Container With Most Water](0011_container_with_most_water/container_with_most_water.go)|Medium|*`array;`* *`double index`*| |0013|[13. Roman to Integer](0013_roman_to_integer/roman_to_integer.go)|Easy|*`math`*| |0014|[14. Longest Common Prefix](0014_longest_common_prefix/lcp.go)|Easy|| |0015|[15. 3Sum](0015_3Sum/3sum.go)|Medium|| |0017|[Letter Combinations of a Phone Number](0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go)|Medium|*`tree`*| |0019|[19. Remove Nth Node From End of List](0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go)|Medium|*`linked list`*| |0020|[Valid Parentheses](0020_valid_parentheses/valid_parentheses.go)|Easy|*`string;`* *`stack`*| |0021|[Merge Two Sorted Lists](0021_merge_two_sorted_lists/mergeTwoLists.go)|Easy|*`linked list`*| |0023|[23. Merge k Sorted Lists](0023_merge_k_sorted_lists/mksl.go)|Hard|*`linked list;`* *`heap`*| |0024|[24. Swap Nodes in Pairs](0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go)|Medium|*`linked list`*| |0025|[Reverse Nodes in k-Group](./0025_reverse_nodes_in_k_group/reverse_node_k_group.go)|Hard|*`linked list`*| |0026|[Remove Duplicates from Sorted Array](0026_remove_duplicates_from_sorted_array/rdfsa.go)|Easy|*`array;`* *`double index`*| |0027|[Remove Element](0027_remove_element/remove_element.go)|Easy|*`array`*| |0028|[28. Implement strStr()](0028_implement_strstr/implement_strstr.go)|Easy|*`double index`*| |0033|[Search in Rotated Sorted Array](0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go)|Medium|*`binary search`*| |0034|[Find First and Last Position of Element in Sorted Array](0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go)|Medium|*`binary search`*| |0035|[35. Search Insert Position](0035_search_insert_position/search_insert_position.go)|Easy|*`binary search`*| |0048|[48. Rotate Image](0048_rotate_image/rotate_image.go)|Medium|*`array`*| |0053|[53. Maximum Subarray](0053_maximum_subarray/maximum_subarray.go)|Easy|*`dynamic programming`*| |0058|[58. Length of Last Word](0058_length_of_last_word/len_of_last_word.go)|Easy|| |0061|[Rotate List](./0061_rotate_list/rotate_list.go)|Medium|*`linked list`*| |0062|[Unique Paths](./0062_unique_paths/unique_paths.go)|Medium|*`recursion;`* *`memory search;`* *`dynamic programming`*| |0063|[Unique Paths 2](./0063_unique_paths_2/unique_paths2.go)|Medium|*`recursion;`* *`memory search;`* *`dynamic programming`*| |0064|[Minimum Path Sum](./0064_minimum_path_sum/minimum_path_sum.go)|Medium|*`dynamic programming;`* *` dfs`*| |0066|[66. Plus One](0066_plus_one/plus_one.go)|Easy|*`math`*| |0067|[add Binary](./0067_add_binary/add_binary.go)|Easy|| |0069|[Sqrt(x)](0069_sqrtx/sqrtx.go)|Easy|*`binary search`*| |0070|[Climbing Stairs](./0070_climbing_stairs/climbing_stairs.go)|Easy|*`dynamic programming`*| |0075|[75. Sort Colors](0075_sort_colors/sort_colors.go)|Medium|*`sort`*| |0076|[Minimum Window Substring](./0076_minimum_window_substring/minimum_window_substring.go)|Hard|*`sliding window`*| |0077|[77. Combinations](0077_combinations/combinations.go)|Medium|*`backtracking;`* *`combine`*| |0079|[79. Word Search](0079_word_search/word_search.go)|Medium|*`backtracking;`* *`array`*| |0080|[80. Remove Duplicates from Sorted Array II](0080_remove_duplicates_from_sorted_array2/rdfsa2.go)|Medium|*`double index`*| |0082|[82. Remove Duplicates from Sorted List II](0082_remove_duplicates_from_sorted_list_2/rdfsl.go)|Medium|*`linked list`*| |0083|[83. Remove Duplicates from Sorted List](0083_remove_duplicates_from_sorted_list/rdfsl.go)|Easy|*`linked list`*| |0086|[86. Partition List](0086_partition_list/partition_list.go)|Medium|*`linked list`*| |0088|[88. Merge Sorted Array](0088_merge_sorted_array/msa.go)|Easy|*`sort`*| |0092|[92. Reverse Linked List II](0092_reverse_linked_list_2/reverse_linked_list2.go)|Medium|*`linked list`*| |0094|[Binary Tree Inorder Traversal](./0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go)|Medium|*`binary tree`*| |0100|[Same Tree](./0100_same_tree/same_tree.go)|Easy|*`binary tree`*| |0101|[Symmetric Tree](./0101_symmetric_tree/symmetric_tree.go)|Easy|*`stack;`* *`recursion; `* *`iterative`*| |0102|[102. Binary Tree Level Order Traversal](0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go)|Medium|*`binary tree;`* *`bfs`*| |0104|[104. Maximum Depth of Binary Tree](0104_maximun_depth_of_binary_tree/maxdobt.go)|Easy|*`binary tree`*| |0107|[Binary Tree Level Order Traversal II](./0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go)|Easy|*`binary tree`*| |0111|[Minimum Depth of Binary Tree](./0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go)|Easy|*`binary tree`*| |0112|[Path Sum](./0112_path_sum/path_sum.go)|Easy|*`binary tree`*| |0120|[Triangle](./0120_triangle/triangle.go)|Medium|*`dynamic programming;`* *` dfs`*| |0121|[121. Best Time to Buy and Sell Stock](0121_best_time_to_buy_and_sell_stock/maxprofit.go)|Easy|| |0122|[122. Best Time to Buy and Sell Stock II](0122_best_time_to_buy_and_sell_stock_2/maxprofit.go)|Easy|*`greedy`*| |0125|[Valid Palindrome](0125_valid_palindrome/valid_palindrome.go)|Easy|| |0136|[136. Single Number](0136_single_number/single_number.go)|Easy|*`hash table;`* *`bit manipulation`*| |0144|[144. Binary Tree Preorder Traversal](0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go)|Medium|*`binary tree`*| |0148|[148. Sort List](148_Sort_List/sortlist.go)|Medium|*`sort;`* *`linked list`*| |0150|[150. Evaluate Reverse Polish Notation](0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go)|Medium|*`stack`*| |0153|[153. Find Minimum in Rotated Sorted Array](0153_find_minimum_in_rotated_sorted_array/fmirsa.go)|Medium|*`binary search`*| |0155|[155. Min Stack](0155_min_stack/min_stack.go)|Easy|*`stack`*| |0165|[165. Compare Version Numbers](0165_compare_version_numbers/compare_version_numbers.go)|Medium|*`string`*| |0167|[Two Sum II - Input array is sorted](./0167_two_sum2/two_sum2.go)|Easy|*`对撞指针(双索引)`*| |0179|[179. Largest Number](0179_largest_number/ln.go)|Medium|*`sort`*| |0198|[House Robber](./0198_house_robber/house_robber.go)|Easy|*`memory search;`* *`dynamic programming`*| |0200|[200. Number of Islands](0200_number_of_island/number_of_island.go)|Medium|*`dfs;`* *`bfs`*| |0203|[203. Remove Linked List Elements](0203_remove_linked_list_elements/remove_linked_list_elements.go)|Easy|*`linked list`*| |0206|[206. Reverse Linked List](0206_reverse_linked_list/reverse_linked_list.go)|Easy|*`linked list`*| |0208|[208. Implement Trie (Prefix Tree)](0208_implement_trie_prefix_tree/impltrie.go)|Medium|*`trie`*| |0209|[Minimum Size Subarray Sum](./0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go)|Medium|*`sliding window`*| |0211|[211. Add and Search Word - Data structure design](0211_add_and_search_word/add_and_search_word.go)|Medium|*`trie`*| |0215|[215. Kth Largest Element in an Array](0215_kth_largest_element_in_an_array/kthleiaa.go)|Medium|*`sort`*| |0217|[217. Contains Duplicate](0217_contains_duplicate/contains_duplicate.go)|Easy|*`map`*| |0219|[219. Contains Duplicate II](0219_contains_duplicate_2/contains_duplicate_2.go)|Easy|*`map`*| |0226|[Invert Binary Tree](./0226_invert_binary_tree/invert_binary_tree.go)|Easy|*`recursion; `* *`binary tree`*| |0235|[235. Lowest Common Ancestor of a Binary Search Tree](0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go)|Easy|*`recursion; `* *`binary tree`*| |0236|[236. Lowest Common Ancestor of a Binary Tree](0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go)|Medium|*`recursion; `* *`binary tree`*| |0237|[237. Delete Node in a Linked List](0237_delete_node_in_a_linked_list/dniall.go)|Easy|*`linked list`*| |0257|[257. Binary Tree Paths](0257_binary_tree_paths/binary_tree_paths.go)|Easy|*`binary tree`*| |0258|[258. Add Digits](0258_add_digits/add_digits.go)|Easy|*`math`*| |0283|[Move Zeroes(solution1)](./0283_move_zeroes/move_zeroes.go)
[Move Zeroes(solution2)](./0283_move_zeroes/move_zeroes2.go)|Easy|*`array`*| |0300|[Longest Increasing Subsequence](./0300_longest_increasing_subsequence/lis.go)|Medium|*`dp`*| |0303|[303. Range Sum Query - Immutable](0303_range_sum_query/rsqim.go)|Easy|| |0304|[304. Range Sum Query 2D - Immutable](304_Range_Sum_Query_2D/rsq.go)|Medium|*`dp`*| |0307|[307. Range Sum Query - Mutable](0307_Range_Sum_Query_Mutable/range_sum_query_mut.go)|Medium|*`segment tree`*| |0328|[328. Odd Even Linked List](0328_odd_even_linked_list/odd_even_linked_list.go)|Medium|*`singly linked list`*| |0343|[Integer Break](./0343_integer_break/integer_break.go)|Medium|*`recursion;`* *`memory search;`* *`dynamic programming`*| |0344|[344. Reverse String](0344_reverse_string/reverse_string.go)|Easy|*`double index`*| |0345|[345. Reverse Vowels of a String](0345_reverse_vowels_of_a_string/reverse_vowels.go)|Easy|*`double index`*| |0347|[347. Top K Frequent Elements](0347_top_k_frequent_elements/topkfe.go)|Medium|*`map;`* *`heap;`* *`array`*| |0349|[Intersection of Two Arrays](./0349_intersection_of_2_arrays/intersection_of_two_arrays.go)|Easy|*`set`*| |0350| [Intersection of Two Arrays II](./0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go)|Easy|*`map`*| |0376|[Wiggle Subsequence](./0376_wiggle_subsequence/wiggle_subsequence.go)|Medium|*`dp`*| |0392|[Is Subsequence](./0392_is_subsequence/is_subsequence.go)|Medium|*`greedy algorithm`*| |0404|[404. Sum of Left Leaves](0404_sum_of_left_leaves/sum_of_left_leaves.go)|Easy|*`binary tree`*| |0416|[Partition Equal Subset Sum](./0416_partition_equal_subset_sum/partition_equal_subset_sum.go)|Medium|*`dp;`* *`0-1 knapsack problem`*| |0435|[Non-overlapping Intervals(dp solution)](./0435_non_overlapping_intervals/dp_solution.go)
[Non-overlapping Intervals(greedy solution)](./0435_non_overlapping_intervals/greedy_solution.go)|Medium|*`dp;`* *`0-1 knapsack problem`*| |0437|[437. Path Sum III](0437_path_sum_3/path_sum_3.go)|Easy|*`binary tree`*| |0438|[ Find All Anagrams in a String](./0438_all_anagrams_in_a_string/all_anagrams_in_a_string.go)|Easy|*`sliding window`*| |0447|[Number of Boomerangs](./0447_number_of_boomerangs/number_of_boomerangs.go)|Easy|| |0454|[4Sum II](./0454_4sum2/4sum2.go)|Medium|| |0455|[Assign Cookies](./0455_assign_cookies/assign_cookies.go)|Easy|*`greedy algorithm`*| |0557|[557. Reverse Words in a String III](0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3.go)|Easy|*`string`*| |0674|[674. Longest Continuous Increasing Subsequence](0674_longest_continuous_increasing_subsequence/lcis.go)|Easy|| |0677|[677. Map Sum Pairs](0677_map_sum_pairs/map_sum_pairs.go)|Medium|*`trie`*| |0704|[Binary Search](0704_binary_search/binary_search.go)|Easy|*`binary search`*| |0713|[713. Subarray Product Less Than K](0713_subarray_product_less_than_k/spltk.go)|Medium|*`sliding window`*| |0717|[717. 1-bit and 2-bit Characters](0717_1_bit_and_2_bit_characters/1bitand2bitc.go)|Easy|| |0728|[Self Dividing Numbers](./0728_self_dividing_numbers/self_dividing_numbers.go)|Easy|| |0735|[735. Asteroid Collision](0735_asteroid_collision/ac.go)|Medium|*`stack`*| |0747|[Largest Number At Least Twice of Others](./0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others.go)|Easy|| |0872|[872. Leaf-Similar Trees](0872_leaf_similar_trees/leaf_similar_trees.go)|Easy|*`binary tree`*| |1021|[1021. Remove Outermost Parentheses](1021_Remove_Outermost_Parentheses/remove_outmost_parentheses.go)|Easy|*`stack`*| ================================================ FILE: ut.bash ================================================ #!/bin/bash function cleanTestCache() { go clean -testcache; } function test_() { go test ./...; } case $1 in clean) cleanTestCache; ;; esac test_; ================================================ FILE: utils/infinite.go ================================================ package utils const ( // MaxUint max unsigned int. MaxUint = ^uint(0) // MaxInt max int. MaxInt = int(MaxUint >> 1) // MinUint min unsigned int. MinUint = 0 // MinInt min int MinInt = -MaxInt - 1 ) ================================================ FILE: utils/maxint.go ================================================ package utils // CalcMaxInt calc max int from multi nums. func CalcMaxInt(nums ...int) (res int) { // 此处也可使用堆排序,构建大顶堆,heapify之后直接取最大值. if len(nums) == 0 { return 0 } res = nums[0] for _, num := range nums { if num > res { res = num } } return } ================================================ FILE: utils/maxint_test.go ================================================ package utils import "testing" func TestCalcMaxInt(t *testing.T) { testData := [][]int{ {}, {3, 4, 67, 8}, } expectedData := []int{0, 67} for index, data := range testData { if res := CalcMaxInt(data...); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } func BenchmarkCalcMaxInt(b *testing.B) { data := []int{3, 4, 67, 8} for i := 0; i < b.N; i++ { CalcMaxInt(data...) } } ================================================ FILE: utils/minint.go ================================================ package utils // CalcMinInt calc min int from multi nums. func CalcMinInt(nums ...int) (res int) { // 此处也可使用堆排序,构建小顶堆,heapify之后直接取最小值. if len(nums) == 0 { return 0 } res = nums[0] for _, num := range nums { if num < res { res = num } } return } ================================================ FILE: utils/minint_test.go ================================================ package utils import "testing" func TestCalcMinInt(t *testing.T) { testData := [][]int{ {3, 4, 67, 8}, {}, {54, 3, 12, 1}, } expectedData := []int{3, 0, 1} for index, data := range testData { if res := CalcMinInt(data...); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } } ================================================ FILE: utils/set.go ================================================ package utils // Exists 空结构体 var Exists = struct{}{} // Set data structure implement by go. type Set map[interface{}]struct{} // NewSet 初始化set func NewSet(items ...interface{}) Set { s := make(Set) s.Add(items...) return s } // Add 向set中添加元素 func (s Set) Add(items ...interface{}) error { for _, item := range items { s[item] = Exists } return nil } // Contains 查看set中是否存在item func (s Set) Contains(item interface{}) bool { _, ok := s[item] return ok } // Size 集合的大小 func (s Set) Size() int { return len(s) } // Clear 清空集合 func (s *Set) Clear() { *s = make(Set) } // Equal 判断两个set是否相等 func (s Set) Equal(other Set) bool { if s.Size() != other.Size() { return false } for key := range s { if !other.Contains(key) { return false } } return true } //IsSubset 判断s是否是other的子集 func (s Set) IsSubset(other Set) bool { if s.Size() > other.Size() { return false } for key := range s { if !other.Contains(key) { return false } } return true } ================================================ FILE: utils/set_test.go ================================================ package utils import ( "testing" "unsafe" ) func TestEmptyStruct(t *testing.T) { if unsafe.Sizeof(Exists) != 0 { t.Error("Exists size must be zero.") } } func TestContains(t *testing.T) { set := NewSet(3, 4) set.Add(5) if set.Contains(3) != true { t.Error("should contains 4.") } if set.Contains(6) != false { t.Error("should not contains 6.") } } func TestSize(t *testing.T) { set := NewSet(3, 4) set.Add(5) if set.Size() != 3 { t.Error("size should be 3.") } } func TestEqual(t *testing.T) { set := NewSet(3, 4) set.Add(5) set1 := NewSet(3, 4, 5) if set.Equal(set1) != true { t.Error("set should equal with set1.") } set1.Add(6) if set.Equal(set1) == true { t.Error("set shouldn't equal with set1.") } } func TestIsSubset(t *testing.T) { set := NewSet(3, 4) set.Add(5) set1 := NewSet(3, 4, 5, 6) if set1.IsSubset(set) == true { t.Error("set1 shouldn't be set's subset.") } if set.IsSubset(set1) == false { t.Error("set should be set1's subset.") } } func TestClear(t *testing.T) { set := NewSet(3, 4) set.Clear() if set.Size() != 0 { t.Error("set should be clear.") } }