├── .codacy.yml ├── .codecov.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── _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 /.codacy.yml: -------------------------------------------------------------------------------- 1 | --- 2 | exclude_paths: 3 | - '**/*.md' 4 | - 'README.md' 5 | -------------------------------------------------------------------------------- /.codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | notify: 3 | require_ci_to_pass: yes 4 | 5 | coverage: 6 | round: up 7 | range: 0..10 8 | precision: 2 9 | 10 | status: 11 | project: yes 12 | patch: yes 13 | changes: yes 14 | 15 | comment: 16 | layout: "reach, diff, flags, files" 17 | behavior: default 18 | require_changes: false # if true: only post the comment if coverage changes 19 | require_base: yes # [yes :: must have a base report to post] 20 | require_head: yes # [yes :: must have a head report to post] 21 | branches: null 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # JetBrains 15 | .idea/ 16 | 17 | # vs code 18 | .vscode/ 19 | 20 | # mac 21 | .DS_Store 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - "1.12.x" 5 | 6 | go_import_path: leetcode 7 | 8 | install: 9 | - go get -t -v ./... 10 | 11 | script: 12 | - go test ./... -race -coverprofile=coverage.txt -covermode=atomic 13 | 14 | after_success: 15 | - bash <(curl -s https://codecov.io/bash) 16 | 17 | branches: 18 | only: 19 | - master 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Basic go commands 2 | GOCMD=go 3 | GOBUILD=$(GOCMD) build 4 | GOCLEAN=$(GOCMD) clean 5 | GOTEST=$(GOCMD) test 6 | GOGET=$(GOCMD) get 7 | GOFMT=$(GOCMD) fmt 8 | 9 | test: 10 | @echo "unit test" 11 | $(GOTEST) ./... 12 | 13 | clean: 14 | @echo "clean test cache" 15 | $(GOCLEAN) -testcache 16 | 17 | fmt: 18 | @echo "fmt code" 19 | $(GOFMT) ./... 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | solutions/README.md -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | ## Welcome to GitHub Pages 2 | 3 | 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. 4 | 5 | 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. 6 | 7 | ### Markdown 8 | 9 | Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for 10 | 11 | ```markdown 12 | Syntax highlighted code block 13 | 14 | # Header 1 15 | ## Header 2 16 | ### Header 3 17 | 18 | - Bulleted 19 | - List 20 | 21 | 1. Numbered 22 | 2. List 23 | 24 | **Bold** and _Italic_ and `Code` text 25 | 26 | [Link](url) and ![Image](src) 27 | ``` 28 | 29 | For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/). 30 | 31 | ### Jekyll Themes 32 | 33 | 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. 34 | 35 | ### Support or Contact 36 | 37 | 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. 38 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module leetcode 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /solutions/0001_two_sum/twosum.go: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Two Sum 3 | 4 | Source: https://leetcode.com/problems/two-sum/ 5 | 6 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 7 | 8 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 9 | 10 | Example: 11 | 12 | Given nums = [2, 7, 11, 15], target = 9, 13 | 14 | Because nums[0] + nums[1] = 2 + 7 = 9, 15 | return [0, 1]. 16 | 17 | */ 18 | 19 | package twosum 20 | 21 | // Time complexity: O(n) 22 | // Space complexity: O(n) 23 | func twoSum(nums []int, target int) []int { 24 | record := make(map[int]int) 25 | 26 | for i, j := range nums { 27 | complement := target - j 28 | if res, ok := record[complement]; ok { 29 | return []int{res, i} 30 | } 31 | record[j] = i 32 | } 33 | return []int{} 34 | } 35 | 36 | // brute force 37 | // Time complexity: O(n^2) 38 | // Space complexity: O(1) 39 | func twoSum1(nums []int, target int) []int { 40 | for i, j := range nums { 41 | for k := i + 1; k < len(nums); k++ { 42 | if nums[k]+j == target { 43 | return []int{i, k} 44 | } 45 | } 46 | } 47 | return []int{} 48 | } 49 | -------------------------------------------------------------------------------- /solutions/0001_two_sum/twosum_test.go: -------------------------------------------------------------------------------- 1 | package twosum 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestTwoSum(t *testing.T) { 9 | nums := []int{2, 7, 11, 15} 10 | 11 | funcs := []func([]int, int) []int{twoSum, twoSum1} 12 | 13 | for _, testFunc := range funcs { 14 | if res := testFunc(nums, 9); !reflect.DeepEqual(res, []int{0, 1}) { 15 | t.Error("Failed, two sum") 16 | } 17 | 18 | if res := testFunc(nums, 6); !reflect.DeepEqual(res, []int{}) { 19 | t.Error("Failed, two sum") 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3. Longest Substring Without Repeating Characters 3 | 4 | Source: https://leetcode.com/problems/longest-substring-without-repeating-characters/ 5 | 6 | Given a string, find the length of the longest substring without repeating characters. 7 | 8 | Example 1: 9 | 10 | Input: "abcabcbb" 11 | Output: 3 12 | Explanation: The answer is "abc", with the length of 3. 13 | Example 2: 14 | 15 | Input: "bbbbb" 16 | Output: 1 17 | Explanation: The answer is "b", with the length of 1. 18 | Example 3: 19 | 20 | Input: "pwwkew" 21 | Output: 3 22 | Explanation: The answer is "wke", with the length of 3. 23 | Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 24 | */ 25 | 26 | package longestsubstringwithoutrepeatingcharacters 27 | 28 | // Time complexity: O(n) 29 | // Space complexity: O(n) 30 | func lengthOfLongestSubstring(s string) int { 31 | 32 | var ( 33 | start = 0 34 | res = 0 35 | lastOccurredRecord = make(map[rune]int) 36 | ) 37 | 38 | for i, ch := range []rune(s) { 39 | if lastIndex, ok := lastOccurredRecord[ch]; ok && lastIndex >= start { 40 | start = lastIndex + 1 41 | } 42 | if i-start+1 > res { 43 | res = i - start + 1 44 | } 45 | lastOccurredRecord[ch] = i 46 | } 47 | return res 48 | } 49 | -------------------------------------------------------------------------------- /solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters_test.go: -------------------------------------------------------------------------------- 1 | package longestsubstringwithoutrepeatingcharacters 2 | 3 | import "testing" 4 | 5 | func TestLengthOfLongestSubstring(t *testing.T) { 6 | testData := []string{ 7 | "abcabcbb", 8 | "bbbbb", 9 | "pwwkew", 10 | } 11 | expectedData := []int{3, 1, 3} 12 | 13 | for index, data := range testData { 14 | if res := lengthOfLongestSubstring(data); res != expectedData[index] { 15 | t.Errorf("expected %d, got %d", expectedData[index], res) 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solutions/0004_median_of_two_sorted_arrays/motsa_test.go: -------------------------------------------------------------------------------- 1 | package motsa 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestFindMedianSortedArrays(t *testing.T) { 8 | type arg struct { 9 | nums1 []int 10 | nums2 []int 11 | } 12 | 13 | testCases := []arg{ 14 | {nums1: []int{1, 3}, nums2: []int{2}}, 15 | {nums1: []int{1, 2}, nums2: []int{3, 4}}, 16 | {nums1: []int{}, nums2: []int{3, 4, 5}}, 17 | {nums1: []int{4, 5, 6}, nums2: []int{}}, 18 | {nums1: []int{2, 3, 4, 5}, nums2: []int{1}}, 19 | {nums1: []int{1}, nums2: []int{2, 3, 4, 5, 6, 7}}, 20 | {nums1: []int{1, 2, 3, 4, 5, 6, 8, 9, 23, 34}, nums2: []int{7}}, 21 | } 22 | 23 | expected := []float64{2, 2.5, 4, 5, 3, 4, 6} 24 | 25 | for index, data := range testCases { 26 | if res := findMedianSortedArrays(data.nums1, data.nums2); res != expected[index] { 27 | t.Errorf("expected %f, got %f", expected[index], res) 28 | } 29 | } 30 | 31 | defer func() { 32 | if err := recover(); err == nil || err != "nums1 and nums2 cannot be both empty." { 33 | t.Errorf("expected err: nums1 and nums2 cannot be both empty.") 34 | } 35 | }() 36 | findMedianSortedArrays([]int{}, []int{}) 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0007_reverse_integer/reverse_integer.go: -------------------------------------------------------------------------------- 1 | /* 2 | 7. Reverse Integer 3 | https://leetcode.com/problems/reverse-integer/ 4 | Given a 32-bit signed integer, reverse digits of an integer. 5 | 6 | */ 7 | // time: 2018-12-29 8 | 9 | package reverseinteger 10 | 11 | // time complexity: O(log 10 x ) = O(log x) 12 | // space complexity: O(1) 13 | func reverse(x int) int { 14 | if 0 == x { 15 | return x 16 | } 17 | 18 | isPositive := true 19 | if x < 0 { 20 | isPositive = false 21 | x *= -1 22 | } 23 | 24 | res := 0 25 | 26 | for x > 0 { 27 | res = res*10 + x%10 28 | x /= 10 29 | } 30 | 31 | if !isPositive { 32 | res *= -1 33 | } 34 | 35 | if res < -1<<31 || res > (1<<31)-1 { 36 | return 0 37 | } 38 | return res 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0007_reverse_integer/reverse_integer_test.go: -------------------------------------------------------------------------------- 1 | package reverseinteger 2 | 3 | import "testing" 4 | 5 | func TestReverse(t *testing.T) { 6 | testCases := []int{ 7 | 123, -123, 10, 0, 12239999999999, 8 | } 9 | expected := []int{321, -321, 1, 0, 0} 10 | 11 | for index, data := range testCases { 12 | if res := reverse(data); res != expected[index] { 13 | t.Errorf("expected %d, got %d", expected[index], res) 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /solutions/0009_palindrome_number/palindrome_number.go: -------------------------------------------------------------------------------- 1 | /* 2 | 9. Palindrome Number 3 | https://leetcode.com/problems/palindrome-number/ 4 | 5 | Determine whether an integer is a palindrome. 6 | An integer is a palindrome when it reads the same backward as forward. 7 | */ 8 | // time: 2018-12-30 9 | 10 | package palindromenumber 11 | 12 | // Time complexity: O(log 10 (n)) 13 | // Space complexity : O(1) 14 | func isPalindrome(x int) bool { 15 | var ( 16 | y int 17 | z = x 18 | ) 19 | 20 | for x > 0 { 21 | y = y*10 + x%10 22 | x /= 10 23 | } 24 | return y == z 25 | } 26 | -------------------------------------------------------------------------------- /solutions/0009_palindrome_number/palindrome_number_test.go: -------------------------------------------------------------------------------- 1 | package palindromenumber 2 | 3 | import "testing" 4 | 5 | func TestIsPalindrome(t *testing.T) { 6 | testCases := []int{121, -121, 10, 0} 7 | expected := []bool{true, false, false, true} 8 | for index, data := range testCases { 9 | if res := isPalindrome(data); res != expected[index] { 10 | t.Errorf("expected %t, got %t", expected[index], res) 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /solutions/0011_container_with_most_water/container_with_most_water_test.go: -------------------------------------------------------------------------------- 1 | package containerwithmostwater 2 | 3 | import "testing" 4 | 5 | func TestMaxArea(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 8, 6, 2, 5, 4, 8, 3, 7}, 8 | {}, 9 | {1}, 10 | {1, 2}, 11 | {2, 3, 5, 7, 8, 9, 5, 3, 2}, 12 | } 13 | expected := []int{49, 0, 0, 1, 20} 14 | for index, data := range testCases { 15 | if res := maxArea(data); res != expected[index] { 16 | t.Errorf("expected %d, got %d", expected[index], res) 17 | } 18 | } 19 | } 20 | 21 | func TestMaxArea1(t *testing.T) { 22 | testCases := [][]int{ 23 | {1, 8, 6, 2, 5, 4, 8, 3, 7}, 24 | {}, 25 | {1}, 26 | {1, 2}, 27 | {2, 3, 5, 7, 8, 9, 5, 3, 2}, 28 | } 29 | expected := []int{49, 0, 0, 1, 20} 30 | for index, data := range testCases { 31 | if res := maxArea1(data); res != expected[index] { 32 | t.Errorf("expected %d, got %d", expected[index], res) 33 | } 34 | } 35 | } 36 | 37 | func TestMaxArea2(t *testing.T) { 38 | testCases := [][]int{ 39 | {1, 8, 6, 2, 5, 4, 8, 3, 7}, 40 | {}, 41 | {1}, 42 | {1, 2}, 43 | {2, 3, 5, 7, 8, 9, 5, 3, 2}, 44 | } 45 | expected := []int{49, 0, 0, 1, 20} 46 | for index, data := range testCases { 47 | if res := maxArea2(data); res != expected[index] { 48 | t.Errorf("expected %d, got %d", expected[index], res) 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /solutions/0013_roman_to_integer/roman_to_integer.go: -------------------------------------------------------------------------------- 1 | /* 2 | 13. Roman to Integer 3 | https://leetcode.com/problems/roman-to-integer/ 4 | */ 5 | // time: 2018-12-31 6 | 7 | package rti 8 | 9 | // time complexity: O(n) 10 | // space complexity: O(1) 11 | func romanToInt(s string) int { 12 | if 0 == len(s) { 13 | return 0 14 | } 15 | 16 | digits := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 17 | sum := digits[s[len(s)-1]] 18 | 19 | for i := len(s) - 1; i > 0; i-- { 20 | cur := digits[s[i]] 21 | pre := digits[s[i-1]] 22 | if cur > pre { 23 | sum -= pre 24 | } else { 25 | sum += pre 26 | } 27 | } 28 | return sum 29 | } 30 | -------------------------------------------------------------------------------- /solutions/0013_roman_to_integer/roman_to_integer_test.go: -------------------------------------------------------------------------------- 1 | package rti 2 | 3 | import "testing" 4 | 5 | func TestRomanToInt(t *testing.T) { 6 | testCases := []string{ 7 | "III", 8 | "IV", 9 | "IX", 10 | "LVIII", 11 | "MCMXCIV", 12 | "", 13 | } 14 | expected := []int{3, 4, 9, 58, 1994, 0} 15 | 16 | for index, s := range testCases { 17 | if res := romanToInt(s); res != expected[index] { 18 | t.Errorf("expected %d, got %d", expected[index], res) 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/0014_longest_common_prefix/lcp.go: -------------------------------------------------------------------------------- 1 | /* 2 | 14. Longest Common Prefix 3 | https://leetcode.com/problems/longest-common-prefix/ 4 | 5 | Write a function to find the longest common prefix string amongst an array of strings. 6 | 7 | If there is no common prefix, return an empty string "". 8 | */ 9 | // time: 2018-12-31 10 | 11 | package lcp 12 | 13 | // time complexity: O(len(strs) * max len of string) 14 | // space complexity: O(1) 15 | func longestCommonPrefix(strs []string) string { 16 | if 0 == len(strs) { 17 | return "" 18 | } 19 | res := "" 20 | for i := 0; i < len(strs[0]); i++ { 21 | c := strs[0][i] 22 | for j := 1; j < len(strs); j++ { 23 | if i >= len(strs[j]) || strs[j][i] != c { 24 | return res 25 | } 26 | } 27 | res += string(c) 28 | } 29 | return res 30 | } 31 | -------------------------------------------------------------------------------- /solutions/0014_longest_common_prefix/lcp_test.go: -------------------------------------------------------------------------------- 1 | package lcp 2 | 3 | import "testing" 4 | 5 | func TestLongestCommonPrefix(t *testing.T) { 6 | testCases := [][]string{ 7 | {"flower", "flow", "flight"}, 8 | {"dog", "racecar", "car"}, 9 | {}, 10 | {""}, 11 | } 12 | 13 | expected := []string{ 14 | "fl", 15 | "", 16 | "", 17 | "", 18 | } 19 | 20 | for index, strs := range testCases { 21 | if res := longestCommonPrefix(strs); res != expected[index] { 22 | t.Errorf("expected %s, got %s", expected[index], res) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /solutions/0015_3Sum/3sum.go: -------------------------------------------------------------------------------- 1 | /* 2 | 15. 3Sum 3 | https://leetcode.com/problems/3sum/ 4 | */ 5 | // time: 2019-03-01 6 | 7 | package threesum 8 | 9 | import "sort" 10 | 11 | // time complexity: O(n^2) 12 | func threeSum(nums []int) [][]int { 13 | sort.Ints(nums) 14 | var res [][]int 15 | for i := 0; i < len(nums)-2; i++ { 16 | if nums[i] > 0 { 17 | break 18 | } 19 | if i > 0 && nums[i] == nums[i-1] { 20 | continue 21 | } 22 | for l, r := i+1, len(nums)-1; l < r; { 23 | if l > i+1 && nums[l] == nums[l-1] { 24 | l++ 25 | continue 26 | } 27 | if r < len(nums)-1 && nums[r] == nums[r+1] { 28 | r-- 29 | continue 30 | } 31 | switch sum := nums[i] + nums[l] + nums[r]; { 32 | case sum < 0: 33 | l++ 34 | case sum > 0: 35 | r-- 36 | default: 37 | res = append(res, []int{nums[i], nums[l], nums[r]}) 38 | l++ 39 | r-- 40 | } 41 | } 42 | } 43 | return res 44 | } 45 | -------------------------------------------------------------------------------- /solutions/0015_3Sum/3sum_test.go: -------------------------------------------------------------------------------- 1 | package threesum 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestThreeSum(t *testing.T) { 9 | testData := [][]int{ 10 | {-1, 0, 1, 2, -6, -4}, 11 | {-7, 3, -7, 3, 4, 5, 6, 6, 4}, 12 | } 13 | expected := [][][]int{ 14 | {{-1, 0, 1}}, 15 | {{-7, 3, 4}}, 16 | } 17 | 18 | for index, nums := range testData { 19 | if res := threeSum(nums); !reflect.DeepEqual(res, expected[index]) { 20 | t.Errorf("expected %v, got %v", expected[index], res) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go: -------------------------------------------------------------------------------- 1 | /* 2 | 17. Letter Combinations of a Phone Number 3 | 4 | Source: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 5 | 6 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. 7 | 8 | A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 9 | 10 | Example: 11 | 12 | Input: "23" 13 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 14 | Note: 15 | 16 | Although the above answer is in lexicographical order, your answer could be in any order you want. 17 | */ 18 | 19 | package lettercombinationsofaphonenumber 20 | 21 | var ( 22 | letterMap = []string{ 23 | " ", 24 | "", 25 | "abc", 26 | "def", 27 | "ghi", 28 | "jkl", 29 | "mno", 30 | "pqrs", 31 | "tuv", 32 | "wxyz", 33 | } 34 | res []string 35 | ) 36 | 37 | // Time complexity: O(2^n) 38 | // Space complexity: O(n) 39 | func letterCombinations(digits string) []string { 40 | res = []string{} 41 | if digits == "" { 42 | return res 43 | } 44 | 45 | findCombinations(digits, 0, "") 46 | return res 47 | } 48 | 49 | func findCombinations(digits string, index int, s string) { 50 | if index == len(digits) { 51 | res = append(res, s) 52 | return 53 | } 54 | 55 | ch := digits[index] 56 | letters := letterMap[ch-'0'] 57 | for _, i := range letters { 58 | findCombinations(digits, index+1, s+string(i)) 59 | } 60 | return 61 | } 62 | -------------------------------------------------------------------------------- /solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number_test.go: -------------------------------------------------------------------------------- 1 | package lettercombinationsofaphonenumber 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestLetterCombinations(t *testing.T) { 9 | testData := []string{ 10 | "23", 11 | "", 12 | } 13 | 14 | expectedData := [][]string{ 15 | {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}, 16 | {}, 17 | } 18 | 19 | for index, digits := range testData { 20 | if res := letterCombinations(digits); !reflect.DeepEqual(res, expectedData[index]) { 21 | t.Errorf("expected %v, got %v", expectedData[index], res) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go: -------------------------------------------------------------------------------- 1 | /* 2 | 19. Remove Nth Node From End of List 3 | https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 4 | 5 | Given a linked list, remove the n-th node from the end of list and return its head. 6 | */ 7 | // time: 2018-12-31 8 | 9 | package rnthnfeol 10 | 11 | // ListNode Definition for singly-linked list. 12 | type ListNode struct { 13 | Val int 14 | Next *ListNode 15 | } 16 | 17 | // time complexity: O(n) 18 | // space complexity: O(1) 19 | func removeNthFromEnd(head *ListNode, n int) *ListNode { 20 | if n <= 0 { 21 | return head 22 | } 23 | dummy := &ListNode{} 24 | dummy.Next = head 25 | 26 | var ( 27 | p = dummy 28 | q = dummy 29 | ) 30 | 31 | for i := 0; i < n; i++ { 32 | q = q.Next 33 | } 34 | 35 | for q.Next != nil { 36 | p = p.Next 37 | q = q.Next 38 | } 39 | 40 | p.Next = p.Next.Next 41 | return dummy.Next 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list_test.go: -------------------------------------------------------------------------------- 1 | package rnthnfeol 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestRemoveNthFromEnd(t *testing.T) { 9 | type arg struct { 10 | head *ListNode 11 | n int 12 | } 13 | 14 | testCase := []arg{ 15 | {head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), n: 2}, 16 | {head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), n: 0}, 17 | } 18 | 19 | expected := []*ListNode{ 20 | createSingleLinkedList([]int{1, 2, 3, 5}), 21 | createSingleLinkedList([]int{1, 2, 3, 4, 5}), 22 | } 23 | 24 | for index, data := range testCase { 25 | if res := removeNthFromEnd(data.head, data.n); !reflect.DeepEqual(res, expected[index]) { 26 | t.Errorf("expected") 27 | } 28 | } 29 | } 30 | 31 | func createSingleLinkedList(arr []int) *ListNode { 32 | head := &ListNode{} 33 | cur := head 34 | 35 | for _, j := range arr { 36 | cur.Next = &ListNode{Val: j} 37 | cur = cur.Next 38 | } 39 | return head.Next 40 | } 41 | -------------------------------------------------------------------------------- /solutions/0020_valid_parentheses/valid_parentheses.go: -------------------------------------------------------------------------------- 1 | /* 2 | 20. Valid Parentheses 3 | 4 | Source: https://leetcode.com/problems/valid-parentheses/ 5 | 6 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 7 | 8 | An input string is valid if: 9 | 10 | 1. Open brackets must be closed by the same type of brackets. 11 | 2. Open brackets must be closed in the correct order. 12 | 13 | Note that an empty string is also considered valid. 14 | 15 | Example 1: 16 | 17 | Input: "()" 18 | Output: true 19 | Example 2: 20 | 21 | Input: "()[]{}" 22 | Output: true 23 | Example 3: 24 | 25 | Input: "(]" 26 | Output: false 27 | Example 4: 28 | 29 | Input: "([)]" 30 | Output: false 31 | Example 5: 32 | 33 | Input: "{[]}" 34 | Output: true 35 | */ 36 | 37 | package validparentheses 38 | 39 | // Time complexity: O(n) 40 | // Space complexity: O(n) 41 | func isValid(s string) bool { 42 | var ( 43 | stacks []rune 44 | mapping = map[rune]rune{')': '(', ']': '[', '}': '{'} 45 | ) 46 | for _, char := range s { 47 | if char == ')' || char == '}' || char == ']' { 48 | var topElement rune 49 | if len(stacks) > 0 { 50 | topElement = stacks[len(stacks)-1] 51 | stacks = stacks[:len(stacks)-1] 52 | } else { 53 | topElement = '#' 54 | } 55 | if mapping[char] != topElement { 56 | return false 57 | } 58 | } else { 59 | stacks = append(stacks, char) 60 | } 61 | } 62 | return len(stacks) == 0 63 | } 64 | -------------------------------------------------------------------------------- /solutions/0020_valid_parentheses/valid_parentheses_test.go: -------------------------------------------------------------------------------- 1 | package validparentheses 2 | 3 | import "testing" 4 | 5 | func TestIsValid(t *testing.T) { 6 | testData := []string{"()", "(((((())))))", "()()()()", "(((((((()", "((()(())))", "", ")(", "}{", "][", "(][)"} 7 | expectedData := []bool{true, true, true, false, true, true, false, false, false, false} 8 | 9 | for i, s := range testData { 10 | result := isValid(s) 11 | if result != expectedData[i] { 12 | t.Error("测试不通过") 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /solutions/0021_merge_two_sorted_lists/mergeTwoLists.go: -------------------------------------------------------------------------------- 1 | /* 2 | 21. Merge Two Sorted Lists 3 | Source: https://leetcode.com/problems/merge-two-sorted-lists/ 4 | 5 | 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. 6 | 7 | Example: 8 | 9 | Input: 1->2->4, 1->3->4 10 | Output: 1->1->2->3->4->4 11 | */ 12 | 13 | package mergetwolists 14 | 15 | // ListNode is node of linked list 16 | type ListNode struct { 17 | Val int 18 | Next *ListNode 19 | } 20 | 21 | // Recursion 22 | // Time complexity: O(len(l1)+len(l2)) 23 | // Space complexity: O(len(l1)+len(l2)) 24 | func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { 25 | if l1 == nil && l2 == nil { 26 | return nil 27 | } 28 | if l1 == nil { 29 | return l2 30 | } 31 | 32 | if l2 == nil { 33 | return l1 34 | } 35 | 36 | if l1.Val < l2.Val { 37 | l1.Next = mergeTwoLists(l1.Next, l2) 38 | return l1 39 | } 40 | l2.Next = mergeTwoLists(l1, l2.Next) 41 | return l2 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0021_merge_two_sorted_lists/mergeTwoLists_test.go: -------------------------------------------------------------------------------- 1 | package mergetwolists 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSingleLinkedList(arr []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | 12 | for _, j := range arr { 13 | cur.Next = &ListNode{Val: j} 14 | cur = cur.Next 15 | } 16 | return head.Next 17 | } 18 | 19 | func TestMergeTwoLists(t *testing.T) { 20 | testDatas := []struct { 21 | name string 22 | arg1 *ListNode 23 | arg2 *ListNode 24 | expected *ListNode 25 | }{ 26 | { 27 | name: "one", 28 | arg1: createSingleLinkedList([]int{1, 3, 5}), 29 | arg2: createSingleLinkedList([]int{2, 4, 6}), 30 | expected: createSingleLinkedList([]int{1, 2, 3, 4, 5, 6}), 31 | }, 32 | { 33 | name: "two", 34 | arg1: createSingleLinkedList([]int{1}), 35 | arg2: createSingleLinkedList([]int{2, 4, 6}), 36 | expected: createSingleLinkedList([]int{1, 2, 4, 6}), 37 | }, 38 | { 39 | name: "three", 40 | arg1: nil, 41 | arg2: nil, 42 | expected: nil, 43 | }, 44 | { 45 | name: "four", 46 | arg1: createSingleLinkedList([]int{2, 4, 6}), 47 | arg2: createSingleLinkedList([]int{1}), 48 | expected: createSingleLinkedList([]int{1, 2, 4, 6}), 49 | }, 50 | } 51 | 52 | for _, testData := range testDatas { 53 | t.Run(testData.name, func(t *testing.T) { 54 | if result := mergeTwoLists(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) { 55 | t.Errorf("mergeTwoLists() = %v, expected %v", result, testData.expected) 56 | } 57 | }) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go: -------------------------------------------------------------------------------- 1 | /* 2 | 24. Swap Nodes in Pairs 3 | https://leetcode.com/problems/swap-nodes-in-pairs/ 4 | 5 | Given a linked list, swap every two adjacent nodes and return its head. 6 | */ 7 | // time: 2019-01-02 8 | 9 | package swapnodesinpairs 10 | 11 | // ListNode Definition for singly-linked list. 12 | type ListNode struct { 13 | Val int 14 | Next *ListNode 15 | } 16 | 17 | // time complexity: O(n/2), where n is len of linked list. 18 | // space complexity: O(1) 19 | func swapPairs(head *ListNode) *ListNode { 20 | dummy := &ListNode{} 21 | dummy.Next = head 22 | cur := dummy 23 | 24 | for cur.Next != nil && cur.Next.Next != nil { 25 | node1 := cur.Next 26 | node2 := node1.Next 27 | node3 := node2.Next 28 | 29 | node2.Next = node1 30 | node1.Next = node3 31 | cur.Next = node2 32 | cur = node1 33 | } 34 | return dummy.Next 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs_test.go: -------------------------------------------------------------------------------- 1 | package swapnodesinpairs 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSwapPairs(t *testing.T) { 9 | head := createSingleList([]int{1, 2, 3, 4}) 10 | expected := createSingleList([]int{2, 1, 4, 3}) 11 | if res := swapPairs(head); !reflect.DeepEqual(res, expected) { 12 | t.Errorf("expected %v, got %v", expected, res) 13 | } 14 | } 15 | 16 | func createSingleList(nums []int) *ListNode { 17 | head := &ListNode{} 18 | cur := head 19 | for _, j := range nums { 20 | cur.Next = &ListNode{Val: j} 21 | cur = cur.Next 22 | } 23 | return head.Next 24 | } 25 | -------------------------------------------------------------------------------- /solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go: -------------------------------------------------------------------------------- 1 | /* 2 | 25. Reverse Nodes in k-Group 3 | 4 | Source: https://leetcode.com/problems/reverse-nodes-in-k-group/ 5 | 6 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 7 | 8 | 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. 9 | 10 | Example: 11 | 12 | Given this linked list: 1->2->3->4->5 13 | 14 | For k = 2, you should return: 2->1->4->3->5 15 | 16 | For k = 3, you should return: 3->2->1->4->5 17 | 18 | Note: 19 | Only constant extra memory is allowed. 20 | You may not alter the values in the list's nodes, only nodes itself may be changed. 21 | */ 22 | 23 | package reversenodesinkgroup 24 | 25 | // ListNode is node of linked list 26 | type ListNode struct { 27 | Val int 28 | Next *ListNode 29 | } 30 | 31 | func reverseKGroup(head *ListNode, k int) *ListNode { 32 | if head == nil || head.Next == nil || k < 2 { 33 | return head 34 | } 35 | 36 | p := new(ListNode) 37 | s := new(ListNode) 38 | l := k 39 | p.Next = head 40 | head = p 41 | s = p 42 | 43 | for s != nil && k != 0 { 44 | s = s.Next 45 | k-- 46 | } 47 | 48 | for s != nil { 49 | reverse(&p, &s) 50 | k = l 51 | for s != nil && k != 0 { 52 | s = s.Next 53 | k-- 54 | } 55 | } 56 | return head.Next 57 | } 58 | 59 | func reverse(p **ListNode, s **ListNode) { 60 | var tmp *ListNode 61 | prev := (*p).Next 62 | tail := (*p).Next 63 | flag := (*s).Next 64 | 65 | (*p).Next = nil 66 | for prev != flag { 67 | tmp = (*p).Next 68 | (*p).Next = prev 69 | prev = prev.Next 70 | (*p).Next.Next = tmp 71 | } 72 | tail.Next = prev 73 | *p = tail 74 | *s = tail 75 | } 76 | -------------------------------------------------------------------------------- /solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group_test.go: -------------------------------------------------------------------------------- 1 | package reversenodesinkgroup 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSingleLinkedList(arr []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | 12 | for _, j := range arr { 13 | cur.Next = &ListNode{Val: j} 14 | cur = cur.Next 15 | } 16 | return head.Next 17 | } 18 | 19 | func TestReverseKGroup(t *testing.T) { 20 | type args struct { 21 | head *ListNode 22 | k int 23 | } 24 | tests := []struct { 25 | name string 26 | args args 27 | expected *ListNode 28 | }{ 29 | { 30 | name: "one", 31 | args: args{ 32 | head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), 33 | k: 2, 34 | }, 35 | expected: createSingleLinkedList([]int{2, 1, 4, 3, 5}), 36 | }, 37 | { 38 | name: "two", 39 | args: args{ 40 | head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), 41 | k: 3, 42 | }, 43 | expected: createSingleLinkedList([]int{3, 2, 1, 4, 5}), 44 | }, 45 | 46 | { 47 | name: "three", 48 | args: args{ 49 | head: createSingleLinkedList([]int{1}), 50 | k: 2, 51 | }, 52 | expected: createSingleLinkedList([]int{1}), 53 | }, 54 | } 55 | for _, data := range tests { 56 | t.Run(data.name, func(t *testing.T) { 57 | if result := reverseKGroup(data.args.head, data.args.k); !reflect.DeepEqual(result, data.expected) { 58 | t.Errorf("reverseKGroup() = %v, expected %v", result, data.expected) 59 | } 60 | }) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go: -------------------------------------------------------------------------------- 1 | /* 2 | 26. Remove Duplicates from Sorted Array 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 4 | 5 | Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | */ 9 | // time: 2018-12-20 10 | 11 | package rdfsa 12 | 13 | // double index 14 | // time complexity: O(n) 15 | // space complexity: O(1) 16 | func removeDuplicates(nums []int) int { 17 | n := len(nums) 18 | 19 | if 0 == n { 20 | return n 21 | } 22 | 23 | var ( 24 | res = 1 25 | i = 1 26 | index = nextDifferentCharacterIndex(nums, 1) // 下一个不重复的地址 27 | ) 28 | 29 | for index < n { 30 | res++ 31 | nums[i] = nums[index] 32 | i++ 33 | index = nextDifferentCharacterIndex(nums, index+1) 34 | } 35 | return res 36 | } 37 | 38 | func nextDifferentCharacterIndex(nums []int, p int) int { 39 | for ; p < len(nums); p++ { 40 | if nums[p] != nums[p-1] { 41 | break 42 | } 43 | } 44 | return p 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0026_remove_duplicates_from_sorted_array/rdfsa_test.go: -------------------------------------------------------------------------------- 1 | package rdfsa 2 | 3 | import "testing" 4 | 5 | func TestRemoveDuplicates(t *testing.T) { 6 | // removeDuplicates([]int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}) 7 | testCases := [][]int{ 8 | {1, 1, 2}, 9 | {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}, 10 | {}, 11 | } 12 | 13 | expected := []int{2, 5, 0} 14 | 15 | for index, data := range testCases { 16 | if res := removeDuplicates(data); expected[index] != res { 17 | t.Errorf("expected %d, got %d", expected[index], res) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/0027_remove_element/remove_element.go: -------------------------------------------------------------------------------- 1 | /* 2 | 27. Remove Element 3 | https://leetcode.com/problems/remove-element/ 4 | 5 | Given an array nums and a value val, remove all instances of that value in-place and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | */ 11 | // time: 2018-12-20 12 | 13 | package removeelement 14 | 15 | // two pointers 16 | // time complexity: O(n) 17 | // space complexity: O(1) 18 | func removeElement(nums []int, val int) int { 19 | x := 0 20 | for j := 0; j < len(nums); j++ { 21 | if nums[j] != val { 22 | if x != j { 23 | nums[x] = nums[j] 24 | } 25 | x++ 26 | } 27 | } 28 | return x 29 | } 30 | 31 | /* 32 | func removeElement1(nums []int, val int) int { 33 | var ( 34 | l int 35 | r = len(nums) 36 | ) 37 | for l < r { 38 | if nums[l] == val { 39 | r-- 40 | nums[l] = nums[r] 41 | } else { 42 | l++ 43 | } 44 | } 45 | return r 46 | } 47 | */ 48 | -------------------------------------------------------------------------------- /solutions/0027_remove_element/remove_element_test.go: -------------------------------------------------------------------------------- 1 | package removeelement 2 | 3 | import "testing" 4 | 5 | func TestRemoveElement(t *testing.T) { 6 | nums := []int{0, 1, 2, 2, 3, 0, 4, 2} 7 | val := 2 8 | expected := 5 9 | 10 | if res := removeElement(nums, val); res != expected { 11 | t.Errorf("expected %d, got %d", expected, res) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /solutions/0028_implement_strstr/implement_strstr.go: -------------------------------------------------------------------------------- 1 | /* 2 | 28. Implement strStr() 3 | https://leetcode.com/problems/implement-strstr/ 4 | 5 | Implement strStr(). 6 | 7 | Return the index of the first occurrence of needle in haystack, 8 | or -1 if needle is not part of haystack. 9 | 10 | clarification: 11 | For the purpose of this problem, we will return 0 when needle is an empty string. 12 | */ 13 | // time: 2019-01-02 14 | 15 | package implstr 16 | 17 | // time complexity: O( (m-n+1)*n ), where m is len(haystack), n is len(needle) 18 | // space complexity: O(1) 19 | func strStr(haystack string, needle string) int { 20 | if 0 == len(needle) { 21 | return 0 22 | } 23 | 24 | for i, j := 0, 0; i <= len(haystack)-len(needle); i++ { 25 | for j = 0; j < len(needle); j++ { 26 | if haystack[i+j] != needle[j] { 27 | break 28 | } 29 | } 30 | if len(needle) == j { 31 | return i 32 | } 33 | } 34 | return -1 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0028_implement_strstr/implement_strstr_test.go: -------------------------------------------------------------------------------- 1 | package implstr 2 | 3 | import "testing" 4 | 5 | func TestStrStr(t *testing.T) { 6 | type arg struct { 7 | haystack string 8 | needle string 9 | } 10 | 11 | testCases := []arg{ 12 | {haystack: "hello", needle: "ll"}, 13 | {haystack: "aaaaa", needle: "bba"}, 14 | {haystack: "hello"}, 15 | } 16 | 17 | expected := []int{2, -1, 0} 18 | for index, data := range testCases { 19 | if res := strStr(data.haystack, data.needle); res != expected[index] { 20 | t.Errorf("expected %d, got %d", expected[index], res) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go: -------------------------------------------------------------------------------- 1 | /* 2 | 33. Search in Rotated Sorted Array 3 | https://leetcode.com/problems/search-in-rotated-sorted-array/ 4 | 5 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 6 | 7 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 8 | 9 | You are given a target value to search. If found in the array return its index, otherwise return -1. 10 | 11 | You may assume no duplicate exists in the array. 12 | 13 | Your algorithm's runtime complexity must be in the order of O(log n). 14 | */ 15 | // time: 2018-12-20 16 | 17 | package searchinrotatedsortedarray 18 | 19 | // binary search 20 | /* 21 | 问题分析: 22 | 二分情况分为三种: 23 | 1.mid在pivot左边,即mid左边部分是有序的。 24 | nums[mid] >= nums[l] && nums[mid] > nums[r] 25 | 此时,只需要比较target是否在左边有序部分。 26 | 2.mid在pivot右边,并且包含pivot,即mid右边是有序的。 27 | nums[mid] < nums[l] && nums[mid] <= nums[r], 28 | 此时,只需要比较target是否在右边有序部分。 29 | 3. 整个array是有序的, 30 | nums[mid] >= nums[l] &&nums[mid] <= nums[r] 31 | 放在第一和第二中情况中处理都可以。 32 | */ 33 | // time complexity: O(logn) 34 | // space complexity: O(1) 35 | func search(nums []int, target int) int { 36 | var ( 37 | l int 38 | r = len(nums) - 1 39 | ) 40 | 41 | for l <= r { 42 | mid := l + (r-l)/2 43 | if target == nums[mid] { 44 | return mid 45 | } 46 | if nums[mid] >= nums[l] && nums[mid] > nums[r] { 47 | if target >= nums[l] && target < nums[mid] { 48 | r = mid - 1 49 | } else { 50 | l = mid + 1 51 | } 52 | } else { 53 | if target > nums[mid] && target <= nums[r] { 54 | l = mid + 1 55 | } else { 56 | r = mid - 1 57 | } 58 | } 59 | } 60 | return -1 61 | } 62 | -------------------------------------------------------------------------------- /solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array_test.go: -------------------------------------------------------------------------------- 1 | package searchinrotatedsortedarray 2 | 3 | import "testing" 4 | 5 | func TestSearch(t *testing.T) { 6 | type arg struct { 7 | nums []int 8 | target int 9 | } 10 | 11 | testCases := []arg{ 12 | {nums: []int{4, 5, 6, 7, 0, 1, 2}, target: 0}, 13 | {nums: []int{4, 5, 6, 7, 0, 1, 2}, target: 3}, 14 | {nums: []int{}, target: 2}, 15 | {nums: []int{4}, target: 4}, 16 | {nums: []int{4, 5, 6, 7, 0}, target: 0}, 17 | {nums: []int{9, 7}, target: 7}, 18 | {nums: []int{1, 3}, target: 3}, 19 | {nums: []int{4, 5, 6, 7, 8, 1, 2}, target: 5}, 20 | } 21 | 22 | expected := []int{4, -1, -1, 0, 4, 1, 1, 1} 23 | 24 | for index, data := range testCases { 25 | if res := search(data.nums, data.target); res != expected[index] { 26 | t.Errorf("expected %d, got %d", expected[index], res) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array_test.go: -------------------------------------------------------------------------------- 1 | package findfirstandlastpositionofelementinsortedarray 2 | 3 | import ( 4 | "reflect" 5 | "runtime" 6 | "testing" 7 | ) 8 | 9 | func TestSearchRange(t *testing.T) { 10 | type arg struct { 11 | nums []int 12 | target int 13 | } 14 | 15 | testCases := []arg{ 16 | { 17 | nums: []int{5, 7, 7, 8, 8, 10}, 18 | target: 8, 19 | }, 20 | { 21 | nums: []int{5, 7, 7, 8, 8, 10}, 22 | target: 6, 23 | }, 24 | { 25 | nums: []int{1}, 26 | target: 1, 27 | }, 28 | { 29 | nums: []int{}, 30 | target: 0, 31 | }, 32 | { 33 | nums: []int{2, 2}, 34 | target: 2, 35 | }, 36 | { 37 | nums: []int{1}, 38 | target: 0, 39 | }, 40 | } 41 | 42 | expected := [][]int{ 43 | {3, 4}, 44 | {-1, -1}, 45 | {0, 0}, 46 | {-1, -1}, 47 | {0, 1}, 48 | {-1, -1}, 49 | } 50 | 51 | testFuncs := []func([]int, int) []int{ 52 | searchRange, 53 | searchRange1, 54 | searchRange2, 55 | } 56 | 57 | for _, testFunc := range testFuncs { 58 | for index, testData := range testCases { 59 | if res := testFunc(testData.nums, testData.target); !reflect.DeepEqual(res, expected[index]) { 60 | t.Errorf("function %s, expected %v, got %v", runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name(), expected[index], res) 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /solutions/0035_search_insert_position/search_insert_position.go: -------------------------------------------------------------------------------- 1 | /* 2 | 35. Search Insert Position 3 | https://leetcode.com/problems/search-insert-position/ 4 | 5 | Given a sorted array and a target value, 6 | return the index if the target is found. 7 | If not, return the index where it would be if it were inserted in order. 8 | 9 | You may assume no duplicates in the array. 10 | */ 11 | // time: 2019-01-02 12 | 13 | package sip 14 | 15 | // binary search 16 | // time complexity: O( log n ) 17 | // space complexity: O(1) 18 | func searchInsert(nums []int, target int) int { 19 | var ( 20 | l int 21 | r = len(nums) - 1 22 | ) 23 | 24 | for l <= r { 25 | mid := l + (r-l)/2 26 | if target == nums[mid] { 27 | return mid 28 | } 29 | if target < nums[mid] { 30 | r = mid - 1 31 | } else { 32 | l = mid + 1 33 | } 34 | } 35 | return l 36 | } 37 | -------------------------------------------------------------------------------- /solutions/0035_search_insert_position/search_insert_position_test.go: -------------------------------------------------------------------------------- 1 | package sip 2 | 3 | import "testing" 4 | 5 | func TestSearchInsert(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 3, 5, 6}, 8 | {1, 3, 5, 6}, 9 | {1, 3, 5, 6}, 10 | {1, 3, 5, 6}, 11 | } 12 | targets := []int{5, 2, 7, 0} 13 | 14 | expected := []int{2, 1, 4, 0} 15 | 16 | for index, nums := range testCases { 17 | if res := searchInsert(nums, targets[index]); res != expected[index] { 18 | t.Errorf("expected %d, got %d", expected[index], res) 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/0048_rotate_image/rotate_image.go: -------------------------------------------------------------------------------- 1 | /* 2 | 48. Rotate Image 3 | https://leetcode.com/problems/rotate-image/ 4 | 5 | You are given an n x n 2D matrix representing an image. 6 | Rotate the image by 90 degrees (clockwise). 7 | 8 | Note: 9 | You have to rotate the image in-place, 10 | which means you have to modify the input 2D matrix directly. 11 | DO NOT allocate another 2D matrix and do the rotation. 12 | */ 13 | // time: 2019-01-02 14 | 15 | package ri 16 | 17 | // time complexity: O(n^2) 18 | // space complexity: O(1) 19 | func rotate(matrix [][]int) { 20 | /* 21 | [ 22 | [1,2,3], 23 | [4,5,6], 24 | [7,8,9] 25 | ] 26 | */ 27 | n := len(matrix) 28 | for i := 0; i < n; i++ { 29 | for j := i + 1; j < n; j++ { 30 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 31 | } 32 | } 33 | /* 34 | [ 35 | [1,4,7], 36 | [2,5,8], 37 | [3,6,9] 38 | ] 39 | */ 40 | for i := 0; i < n; i++ { 41 | for j := 0; j < n/2; j++ { 42 | matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j] 43 | } 44 | } 45 | /* 46 | [ 47 | [7,4,1], 48 | [8,5,2], 49 | [9,6,3] 50 | ] 51 | */ 52 | } 53 | -------------------------------------------------------------------------------- /solutions/0048_rotate_image/rotate_image_test.go: -------------------------------------------------------------------------------- 1 | package ri 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestRotate(t *testing.T) { 9 | matrix := [][]int{ 10 | {5, 1, 9, 11}, 11 | {2, 4, 8, 10}, 12 | {13, 3, 6, 7}, 13 | {15, 14, 12, 16}, 14 | } 15 | 16 | expected := [][]int{ 17 | {15, 13, 2, 5}, 18 | {14, 3, 4, 1}, 19 | {12, 6, 8, 9}, 20 | {16, 7, 10, 11}, 21 | } 22 | 23 | if rotate(matrix); !reflect.DeepEqual(matrix, expected) { 24 | t.Errorf("expected %v, got %v", expected, matrix) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /solutions/0053_maximum_subarray/maximum_subarray.go: -------------------------------------------------------------------------------- 1 | /* 2 | 53. Maximum Subarray 3 | https://leetcode.com/problems/maximum-subarray/ 4 | 5 | Given an integer array nums, 6 | find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 7 | */ 8 | // time: 2019-01-02 9 | 10 | package maximumsubarray 11 | 12 | import ( 13 | "fmt" 14 | "math" 15 | ) 16 | 17 | // time complexity: O(n) 18 | // space complexity: O(1) 19 | func maxSubArray(nums []int) int { 20 | var ( 21 | max = math.MinInt32 22 | sum int 23 | start, end, f int 24 | ) 25 | for i, j := range nums { 26 | sum += j 27 | if sum > max { 28 | if f != 0 { 29 | start = f + 1 30 | f = 0 31 | } 32 | max = sum 33 | end = i 34 | } 35 | if sum < 0 { 36 | f = i 37 | sum = 0 38 | } 39 | } 40 | fmt.Printf("start index is %d, end index is %d\n", start, end) 41 | return max 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0053_maximum_subarray/maximum_subarray_test.go: -------------------------------------------------------------------------------- 1 | package maximumsubarray 2 | 3 | import "testing" 4 | 5 | func TestMaxSubarray(t *testing.T) { 6 | nums := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} 7 | expected := 6 8 | 9 | if res := maxSubArray(nums); res != expected { 10 | t.Errorf("expected %d, got %d", expected, res) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /solutions/0058_length_of_last_word/len_of_last_word.go: -------------------------------------------------------------------------------- 1 | /* 2 | 58. Length of Last Word 3 | https://leetcode.com/problems/length-of-last-word/ 4 | 5 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', 6 | return the length of last word in the string. 7 | If the last word does not exist, return 0. 8 | 9 | Note: A word is defined as a character sequence consists of non-space characters only. 10 | */ 11 | // time: 2019-01-02 12 | 13 | package lenoflastword 14 | 15 | // time complexity: O(n) 16 | // space complexity: O(1) 17 | func lengthOfLastWord(s string) int { 18 | var ( 19 | n = len(s) 20 | cur = n - 1 21 | ) 22 | 23 | for cur >= 0 { 24 | if n-1 == cur && s[cur] == 32 { 25 | cur-- 26 | n-- 27 | continue 28 | } 29 | if s[cur] != 32 { 30 | cur-- 31 | } else { 32 | break 33 | } 34 | } 35 | return n - cur - 1 36 | } 37 | -------------------------------------------------------------------------------- /solutions/0058_length_of_last_word/len_of_last_word_test.go: -------------------------------------------------------------------------------- 1 | package lenoflastword 2 | 3 | import "testing" 4 | 5 | func TestLengthOfLastWord(t *testing.T) { 6 | s := "hello world " 7 | expected := 5 8 | if res := lengthOfLastWord(s); res != expected { 9 | t.Errorf("expected %d, got %d", expected, res) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /solutions/0061_rotate_list/rotate_list.go: -------------------------------------------------------------------------------- 1 | /* 2 | 61. Rotate List 3 | 4 | Source: https://leetcode.com/problems/rotate-list/ 5 | 6 | Given a linked list, rotate the list to the right by k places, where k is non-negative. 7 | 8 | Example 1: 9 | Input: 1->2->3->4->5->NULL, k = 2 10 | Output: 4->5->1->2->3->NULL 11 | Explanation: 12 | rotate 1 steps to the right: 5->1->2->3->4->NULL 13 | rotate 2 steps to the right: 4->5->1->2->3->NULL 14 | 15 | Example 2: 16 | Input: 0->1->2->NULL, k = 4 17 | Output: 2->0->1->NULL 18 | rotate 1 steps to the right: 2->0->1->NULL 19 | Explanation: 20 | rotate 2 steps to the right: 1->2->0->NULL 21 | otate 3 steps to the right: 0->1->2->NULL 22 | rotate 4 steps to the right: 2->0->1->NULL 23 | */ 24 | 25 | package rotatelist 26 | 27 | // ListNode is node of linked list 28 | type ListNode struct { 29 | Val int 30 | Next *ListNode 31 | } 32 | 33 | func rotateRight(head *ListNode, k int) *ListNode { 34 | if k == 0 || head == nil || head.Next == nil { 35 | return head 36 | } 37 | 38 | var ( 39 | listSize int 40 | count int 41 | p = head 42 | rotateNode = head 43 | ) 44 | 45 | for p != nil && count < k { 46 | p = p.Next 47 | listSize++ 48 | count++ 49 | } 50 | 51 | if p == nil { 52 | k = k % listSize 53 | if k == 0 { 54 | return head 55 | } 56 | p = head 57 | for count = 0; count < k; count++ { 58 | p = p.Next 59 | } 60 | } 61 | 62 | for p.Next != nil { 63 | rotateNode = rotateNode.Next 64 | p = p.Next 65 | } 66 | 67 | p.Next = head 68 | head = rotateNode.Next 69 | rotateNode.Next = nil 70 | return head 71 | } 72 | -------------------------------------------------------------------------------- /solutions/0062_unique_paths/unique_paths_test.go: -------------------------------------------------------------------------------- 1 | package uniquepaths 2 | 3 | import "testing" 4 | 5 | func TestUniquePaths(t *testing.T) { 6 | testData := [][2]int{ 7 | {3, 2}, 8 | {51, 9}, 9 | {9, 9}, 10 | } 11 | 12 | expectedData := []int{3, 1916797311, 12870} 13 | 14 | for index, data := range testData { 15 | if res := uniquePaths(data[0], data[1]); res != expectedData[index] { 16 | t.Errorf("expected %d, got %d", expectedData[index], res) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/0063_unique_paths_2/unique_paths2_test.go: -------------------------------------------------------------------------------- 1 | package uniquepaths2 2 | 3 | import "testing" 4 | 5 | func TestUniquePaths2(t *testing.T) { 6 | testData := [][][]int{ 7 | { 8 | {0, 0, 0}, 9 | {0, 1, 0}, 10 | {0, 0, 0}, 11 | }, 12 | { 13 | {0, 0, 0}, 14 | {0, 1, 0}, 15 | {0, 0, 0}, 16 | {0, 1, 0}, 17 | }, 18 | { 19 | {1}, 20 | }, 21 | { 22 | {1, 0}, 23 | }, 24 | } 25 | 26 | expectedData := []int{2, 2, 0, 0} 27 | 28 | for index, data := range testData { 29 | if res := uniquePathsWithObstacles(data); res != expectedData[index] { 30 | t.Errorf("expected %d, got %d", expectedData[index], res) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /solutions/0064_minimum_path_sum/minimum_path_sum_test.go: -------------------------------------------------------------------------------- 1 | package minimumpathsum 2 | 3 | import "testing" 4 | 5 | func TestMininumPathSum(t *testing.T) { 6 | testData := [][][]int{ 7 | { 8 | {1, 3, 1}, 9 | {1, 5, 1}, 10 | {4, 2, 1}, 11 | }, 12 | { 13 | {3, 8, 6, 0, 5, 9, 9, 6, 3, 4, 0, 5, 7, 3, 9, 3}, 14 | {0, 9, 2, 5, 5, 4, 9, 1, 4, 6, 9, 5, 6, 7, 3, 2}, 15 | {8, 2, 2, 3, 3, 3, 1, 6, 9, 1, 1, 6, 6, 2, 1, 9}, 16 | {1, 3, 6, 9, 9, 5, 0, 3, 4, 9, 1, 0, 9, 6, 2, 7}, 17 | {8, 6, 2, 2, 1, 3, 0, 0, 7, 2, 7, 5, 4, 8, 4, 8}, 18 | {4, 1, 9, 5, 8, 9, 9, 2, 0, 2, 5, 1, 8, 7, 0, 9}, 19 | {6, 2, 1, 7, 8, 1, 8, 5, 5, 7, 0, 2, 5, 7, 2, 1}, 20 | {8, 1, 7, 6, 2, 8, 1, 2, 2, 6, 4, 0, 5, 4, 1, 3}, 21 | {9, 2, 1, 7, 6, 1, 4, 3, 8, 6, 5, 5, 3, 9, 7, 3}, 22 | {0, 6, 0, 2, 4, 3, 7, 6, 1, 3, 8, 6, 9, 0, 0, 8}, 23 | {4, 3, 7, 2, 4, 3, 6, 4, 0, 3, 9, 5, 3, 6, 9, 3}, 24 | {2, 1, 8, 8, 4, 5, 6, 5, 8, 7, 3, 7, 7, 5, 8, 3}, 25 | {0, 7, 6, 6, 1, 2, 0, 3, 5, 0, 8, 0, 8, 7, 4, 3}, 26 | {0, 4, 3, 4, 9, 0, 1, 9, 7, 7, 8, 6, 4, 6, 9, 5}, 27 | {6, 5, 1, 9, 9, 2, 2, 7, 4, 2, 7, 2, 2, 3, 7, 2}, 28 | {7, 1, 9, 6, 1, 2, 7, 0, 9, 6, 6, 4, 4, 5, 1, 0}, 29 | {3, 4, 9, 2, 8, 3, 1, 2, 6, 9, 7, 0, 2, 4, 2, 0}, 30 | {5, 1, 8, 8, 4, 6, 8, 5, 2, 4, 1, 6, 2, 2, 9, 7}, 31 | }, 32 | {}, 33 | } 34 | 35 | expectedData := []int{7, 83, 0} 36 | 37 | for index, data := range testData { 38 | if mininumPathSum := minPathSum(data); expectedData[index] != mininumPathSum { 39 | t.Errorf("expected %d, got %d", expectedData[index], mininumPathSum) 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0066_plus_one/plus_one.go: -------------------------------------------------------------------------------- 1 | /* 2 | 66. Plus One 3 | https://leetcode.com/problems/plus-one/ 4 | 5 | Given a non-empty array of digits representing a non-negative integer, 6 | plus one to the integer. 7 | 8 | The digits are stored such that the most significant digit is at the head of the list, 9 | and each element in the array contain a single digit. 10 | 11 | You may assume the integer does not contain any leading zero, except the number 0 itself. 12 | */ 13 | // time: 2019-01-02 14 | 15 | package plusone 16 | 17 | // time complexity: O(n) 18 | // space complexity: O(1) 19 | func plusOne(digits []int) []int { 20 | var ( 21 | carry = 1 22 | index = len(digits) - 1 23 | ) 24 | for index >= 0 { 25 | sum := carry + digits[index] 26 | digits[index] = sum % 10 27 | carry = sum / 10 28 | index-- 29 | } 30 | 31 | if carry > 0 { 32 | digits = append(digits, 0) 33 | copy(digits[1:], digits[0:]) 34 | digits[0] = carry 35 | } 36 | return digits 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0066_plus_one/plus_one_test.go: -------------------------------------------------------------------------------- 1 | package plusone 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestPlusOne(t *testing.T) { 9 | digits := []int{9, 9, 9, 9} 10 | expected := []int{1, 0, 0, 0, 0} 11 | if res := plusOne(digits); !reflect.DeepEqual(expected, res) { 12 | t.Errorf("expected %v, got %v", expected, res) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /solutions/0067_add_binary/add_binary.go: -------------------------------------------------------------------------------- 1 | /* 2 | 67. Add Binary 3 | https://leetcode.com/problems/add-binary/ 4 | 5 | Given two binary strings, return their sum (also a binary string). 6 | The input strings are both non-empty and contains only characters 1 or 0. 7 | 8 | Example: 9 | Input: a = "11", b = "1" 10 | Output: "100" 11 | */ 12 | // time: 2018-12-19 13 | 14 | package addbinary 15 | 16 | import ( 17 | "strconv" 18 | ) 19 | 20 | // Time complexity: O( max( len(a), len(b) ) ) 21 | // Space complexity: O(1) 22 | func addBinary(a string, b string) string { 23 | var ( 24 | lenA = len(a) 25 | lenB = len(b) 26 | carry int 27 | res = "" 28 | ) 29 | for lenA > 0 && lenB > 0 { 30 | tmp := int(a[lenA-1]-'0') + int(b[lenB-1]-'0') + carry 31 | res = strconv.Itoa(tmp%2) + res 32 | carry = tmp / 2 33 | lenA-- 34 | lenB-- 35 | } 36 | 37 | if lenA == 0 { 38 | for lenB > 0 { 39 | tmp := int(b[lenB-1]-'0') + carry 40 | res = strconv.Itoa(tmp%2) + res 41 | carry = tmp / 2 42 | lenB-- 43 | } 44 | } 45 | 46 | if lenB == 0 { 47 | for lenA > 0 { 48 | tmp := int(a[lenA-1]-'0') + carry 49 | res = strconv.Itoa(tmp%2) + res 50 | carry = tmp / 2 51 | lenA-- 52 | } 53 | } 54 | 55 | if carry == 1 { 56 | res = strconv.Itoa(carry) + res 57 | } 58 | return res 59 | } 60 | -------------------------------------------------------------------------------- /solutions/0067_add_binary/add_binary_test.go: -------------------------------------------------------------------------------- 1 | package addbinary 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestAddBinary(t *testing.T) { 8 | type arg struct { 9 | a string 10 | b string 11 | } 12 | 13 | testCases := []arg{ 14 | { 15 | a: "11", 16 | b: "1", 17 | }, 18 | { 19 | b: "11", 20 | a: "1", 21 | }, 22 | } 23 | 24 | expected := []string{ 25 | "100", "100", 26 | } 27 | 28 | for index, data := range testCases { 29 | if res := addBinary(data.a, data.b); res != expected[index] { 30 | t.Errorf("expected %s, got %s", expected[index], res) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /solutions/0069_sqrtx/sqrtx.go: -------------------------------------------------------------------------------- 1 | /* 2 | 69. Sqrt(x) 3 | https://leetcode.com/problems/sqrtx/ 4 | 5 | Implement int sqrt(int x). 6 | 7 | Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 8 | 9 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 10 | */ 11 | 12 | // time: 2018-12-20 13 | 14 | package sqrtx 15 | 16 | // binary search 17 | // time complexity: O(logn) 18 | // space complexity: O(1) 19 | func mySqrt(x int) int { 20 | var ( 21 | l int 22 | r = x // 在0~x范围内寻找平凡根 23 | ) 24 | 25 | for l <= r { 26 | mid := l + (r-l)>>1 //位运算更高效 27 | if mid*mid == x { 28 | return mid 29 | } 30 | 31 | if mid*mid < x { 32 | if (mid+1)*(mid+1) > x { 33 | return mid // 返回整数部分 34 | } 35 | l = mid + 1 36 | } else { 37 | r = mid - 1 38 | } 39 | } 40 | return x // 不会执行,如果x为负数,会执行到此处,但是不符合题目要求。 41 | } 42 | -------------------------------------------------------------------------------- /solutions/0069_sqrtx/sqrtx_test.go: -------------------------------------------------------------------------------- 1 | package sqrtx 2 | 3 | import "testing" 4 | 5 | func TestMySqrt(t *testing.T) { 6 | testCases := []int{66, 99, 9} 7 | expected := []int{8, 9, 3} 8 | 9 | for index, data := range testCases { 10 | if res := mySqrt(data); res != expected[index] { 11 | t.Errorf("expected %d, got %d", expected[index], res) 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /solutions/0070_climbing_stairs/climbing_stairs.go: -------------------------------------------------------------------------------- 1 | /* 2 | 70. Climbing Stairs 3 | 4 | source:https://leetcode.com/problems/climbing-stairs/ 5 | 6 | You are climbing a stair case. It takes n steps to reach to the top. 7 | 8 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 9 | 10 | Note: Given n will be a positive integer. 11 | 12 | Example 1: 13 | 14 | Input: 2 15 | Output: 2 16 | Explanation: There are two ways to climb to the top. 17 | 1. 1 step + 1 step 18 | 2. 2 steps 19 | Example 2: 20 | 21 | Input: 3 22 | Output: 3 23 | Explanation: There are three ways to climb to the top. 24 | 1. 1 step + 1 step + 1 step 25 | 2. 1 step + 2 steps 26 | 3. 2 steps + 1 step 27 | */ 28 | 29 | package climbingstairs 30 | 31 | // recursion 32 | /* 33 | func climbStairs(n int) int { 34 | // if n == 1 { 35 | // return 1 36 | // } 37 | // if n == 2 { 38 | // return 2 39 | // } 40 | // 41 | 42 | if n == 1 || n == 0 { 43 | return 1 44 | } 45 | 46 | return climbStairs(n-1) + climbStairs(n-2) 47 | } 48 | */ 49 | 50 | // memory search 51 | /* 52 | func climbStairs(n int) int { 53 | var memo []int 54 | for i := 0; i <= n; i++ { 55 | memo = append(memo, -1) 56 | } 57 | return calcWays(n, memo) 58 | } 59 | 60 | func calcWays(n int, memo []int) int { 61 | if n == 0 || n == 1 { 62 | return 1 63 | } 64 | 65 | if memo[n] == -1 { 66 | memo[n] = calcWays(n-1, memo) + calcWays(n-2, memo) 67 | } 68 | 69 | return memo[n] 70 | } 71 | */ 72 | 73 | // dynamic programming 74 | func climbStairs(n int) int { 75 | var memo = []int{1, 1} 76 | for i := 2; i <= n; i++ { 77 | memo = append(memo, memo[i-1]+memo[i-2]) 78 | } 79 | return memo[n] 80 | } 81 | -------------------------------------------------------------------------------- /solutions/0070_climbing_stairs/climbing_stairs_test.go: -------------------------------------------------------------------------------- 1 | package climbingstairs 2 | 3 | import "testing" 4 | 5 | func TestClimbStairs(t *testing.T) { 6 | testDatas := []int{0, 1, 2, 3, 34} 7 | expected := []int{1, 1, 2, 3, 9227465} 8 | 9 | for i, data := range testDatas { 10 | if steps := climbStairs(data); steps != expected[i] { 11 | t.Errorf("expected %d, got %d", expected[i], steps) 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /solutions/0075_sort_colors/sort_colors.go: -------------------------------------------------------------------------------- 1 | /* 2 | 75. Sort Colors 3 | https://leetcode.com/problems/sort-colors/ 4 | 5 | Given an array with n objects colored red, white or blue, 6 | sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. 7 | 8 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 9 | 10 | Note: You are not suppose to use the library's sort function for this problem. 11 | */ 12 | 13 | // time: 2018-12-21 14 | 15 | package sortcolors 16 | 17 | // 计数排序 18 | // time complexity: O(n) 19 | // space complexity: O(1) 20 | func sortColorsCountSort(nums []int) { 21 | var count = [3]int{} 22 | 23 | for _, num := range nums { 24 | count[num]++ 25 | } 26 | 27 | index := 0 28 | 29 | for i, j := range count { 30 | for k := 0; k < j; k++ { 31 | nums[index] = i 32 | index++ 33 | } 34 | } 35 | } 36 | 37 | // quick sort 3 ways 38 | // time complexity: O(n) 39 | // space complexity: O(1) 40 | func sortColorsQuickSort3Ways(nums []int) { 41 | var ( 42 | zero = -1 43 | two = len(nums) 44 | ) 45 | 46 | for i := 0; i < two; { 47 | if 1 == nums[i] { 48 | i++ 49 | } else if 2 == nums[i] { 50 | two-- 51 | nums[i], nums[two] = nums[two], nums[i] 52 | } else { // nums[i] == 0 53 | zero++ 54 | nums[i], nums[zero] = nums[zero], nums[i] 55 | i++ 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /solutions/0075_sort_colors/sort_colors_test.go: -------------------------------------------------------------------------------- 1 | package sortcolors 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSortColorsCountSort(t *testing.T) { 9 | nums := []int{2, 0, 2, 1, 1, 0} 10 | expected := []int{0, 0, 1, 1, 2, 2} 11 | 12 | sortColorsCountSort(nums) 13 | 14 | if !reflect.DeepEqual(nums, expected) { 15 | t.Errorf("expected %v, got %v", expected, nums) 16 | } 17 | } 18 | func TestSortColorsQuickSort3Ways(t *testing.T) { 19 | nums := []int{2, 0, 2, 1, 1, 0} 20 | expected := []int{0, 0, 1, 1, 2, 2} 21 | 22 | sortColorsQuickSort3Ways(nums) 23 | 24 | if !reflect.DeepEqual(nums, expected) { 25 | t.Errorf("expected %v, got %v", expected, nums) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0076_minimum_window_substring/minimum_window_substring.go: -------------------------------------------------------------------------------- 1 | /* 2 | 76. Minimum Window Substring 3 | https://leetcode.com/problems/minimum-window-substring/ 4 | 5 | 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). 6 | 7 | Example: 8 | Input: S = "ADOBECODEBANC", T = "ABC" 9 | Output: "BANC" 10 | 11 | Note: 12 | 1. If there is no such window in S that covers all characters in T, return the empty string "". 13 | 2. If there is such window, you are guaranteed that there will always be only one unique minimum window in S. 14 | */ 15 | 16 | package minimumwindowsubstring 17 | 18 | import "leetcode/utils" 19 | 20 | /* 21 | 使用滑动窗口解决这一问题,使用map或者slice统计T字符串中的字母的个数,之后,开始遍历S字符串,对于S中遍历到 22 | 的每一个字母,都在map或者slice中的对应个数减一,如果减一后仍然大于等于0,说明当前遍历到的字母是T中的字母, 23 | 使用计数器count,使其加一,当count和T串字母个数相等时,说明此时的窗口已经包含了T串中的所有字母,此时记录 24 | 一下字串和字串长度, 25 | 然后开始收缩左边界,由于我们遍历的时候,对应值减了1,所以此时去除字母的时候,就要把减去的1加回来, 26 | 此时如果加1后的值大于0了,说明此时我们少了一个T中的字母,那么count值就要减1了,然后移动左边界left。 27 | */ 28 | 29 | // sliding window 30 | // Time complexity: O(n) 31 | // Space complexity: O(128) = O(1) 32 | func minWindow(s string, t string) string { 33 | var ( 34 | res string 35 | letterCount = make([]int, 128) 36 | left int 37 | count int 38 | minLen = utils.MaxInt 39 | ) 40 | 41 | for i := 0; i < len(t); i++ { 42 | letterCount[t[i]]++ 43 | } 44 | 45 | for i := 0; i < len(s); i++ { 46 | if letterCount[s[i]]--; letterCount[s[i]] >= 0 { 47 | count++ 48 | } 49 | 50 | for count == len(t) { 51 | if minLen > i-left+1 { 52 | minLen = i - left + 1 53 | res = s[left : minLen+left] 54 | } 55 | if letterCount[s[left]]++; letterCount[s[left]] > 0 { 56 | count-- 57 | } 58 | left++ 59 | } 60 | } 61 | return res 62 | } 63 | -------------------------------------------------------------------------------- /solutions/0076_minimum_window_substring/minimum_window_substring_test.go: -------------------------------------------------------------------------------- 1 | package minimumwindowsubstring 2 | 3 | import "testing" 4 | 5 | func TestMinWindow(t *testing.T) { 6 | s := "ADOBECODEBANC" 7 | l := "ABC" 8 | expected := "BANC" 9 | 10 | if res := minWindow(s, l); res != expected { 11 | t.Errorf("expected %s, got %s", expected, res) 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /solutions/0077_combinations/combinations.go: -------------------------------------------------------------------------------- 1 | /* 2 | 77. Combinations 3 | https://leetcode.com/problems/combinations/ 4 | 5 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 6 | */ 7 | // time: 2019-01-04 8 | 9 | package combinations 10 | 11 | // backtracking 12 | // time complexity: O(n^k) 13 | // space complexity: O(k) 14 | func combine(n int, k int) [][]int { 15 | if n <= 0 || k <= 0 || k > n { 16 | return [][]int{} 17 | } 18 | res := make([][]int, 0) 19 | c := make([]int, 0, k) 20 | generateCombinations(n, k, 1, c, &res) 21 | return res 22 | } 23 | 24 | // 求解C(n,k), 当前已经找到的组合存储在c中,需要从start开始搜索新元素。 25 | func generateCombinations(n, k, start int, c []int, res *[][]int) { 26 | if len(c) == k { 27 | cpy := make([]int, k) 28 | copy(cpy, c) 29 | *res = append(*res, cpy) 30 | return 31 | } 32 | // 回朔法剪枝。 33 | // 还有k - len(c)个空位,所以, [i...n]中至少要有k - len(c)个元素 34 | // i最多为n-(k-len(c))+1 35 | for i := start; i <= n-(k-len(c))+1; i++ { 36 | c = append(c, i) 37 | generateCombinations(n, k, i+1, c, res) 38 | c = c[:len(c)-1] 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /solutions/0077_combinations/combinations_test.go: -------------------------------------------------------------------------------- 1 | package combinations 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestCombine(t *testing.T) { 9 | type arg struct { 10 | n, k int 11 | } 12 | 13 | testCases := []arg{ 14 | {n: 0, k: 2}, 15 | {n: 2, k: 0}, 16 | {n: 1, k: 5}, 17 | {n: 4, k: 2}, 18 | } 19 | expected := [][][]int{ 20 | {}, 21 | {}, 22 | {}, 23 | {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}, 24 | } 25 | 26 | for index, data := range testCases { 27 | if res := combine(data.n, data.k); !reflect.DeepEqual(res, expected[index]) { 28 | t.Errorf("expected %v, got %v", expected[index], res) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/0079_word_search/word_search.go: -------------------------------------------------------------------------------- 1 | /* 2 | 79. Word Search 3 | https://leetcode.com/problems/word-search/ 4 | 5 | Given a 2D board and a word, find if the word exists in the grid. 6 | The word can be constructed from letters of sequentially adjacent cell, 7 | where "adjacent" cells are those horizontally or vertically neighboring. 8 | The same letter cell may not be used more than once. 9 | */ 10 | // 2019-01-04 11 | 12 | package wordsearch 13 | 14 | var ( 15 | d = [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} 16 | m, n int 17 | visited [][]bool 18 | ) 19 | 20 | // backtracking 21 | // time complexity: O(m*n*m*n) 22 | // space complexity: O(m*n) 23 | func exist(board [][]byte, word string) bool { 24 | m = len(board) 25 | n = len(board[0]) 26 | visited = make([][]bool, m) 27 | for i := 0; i < m; i++ { 28 | visited[i] = make([]bool, n) 29 | } 30 | for i := 0; i < len(board); i++ { 31 | for j := 0; j < len(board[i]); j++ { 32 | if searchWord(board, word, 0, i, j) { 33 | return true 34 | } 35 | } 36 | } 37 | return false 38 | } 39 | 40 | func searchWord(board [][]byte, word string, index, startX, startY int) bool { 41 | if len(word)-1 == index { 42 | return board[startX][startY] == word[index] 43 | } 44 | if board[startX][startY] == word[index] { 45 | visited[startX][startY] = true 46 | // 从startX, startY开始,向四个方向寻找 47 | for i := 0; i < 4; i++ { 48 | newX := startX + d[i][0] 49 | newY := startY + d[i][1] 50 | if inArea(newX, newY) && !visited[newX][newY] && searchWord(board, word, index+1, newX, newY) { 51 | return true 52 | } 53 | } 54 | visited[startX][startY] = false 55 | } 56 | return false 57 | } 58 | 59 | func inArea(x, y int) bool { 60 | return x >= 0 && x < m && y >= 0 && y < n 61 | } 62 | -------------------------------------------------------------------------------- /solutions/0079_word_search/word_search_test.go: -------------------------------------------------------------------------------- 1 | package wordsearch 2 | 3 | import "testing" 4 | 5 | func TestExist(t *testing.T) { 6 | board := [][]byte{ 7 | {'A', 'B', 'C', 'E'}, 8 | {'S', 'F', 'C', 'S'}, 9 | {'A', 'D', 'E', 'E'}, 10 | } 11 | testCases := []string{ 12 | "ABCCED", 13 | "SEE", 14 | "ABCB", 15 | } 16 | expected := []bool{true, true, false} 17 | for index, word := range testCases { 18 | if res := exist(board, word); res != expected[index] { 19 | t.Errorf("expected %t, got %t", expected[index], res) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 80. Remove Duplicates from Sorted Array II 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 4 | 5 | Given a sorted array nums, remove the duplicates in-place such that 6 | duplicates appeared at most twice and return the new length. 7 | 8 | Do not allocate extra space for another array, you must do this 9 | by modifying the input array in-place with O(1) extra memory. 10 | */ 11 | // time: 2018-12-21 12 | 13 | package rdfsa2 14 | 15 | // double index 16 | // time complexity: O(n) 17 | // space complexity: O(1) 18 | func removeDuplicates(nums []int) int { 19 | n := len(nums) 20 | if 0 == n || 1 == n { 21 | return n 22 | } 23 | 24 | var ( 25 | res = 2 26 | i = 2 27 | index = nextDifferentCharacterIndex(nums, i, 2) // 寻找下一个满足条件的下标 28 | ) 29 | 30 | for index < n { 31 | res++ 32 | nums[i] = nums[index] 33 | i++ 34 | index = nextDifferentCharacterIndex(nums, i, index+1) 35 | } 36 | return res 37 | } 38 | 39 | func nextDifferentCharacterIndex(nums []int, j int, p int) int { 40 | for ; p < len(nums); p++ { 41 | if nums[j-1] == nums[j-2] && nums[p] != nums[j-1] || nums[j-1] != nums[j-2] { 42 | break 43 | } 44 | } 45 | return p 46 | } 47 | -------------------------------------------------------------------------------- /solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2_test.go: -------------------------------------------------------------------------------- 1 | package rdfsa2 2 | 3 | import "testing" 4 | 5 | func TestRemoveDuplicates(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 1, 1, 2, 2, 3}, 8 | {1, 2, 2}, 9 | {0, 0, 1, 1, 1, 1, 2, 3, 3}, 10 | {}, 11 | {1}, 12 | {2, 2}, 13 | {2, 2, 2}, 14 | } 15 | expected := []int{5, 3, 7, 0, 1, 2, 2} 16 | 17 | for index, data := range testCases { 18 | if res := removeDuplicates(data); res != expected[index] { 19 | t.Errorf("expected %d, got %d", expected[index], res) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go: -------------------------------------------------------------------------------- 1 | /* 2 | 82. Remove Duplicates from Sorted List II 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 4 | 5 | Given a sorted linked list, delete all nodes that have duplicate numbers, 6 | leaving only distinct numbers from the original list. 7 | */ 8 | // time: 2019-01-04 9 | 10 | package rdfsl 11 | 12 | // ListNode Definition for singly-linked list. 13 | type ListNode struct { 14 | Val int 15 | Next *ListNode 16 | } 17 | 18 | // time complexity: O(n) 19 | // space complexity: O(1) 20 | func deleteDuplicates(head *ListNode) *ListNode { 21 | dummyHead := &ListNode{} 22 | dummyHead.Next = head 23 | 24 | pre := dummyHead 25 | cur := head 26 | 27 | for cur != nil && cur.Next != nil { 28 | if cur.Val == cur.Next.Val { 29 | num := cur.Val 30 | for cur != nil && cur.Val == num { 31 | cur = cur.Next 32 | } 33 | pre.Next = cur 34 | } else { 35 | pre = cur 36 | cur = cur.Next 37 | } 38 | } 39 | return dummyHead.Next 40 | } 41 | -------------------------------------------------------------------------------- /solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl_test.go: -------------------------------------------------------------------------------- 1 | package rdfsl 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestDeleteDuplicates(t *testing.T) { 9 | testCases := []*ListNode{ 10 | createSingleLinkedList([]int{1, 2, 3, 3, 4, 4, 5}), 11 | createSingleLinkedList([]int{1, 1, 1, 2, 3}), 12 | } 13 | 14 | expected := []*ListNode{ 15 | createSingleLinkedList([]int{1, 2, 5}), 16 | createSingleLinkedList([]int{2, 3}), 17 | } 18 | 19 | for index, head := range testCases { 20 | if res := deleteDuplicates(head); !reflect.DeepEqual(res, expected[index]) { 21 | t.Errorf("expected %v, got %v", expected[index], res) 22 | } 23 | } 24 | } 25 | 26 | func createSingleLinkedList(nums []int) *ListNode { 27 | head := &ListNode{} 28 | cur := head 29 | for _, num := range nums { 30 | cur.Next = &ListNode{Val: num} 31 | cur = cur.Next 32 | } 33 | return head.Next 34 | } 35 | -------------------------------------------------------------------------------- /solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go: -------------------------------------------------------------------------------- 1 | /* 2 | 83. Remove Duplicates from Sorted List 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 4 | 5 | Given a sorted linked list, delete all duplicates such that each element appear only once. 6 | */ 7 | 8 | package rdfsl 9 | 10 | // ListNode Definition for singly-linked list. 11 | type ListNode struct { 12 | Val int 13 | Next *ListNode 14 | } 15 | 16 | // time complexity: O(n) 17 | // space complexity: O(1) 18 | func deleteDuplicates(head *ListNode) *ListNode { 19 | if head == nil || head.Next == nil { 20 | return head 21 | } 22 | 23 | var ( 24 | pre = head 25 | cur = head.Next 26 | ) 27 | 28 | for cur != nil { 29 | if cur.Val == pre.Val { 30 | pre.Next = cur.Next 31 | cur = cur.Next 32 | } else { 33 | pre = cur 34 | cur = cur.Next 35 | } 36 | } 37 | return head 38 | } 39 | -------------------------------------------------------------------------------- /solutions/0083_remove_duplicates_from_sorted_list/rdfsl_test.go: -------------------------------------------------------------------------------- 1 | package rdfsl 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSingleLinkedList(nums []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | 12 | for _, num := range nums { 13 | cur.Next = &ListNode{Val: num} 14 | cur = cur.Next 15 | } 16 | return head.Next 17 | } 18 | 19 | func TestDeleteDuplicates(t *testing.T) { 20 | testCases := []*ListNode{ 21 | createSingleLinkedList([]int{1, 1, 2}), 22 | createSingleLinkedList([]int{1, 1, 2, 3, 3}), 23 | nil, 24 | } 25 | expected := []*ListNode{ 26 | createSingleLinkedList([]int{1, 2}), 27 | createSingleLinkedList([]int{1, 2, 3}), 28 | nil, 29 | } 30 | for index, head := range testCases { 31 | if res := deleteDuplicates(head); !reflect.DeepEqual(res, expected[index]) { 32 | t.Errorf("expected %v, got %v", expected[index], res) 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0086_partition_list/partition_list.go: -------------------------------------------------------------------------------- 1 | /* 2 | 86. Partition List 3 | https://leetcode.com/problems/partition-list/ 4 | 5 | Given a linked list and a value x, 6 | partition it such that all nodes less than x come before nodes greater than or equal to x. 7 | 8 | You should preserve the original relative order of the nodes in each of the two partitions. 9 | */ 10 | // time: 2019-01-04 11 | 12 | package partitionlist 13 | 14 | // ListNode Definition for singly-linked list. 15 | type ListNode struct { 16 | Val int 17 | Next *ListNode 18 | } 19 | 20 | // time complexity: O(n) 21 | // space complexity: O(1) 22 | func partition(head *ListNode, x int) *ListNode { 23 | var ( 24 | dummyHead1 = &ListNode{} 25 | dummyHead2 = &ListNode{} 26 | cur1 = dummyHead1 27 | cur2 = dummyHead2 28 | ) 29 | 30 | for cur := head; cur != nil; { 31 | if cur.Val < x { 32 | cur1.Next = cur 33 | cur1 = cur1.Next 34 | cur = cur.Next 35 | cur1.Next = nil 36 | } else { 37 | cur2.Next = cur 38 | cur2 = cur2.Next 39 | cur = cur.Next 40 | cur2.Next = nil 41 | } 42 | } 43 | cur1.Next = dummyHead2.Next 44 | return dummyHead1.Next 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0086_partition_list/partition_list_test.go: -------------------------------------------------------------------------------- 1 | package partitionlist 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSingleLinkedList(nums []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | 12 | for _, num := range nums { 13 | cur.Next = &ListNode{Val: num} 14 | cur = cur.Next 15 | } 16 | return head.Next 17 | } 18 | 19 | func TestDeleteDuplicates(t *testing.T) { 20 | testCase := createSingleLinkedList([]int{1, 4, 3, 2, 5, 2}) 21 | 22 | expected := createSingleLinkedList([]int{1, 2, 2, 4, 3, 5}) 23 | x := 3 24 | if res := partition(testCase, x); !reflect.DeepEqual(res, expected) { 25 | t.Errorf("expected %v, got %v", expected, res) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0088_merge_sorted_array/msa.go: -------------------------------------------------------------------------------- 1 | /* 2 | 88. Merge Sorted Array 3 | https://leetcode.com/problems/merge-sorted-array/ 4 | 5 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 6 | 7 | Note: 8 | 1. The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | 2. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 10 | */ 11 | 12 | // time: 2018-12-21 13 | 14 | package msa 15 | 16 | // standard merge process in merge sort 17 | // time complexity: O(n+m) 18 | // space complexity: O(1) 19 | func merge(nums1 []int, m int, nums2 []int, n int) { 20 | for i := n + m - 1; i >= n; i-- { 21 | nums1[i] = nums1[i-n] 22 | } 23 | 24 | var ( 25 | i = n // pointer for nums1 [n, n+m) 26 | j = 0 // pointer for nums2 [0, n) 27 | k = 0 // pointer for merged nums1 [0, n+m) 28 | ) 29 | 30 | for k < n+m { 31 | if i >= n+m { 32 | nums1[k] = nums2[j] 33 | k++ 34 | j++ 35 | } else if j >= n { 36 | break 37 | // nums1[k] = nums1[i] 38 | // k++ 39 | // i++ 40 | } else if nums1[i] < nums2[j] { 41 | nums1[k] = nums1[i] 42 | i++ 43 | k++ 44 | } else { //nums1[i] >= nums2[j] 45 | nums1[k] = nums2[j] 46 | k++ 47 | j++ 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /solutions/0088_merge_sorted_array/msa_test.go: -------------------------------------------------------------------------------- 1 | package msa 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestMerge(t *testing.T) { 9 | type arg struct { 10 | nums1 []int 11 | m int 12 | nums2 []int 13 | n int 14 | } 15 | testCases := []arg{ 16 | {nums1: []int{1, 2, 3, 7, 0, 0, 0}, m: 4, nums2: []int{2, 5, 6}, n: 3}, 17 | {nums1: []int{2, 5, 6, 0, 0, 0}, m: 3, nums2: []int{7, 8, 9}, n: 3}, 18 | } 19 | 20 | expected := [][]int{{1, 2, 2, 3, 5, 6, 7}, {2, 5, 6, 7, 8, 9}} 21 | 22 | for index, data := range testCases { 23 | if merge(data.nums1, data.m, data.nums2, data.n); !reflect.DeepEqual(expected[index], data.nums1) { 24 | t.Errorf("expected %v, got %v", expected[index], data.nums1) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0092_reverse_linked_list_2/reverse_linked_list2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 92. Reverse Linked List II 3 | https://leetcode.com/problems/reverse-linked-list-ii/ 4 | 5 | Reverse a linked list from position m to n. Do it in one-pass. 6 | Note: 1 ≤ m ≤ n ≤ length of list. 7 | */ 8 | // time: 2019-01-04 9 | 10 | package reverselinkedlist2 11 | 12 | // ListNode Definition for singly-linked list. 13 | type ListNode struct { 14 | Val int 15 | Next *ListNode 16 | } 17 | 18 | // time complexity: O(n-m) 19 | // space complexity: O(1) 20 | func reverseBetween(head *ListNode, m, n int) *ListNode { 21 | var ( 22 | dummy = &ListNode{} 23 | p = dummy 24 | s = p 25 | ) 26 | dummy.Next = head 27 | 28 | // 1 ≤ m ≤ n ≤ length of list. 29 | for s != nil && n > 0 { 30 | s = s.Next 31 | n-- 32 | } 33 | for s != nil && m > 1 { 34 | p = p.Next 35 | m-- 36 | } 37 | reverse(&p, &s) 38 | return dummy.Next 39 | } 40 | 41 | func reverse(p, s **ListNode) { 42 | var ( 43 | tmp *ListNode 44 | prev = (*p).Next 45 | tail = (*p).Next 46 | flag = (*s).Next 47 | ) 48 | (*p).Next = nil 49 | for prev != flag { 50 | tmp = (*p).Next 51 | (*p).Next = prev 52 | prev = prev.Next 53 | (*p).Next.Next = tmp 54 | } 55 | tail.Next = prev 56 | /* 57 | 1->2->3->4->5 58 | 1->3->2->4->5 59 | 1->4->3->2->5 60 | 1->5->4->3->2 61 | */ 62 | } 63 | -------------------------------------------------------------------------------- /solutions/0092_reverse_linked_list_2/reverse_linked_list2_test.go: -------------------------------------------------------------------------------- 1 | package reverselinkedlist2 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSingleList(nums []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | for _, num := range nums { 12 | cur.Next = &ListNode{Val: num} 13 | cur = cur.Next 14 | } 15 | return head.Next 16 | } 17 | 18 | func TestReverseBetween(t *testing.T) { 19 | head := createSingleList([]int{1, 2, 3, 4, 5}) 20 | m := 2 21 | n := 4 22 | expected := createSingleList([]int{1, 4, 3, 2, 5}) 23 | 24 | if res := reverseBetween(head, m, n); !reflect.DeepEqual(res, expected) { 25 | t.Errorf("expected %v, got %v", expected, res) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go: -------------------------------------------------------------------------------- 1 | /* 2 | 94. Binary Tree Inorder Traversal 3 | source: https://leetcode.com/problems/binary-tree-inorder-traversal/ 4 | 5 | Given a binary tree, return the inorder traversal of its nodes' values. 6 | 7 | Example: 8 | 9 | Input: [1,null,2,3] 10 | 1 11 | \ 12 | 2 13 | / 14 | 3 15 | 16 | Output: [1,3,2] 17 | Follow up: Recursive solution is trivial, could you do it iteratively? 18 | */ 19 | 20 | package binarytreeinordertraversal 21 | 22 | // TreeNode binary tree node. 23 | type TreeNode struct { 24 | Val int 25 | Left *TreeNode 26 | Right *TreeNode 27 | } 28 | 29 | func inorderTraversal(root *TreeNode) []int { 30 | res := make([]int, 0, 1) 31 | inorderTraversalHelp(root, &res) 32 | return res 33 | } 34 | 35 | func inorderTraversalHelp(root *TreeNode, res *[]int) { 36 | if root == nil { 37 | return 38 | } 39 | inorderTraversalHelp(root.Left, res) 40 | *res = append(*res, root.Val) 41 | inorderTraversalHelp(root.Right, res) 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal_test.go: -------------------------------------------------------------------------------- 1 | package binarytreeinordertraversal 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []int) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []int, index int) *TreeNode { 13 | if index >= len(nums) { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{Val: nums[index]} 18 | tree.Left = performCreate(nums, 2*index+1) 19 | tree.Right = performCreate(nums, 2*index+2) 20 | return &tree 21 | } 22 | 23 | func TestInorderTraversal(t *testing.T) { 24 | testData := [][]int{ 25 | {1, 2, 3}, 26 | } 27 | expectedData := [][]int{ 28 | {2, 1, 3}, 29 | } 30 | 31 | for index, data := range testData { 32 | if res := inorderTraversal(createBinaryTree(data)); !reflect.DeepEqual(res, expectedData[index]) { 33 | t.Errorf("expected %v, got %v", expectedData[index], res) 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /solutions/0100_same_tree/same_tree.go: -------------------------------------------------------------------------------- 1 | /* 2 | 100. Same Tree 3 | https://leetcode.com/problems/same-tree/ 4 | 5 | Given two binary trees, write a function to check if they are the same or not. 6 | 7 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 8 | 9 | */ 10 | 11 | package sametree 12 | 13 | // TreeNode binary tree node. 14 | type TreeNode struct { 15 | Val int 16 | Left *TreeNode 17 | Right *TreeNode 18 | } 19 | 20 | func isSameTree(p *TreeNode, q *TreeNode) bool { 21 | if p == nil { 22 | return q == nil 23 | } 24 | if q == nil { 25 | return p == nil 26 | } 27 | if p.Val == q.Val { 28 | return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) 29 | } 30 | return false 31 | } 32 | -------------------------------------------------------------------------------- /solutions/0100_same_tree/same_tree_test.go: -------------------------------------------------------------------------------- 1 | package sametree 2 | 3 | import "testing" 4 | 5 | type arg struct { 6 | p []int 7 | q []int 8 | } 9 | 10 | func createBinaryTree(nums []int) *TreeNode { 11 | return performCreate(nums, 0) 12 | } 13 | 14 | func performCreate(nums []int, index int) *TreeNode { 15 | if index >= len(nums) { 16 | return nil 17 | } 18 | 19 | tree := TreeNode{Val: nums[index]} 20 | tree.Left = performCreate(nums, 2*index+1) 21 | tree.Right = performCreate(nums, 2*index+2) 22 | return &tree 23 | } 24 | 25 | func TestSameTree(t *testing.T) { 26 | testData := []arg{ 27 | {p: []int{1, 2, 3}, q: []int{1, 2, 3}}, 28 | {p: []int{1, 2, 3}, q: []int{1, 2}}, 29 | {p: []int{1, 2, 3}, q: []int{1, 2, 4}}, 30 | } 31 | 32 | expectedData := []bool{true, false, false} 33 | 34 | for index, data := range testData { 35 | if res := isSameTree(createBinaryTree(data.p), createBinaryTree(data.q)); res != expectedData[index] { 36 | t.Errorf("expected %t, got %t", expectedData[index], res) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0101_symmetric_tree/symmetric_tree.go: -------------------------------------------------------------------------------- 1 | /* 2 | 101. Symmetric Tree 3 | https://leetcode.com/problems/symmetric-tree/ 4 | 5 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 6 | */ 7 | 8 | package symmetrictree 9 | 10 | // TreeNode binary tree node. 11 | type TreeNode struct { 12 | Val int 13 | Left *TreeNode 14 | Right *TreeNode 15 | } 16 | 17 | func isSymmetric(root *TreeNode) bool { 18 | if root == nil { 19 | return true 20 | } 21 | return symmetric(root.Left, root.Right) 22 | } 23 | 24 | func symmetric(left *TreeNode, right *TreeNode) bool { 25 | if left == nil && right == nil { 26 | return true 27 | } 28 | 29 | if left == nil || right == nil { 30 | return false 31 | } 32 | return left.Val == right.Val && symmetric(left.Left, right.Right) && symmetric(left.Right, right.Left) 33 | } 34 | -------------------------------------------------------------------------------- /solutions/0101_symmetric_tree/symmetric_tree_test.go: -------------------------------------------------------------------------------- 1 | package symmetrictree 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func createBinaryTree(nums []int) *TreeNode { 8 | return performCreate(nums, 0) 9 | } 10 | 11 | func performCreate(nums []int, index int) *TreeNode { 12 | if index >= len(nums) { 13 | return nil 14 | } 15 | 16 | tree := TreeNode{Val: nums[index]} 17 | tree.Left = performCreate(nums, 2*index+1) 18 | tree.Right = performCreate(nums, 2*index+2) 19 | return &tree 20 | } 21 | 22 | func TestIsSymmetric(t *testing.T) { 23 | testData := [][]int{ 24 | {1, 2, 2, 3, 4, 4, 3}, 25 | {1, 2, 2, 3, 3}, 26 | {}, 27 | } 28 | expectedData := []bool{true, false, true} 29 | 30 | for index, data := range testData { 31 | if res := isSymmetric(createBinaryTree(data)); res != expectedData[index] { 32 | t.Errorf("expected %t, got %t", expectedData[index], res) 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go: -------------------------------------------------------------------------------- 1 | /* 2 | 102. Binary Tree Level Order Traversal 3 | https://leetcode.com/problems/binary-tree-level-order-traversal/ 4 | 5 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 6 | */ 7 | // time: 2019-01-04 8 | 9 | package btlot 10 | 11 | // TreeNode Definition for a binary tree node. 12 | type TreeNode struct { 13 | Val int 14 | Left *TreeNode 15 | Right *TreeNode 16 | } 17 | 18 | type queueEle struct { 19 | Level int 20 | Ele *TreeNode 21 | } 22 | 23 | // bfs 24 | // time complexity: O(n), where n is number of tree nodes. 25 | // space complexity: O(n) 26 | func levelOrder(root *TreeNode) [][]int { 27 | if root == nil { 28 | return [][]int{} 29 | } 30 | 31 | var ( 32 | queue []queueEle 33 | res = make([][]int, 0) 34 | ) 35 | 36 | queue = append(queue, queueEle{Level: 0, Ele: root}) 37 | 38 | for len(queue) > 0 { 39 | node := queue[0].Ele 40 | level := queue[0].Level 41 | queue = queue[1:] 42 | 43 | if len(res) > level { 44 | res[level] = append(res[level], node.Val) 45 | } else { 46 | res = append(res, []int{node.Val}) 47 | } 48 | 49 | if node.Left != nil { 50 | queue = append(queue, queueEle{Level: level + 1, Ele: node.Left}) 51 | } 52 | if node.Right != nil { 53 | queue = append(queue, queueEle{Level: level + 1, Ele: node.Right}) 54 | } 55 | 56 | } 57 | return res 58 | } 59 | -------------------------------------------------------------------------------- /solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal_test.go: -------------------------------------------------------------------------------- 1 | package btlot 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestLevelOrder(t *testing.T) { 9 | testCases := []*TreeNode{ 10 | createBinaryTree([]int{1, 2, 3, 4, 5}), 11 | nil, 12 | } 13 | expected := [][][]int{ 14 | {{1}, {2, 3}, {4, 5}}, 15 | {}, 16 | } 17 | 18 | for index, root := range testCases { 19 | if res := levelOrder(root); !reflect.DeepEqual(res, expected[index]) { 20 | t.Errorf("expected %v, got %v", expected[index], res) 21 | } 22 | } 23 | } 24 | 25 | func createBinaryTree(nums []int) *TreeNode { 26 | return performCreate(nums, 0) 27 | } 28 | 29 | func performCreate(nums []int, index int) *TreeNode { 30 | if index >= len(nums) { 31 | return nil 32 | } 33 | tree := TreeNode{Val: nums[index]} 34 | tree.Left = performCreate(nums, 2*index+1) 35 | tree.Right = performCreate(nums, 2*index+2) 36 | return &tree 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0104_maximun_depth_of_binary_tree/maxdobt.go: -------------------------------------------------------------------------------- 1 | /* 2 | 104. Maximum Depth of Binary Tree 3 | https://leetcode.com/problems/maximum-depth-of-binary-tree/ 4 | 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along 8 | the longest path from the root node down to the farthest leaf node. 9 | 10 | Note: A leaf is a node with no children. 11 | */ 12 | // time: 2019-01-06 13 | 14 | package maxdobt 15 | 16 | // TreeNode Definition for a binary tree node. 17 | type TreeNode struct { 18 | Val int 19 | Left *TreeNode 20 | Right *TreeNode 21 | } 22 | 23 | // Recursive 24 | // time complexity: O(n), where n is the nodes number in the tree. 25 | // space complexity: O(h), where h is the height of the tree. 26 | func maxDepth(root *TreeNode) int { 27 | if root == nil { 28 | return 0 29 | } 30 | left := maxDepth(root.Left) 31 | right := maxDepth(root.Right) 32 | 33 | var max int 34 | if left > right { 35 | max = left 36 | } else { 37 | max = right 38 | } 39 | return max + 1 40 | } 41 | -------------------------------------------------------------------------------- /solutions/0104_maximun_depth_of_binary_tree/maxdobt_test.go: -------------------------------------------------------------------------------- 1 | package maxdobt 2 | 3 | import "testing" 4 | 5 | func TestMaxDepth(t *testing.T) { 6 | root := createBinaryTree([]int{1, 2, 3, 4, 5}) 7 | expected := 3 8 | 9 | if res := maxDepth(root); res != expected { 10 | t.Errorf("expected %d, got %d", expected, res) 11 | } 12 | 13 | } 14 | 15 | func createBinaryTree(nums []int) *TreeNode { 16 | return performCreate(nums, 0) 17 | } 18 | 19 | func performCreate(nums []int, index int) *TreeNode { 20 | if index >= len(nums) { 21 | return nil 22 | } 23 | tree := &TreeNode{Val: nums[index]} 24 | tree.Left = performCreate(nums, 2*index+1) 25 | tree.Right = performCreate(nums, 2*index+2) 26 | return tree 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 107. Binary Tree Level Order Traversal II 3 | https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ 4 | 5 | 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). 6 | */ 7 | 8 | package binarytreelevelordertraversal2 9 | 10 | // TreeNode binary tree node. 11 | type TreeNode struct { 12 | Val int 13 | Left *TreeNode 14 | Right *TreeNode 15 | } 16 | 17 | func levelOrderBottom(root *TreeNode) [][]int { 18 | var record [][]int 19 | traversal(root, 0, &record) 20 | var reversed [][]int 21 | for i := len(record) - 1; i >= 0; i-- { 22 | reversed = append(reversed, record[i]) 23 | } 24 | return reversed 25 | } 26 | 27 | func traversal(root *TreeNode, index int, record *[][]int) { 28 | if root == nil { 29 | return 30 | } 31 | if len(*record) == index { 32 | *record = append(*record, make([]int, 0)) 33 | } 34 | (*record)[index] = append((*record)[index], root.Val) 35 | traversal(root.Left, index+1, record) 36 | traversal(root.Right, index+1, record) 37 | // (*record)[len(*record)-1-index] = append((*record)[len(*record)-1-index], root.Val) 38 | // 这个方法用java可以实现,go不行,猜测可能跟java的递归实现有关。 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2_test.go: -------------------------------------------------------------------------------- 1 | package binarytreelevelordertraversal2 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []int) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []int, index int) *TreeNode { 13 | if index >= len(nums) { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{Val: nums[index]} 18 | tree.Left = performCreate(nums, 2*index+1) 19 | tree.Right = performCreate(nums, 2*index+2) 20 | return &tree 21 | } 22 | 23 | func TestBinaryTreeLevelOrderTraversal2(t *testing.T) { 24 | testData := [][]int{ 25 | {3, 9, 20, 15, 17}, 26 | } 27 | expectedData := [][][]int{ 28 | { 29 | {15, 17}, 30 | {9, 20}, 31 | {3}, 32 | }, 33 | } 34 | 35 | for index, data := range testData { 36 | if res := levelOrderBottom(createBinaryTree(data)); !reflect.DeepEqual(res, expectedData[index]) { 37 | t.Errorf("expected %v, got %v", expectedData[index], res) 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go: -------------------------------------------------------------------------------- 1 | /* 2 | 111. Minimum Depth of Binary Tree 3 | https://leetcode.com/problems/minimum-depth-of-binary-tree/ 4 | 5 | Given a binary tree, find its minimum depth. 6 | 7 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 8 | 9 | Note: A leaf is a node with no children. 10 | 11 | */ 12 | 13 | package minimumdepthofbinarytree 14 | 15 | import "leetcode/utils" 16 | 17 | // TreeNode binary tree node. 18 | type TreeNode struct { 19 | Val int 20 | Left *TreeNode 21 | Right *TreeNode 22 | } 23 | 24 | func minDepth(root *TreeNode) int { 25 | if root == nil { 26 | return 0 27 | } 28 | left := minDepth(root.Left) 29 | right := minDepth(root.Right) 30 | 31 | if left == 0 || right == 0 { 32 | return utils.CalcMaxInt(left, right) + 1 33 | } 34 | return utils.CalcMinInt(left, right) + 1 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree_test.go: -------------------------------------------------------------------------------- 1 | package minimumdepthofbinarytree 2 | 3 | import "testing" 4 | 5 | func createBinaryTree(nums []int) *TreeNode { 6 | return performCreate(nums, 0) 7 | } 8 | 9 | func performCreate(nums []int, index int) *TreeNode { 10 | if index >= len(nums) { 11 | return nil 12 | } 13 | 14 | tree := TreeNode{Val: nums[index]} 15 | tree.Left = performCreate(nums, 2*index+1) 16 | tree.Right = performCreate(nums, 2*index+2) 17 | return &tree 18 | } 19 | func TestMinDepth(t *testing.T) { 20 | testData := [][]int{ 21 | {3, 9, 20, 15, 7}, 22 | } 23 | 24 | expectedData := []int{2} 25 | 26 | for index, data := range testData { 27 | if res := minDepth(createBinaryTree(data)); res != expectedData[index] { 28 | t.Errorf("expected %d, got %d", expectedData[index], res) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/0112_path_sum/path_sum.go: -------------------------------------------------------------------------------- 1 | /* 2 | 112. Path Sum 3 | https://leetcode.com/problems/path-sum/ 4 | 5 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 6 | 7 | Note: A leaf is a node with no children. 8 | */ 9 | 10 | package pathsum 11 | 12 | // TreeNode binary tree node. 13 | type TreeNode struct { 14 | Val int 15 | Left *TreeNode 16 | Right *TreeNode 17 | } 18 | 19 | func hasPathSum(root *TreeNode, sum int) bool { 20 | if root == nil { 21 | return false 22 | } 23 | 24 | if root.Left == nil && root.Right == nil { 25 | return root.Val == sum 26 | } 27 | return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val) 28 | } 29 | -------------------------------------------------------------------------------- /solutions/0112_path_sum/path_sum_test.go: -------------------------------------------------------------------------------- 1 | package pathsum 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []interface{}) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []interface{}, index int) *TreeNode { 13 | if !(index < len(nums)) || nums[index] == nil { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{} 18 | if num, ok := nums[index].(int); ok { // type assertion 19 | tree.Val = num 20 | } 21 | tree.Left = performCreate(nums, 2*index+1) 22 | tree.Right = performCreate(nums, 2*index+2) 23 | return &tree 24 | } 25 | 26 | type arg struct { 27 | nums []interface{} 28 | sum int 29 | } 30 | 31 | func TestHasPathSum(t *testing.T) { 32 | testData := []arg{ 33 | {nums: []interface{}{5, 4, 8, 11, nil, 13, 4, 7, 2, nil, nil, nil, 1}, sum: 22}, 34 | {nums: []interface{}{}, sum: 0}, 35 | } 36 | expectedData := []bool{true, false} 37 | for index, data := range testData { 38 | if res := hasPathSum(createBinaryTree(data.nums), data.sum); res != expectedData[index] { 39 | t.Errorf("expected %t, got %t", expectedData[index], res) 40 | } 41 | } 42 | } 43 | 44 | func TestMain(m *testing.M) { 45 | os.Exit(m.Run()) 46 | } 47 | -------------------------------------------------------------------------------- /solutions/0120_triangle/triangle.go: -------------------------------------------------------------------------------- 1 | /* 2 | 120. Triangle 3 | https://leetcode.com/problems/triangle/ 4 | 5 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 6 | 7 | */ 8 | 9 | package triangle 10 | 11 | import "leetcode/utils" 12 | 13 | // dfs 14 | /* 15 | func minimumTotal(triangle [][]int) int { 16 | if len(triangle) == 0 { 17 | return 0 18 | } 19 | result := utils.MaxInt 20 | dfs(0, 0, 0, triangle, &result) 21 | return result 22 | } 23 | 24 | func dfs(x int, y int, sum int, triangle [][]int, result *int) { 25 | if len(triangle) == x { 26 | if sum < *result { 27 | *result = sum 28 | } 29 | return 30 | } 31 | sum += triangle[x][y] 32 | 33 | dfs(x+1, y, sum, triangle, result) 34 | dfs(x+1, y+1, sum, triangle, result) 35 | } 36 | */ 37 | 38 | // dynamic programming 39 | func minimumTotal(triangle [][]int) int { 40 | m := len(triangle) 41 | if m == 0 { 42 | return 0 43 | } 44 | 45 | dp := make([][]int, m) 46 | 47 | dp[0] = append(dp[0], triangle[0][0]) 48 | 49 | for i := 1; i < m; i++ { 50 | for j, num := range triangle[i] { 51 | if j >= len(dp[i-1]) { 52 | dp[i] = append(dp[i], num+dp[i-1][j-1]) 53 | } else { 54 | if j-1 >= 0 && dp[i-1][j-1] < dp[i-1][j] { 55 | dp[i] = append(dp[i], num+dp[i-1][j-1]) 56 | } else { 57 | dp[i] = append(dp[i], num+dp[i-1][j]) 58 | } 59 | } 60 | } 61 | } 62 | 63 | var mininum = utils.MaxInt 64 | for _, num := range dp[m-1] { 65 | if num < mininum { 66 | mininum = num 67 | } 68 | } 69 | return mininum 70 | } 71 | -------------------------------------------------------------------------------- /solutions/0120_triangle/triangle_test.go: -------------------------------------------------------------------------------- 1 | package triangle 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestTriangle(t *testing.T) { 8 | testData := [][][]int{ 9 | {{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}, 10 | {}, 11 | {{-1}, {2, 3}, {1, -1, -3}}, 12 | } 13 | 14 | expectedData := []int{11, 0, -1} 15 | 16 | for index, data := range testData { 17 | if mininum := minimumTotal(data); mininum != expectedData[index] { 18 | t.Errorf("expected %d, got %d", expectedData[index], mininum) 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go: -------------------------------------------------------------------------------- 1 | /* 2 | 121. Best Time to Buy and Sell Stock 3 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 4 | 5 | Say you have an array for which the ith element is the price of a given stock on day i. 6 | 7 | If you were only permitted to complete at most one transaction 8 | (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 9 | 10 | Note that you cannot sell a stock before you buy one. 11 | */ 12 | // time: 2018-12-28 13 | 14 | package maxprofit 15 | 16 | // dynamic programming 17 | // for every price, find the max profit, then record the current minimum price. 18 | // time complexity: O(n) 19 | // space complexity: O(1) 20 | func maxProfit(prices []int) int { 21 | n := len(prices) 22 | if 0 == n || 1 == n { 23 | return 0 24 | } 25 | 26 | var ( 27 | res int 28 | minPrice = prices[0] 29 | ) 30 | 31 | for _, price := range prices { 32 | if price-minPrice > res { 33 | res = price - minPrice 34 | } 35 | if price < minPrice { 36 | minPrice = price 37 | } 38 | } 39 | return res 40 | } 41 | 42 | // brute force 43 | // time complexity: O(n^2) 44 | // space complexity: O(1) 45 | func maxProfit1(prices []int) int { 46 | n := len(prices) 47 | if 0 == n || 1 == n { 48 | return 0 49 | } 50 | res := 0 51 | for i := 1; i < n; i++ { 52 | for j := 0; j < i; j++ { 53 | if prices[i]-prices[j] > res { 54 | res = prices[i] - prices[j] 55 | } 56 | } 57 | } 58 | return res 59 | } 60 | -------------------------------------------------------------------------------- /solutions/0121_best_time_to_buy_and_sell_stock/maxprofit_test.go: -------------------------------------------------------------------------------- 1 | package maxprofit 2 | 3 | import "testing" 4 | 5 | func TestMaxProfit(t *testing.T) { 6 | testCases := [][]int{ 7 | {7, 1, 5, 3, 6, 4}, 8 | {5, 3, 2, 2, 5, 7, 9, 4}, 9 | {}, 10 | {3}, 11 | {5, 3, 2, 2, 5, 7, 9, 4, 5, 3, 2, 2, 5, 7, 9, 4}, 12 | {2, 4, 1, 11, 7}, 13 | } 14 | 15 | expected := []int{5, 7, 0, 0, 7, 10} 16 | 17 | for index, data := range testCases { 18 | if res := maxProfit(data); res != expected[index] { 19 | t.Errorf("expected %d, got %d", expected[index], res) 20 | } 21 | } 22 | } 23 | 24 | func TestMaxProfit1(t *testing.T) { 25 | testCases := [][]int{ 26 | {7, 1, 5, 3, 6, 4}, 27 | {5, 3, 2, 2, 5, 7, 9, 4}, 28 | {}, 29 | {3}, 30 | } 31 | 32 | expected := []int{5, 7, 0, 0} 33 | 34 | for index, data := range testCases { 35 | if res := maxProfit1(data); res != expected[index] { 36 | t.Errorf("expected %d, got %d", expected[index], res) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go: -------------------------------------------------------------------------------- 1 | /* 2 | 122. Best Time to Buy and Sell Stock II 3 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 4 | 5 | Say you have an array for which the ith element is the price of a given stock on day i. 6 | 7 | Design an algorithm to find the maximum profit. 8 | You may complete as many transactions as you like 9 | (i.e., buy one and sell one share of the stock multiple times). 10 | 11 | Note: You may not engage in multiple transactions at the same time 12 | (i.e., you must sell the stock before you buy again). 13 | */ 14 | // time: 2018-12-28 15 | 16 | package maxprofit 17 | 18 | // greedy 19 | // time complexity: O(n) 20 | // space complexity: O(1) 21 | func maxProfit(prices []int) int { 22 | n := len(prices) 23 | 24 | if 0 == n || 1 == n { 25 | return 0 26 | } 27 | 28 | var ( 29 | res int 30 | minPrice = prices[0] 31 | ) 32 | for i := 1; i < n; i++ { 33 | if prices[i] < prices[i-1] { 34 | res += prices[i-1] - minPrice 35 | minPrice = prices[i] 36 | } 37 | if i == n-1 { 38 | res += prices[i] - minPrice 39 | } 40 | } 41 | return res 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit_test.go: -------------------------------------------------------------------------------- 1 | package maxprofit 2 | 3 | import "testing" 4 | 5 | func TestMaxProfit(t *testing.T) { 6 | testCases := [][]int{ 7 | {7, 1, 5, 3, 6, 4}, 8 | {1, 2, 3, 4, 5}, 9 | {7, 6, 4, 3, 1}, 10 | {}, {1}, 11 | } 12 | expected := []int{7, 4, 0, 0, 0} 13 | 14 | for index, data := range testCases { 15 | if res := maxProfit(data); res != expected[index] { 16 | t.Errorf("expected %d, got %d", expected[index], res) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/0125_valid_palindrome/valid_palindrome.go: -------------------------------------------------------------------------------- 1 | /* 2 | 125. Valid Palindrome 3 | https://leetcode.com/problems/valid-palindrome/ 4 | 5 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 6 | 7 | Note: For the purpose of this problem, we define empty string as valid palindrome. 8 | */ 9 | 10 | // time: 2018-12-26 11 | 12 | package validpalindrome 13 | 14 | // double index 15 | // time complexity: O(n) 16 | // space complexity: O(n) 17 | func isPalindrome(s string) bool { 18 | chars := make([]uint8, 0) 19 | 20 | for i := 0; i < len(s); i++ { 21 | if s[i] >= 65 && s[i] <= 90 { 22 | chars = append(chars, s[i]) 23 | } 24 | if s[i] >= 97 && s[i] <= 122 { 25 | chars = append(chars, s[i]-32) 26 | } 27 | if s[i] >= 48 && s[i] <= 57 { 28 | chars = append(chars, s[i]) 29 | } 30 | } 31 | 32 | var ( 33 | l int 34 | r = len(chars) - 1 35 | ) 36 | 37 | for r >= l { 38 | if chars[r] != chars[l] { 39 | return false 40 | } 41 | r-- 42 | l++ 43 | } 44 | return true 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0125_valid_palindrome/valid_palindrome_test.go: -------------------------------------------------------------------------------- 1 | package validpalindrome 2 | 3 | import "testing" 4 | 5 | func TestIsPalindrome(t *testing.T) { 6 | testCases := []string{ 7 | "A man, a plan, a canal: Panama", 8 | "race a car", 9 | "0P", 10 | "", 11 | } 12 | 13 | expected := []bool{true, false, false, true} 14 | 15 | for index, data := range testCases { 16 | if res := isPalindrome(data); res != expected[index] { 17 | t.Errorf("expected %t, got %t", expected[index], res) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/0136_single_number/single_number.go: -------------------------------------------------------------------------------- 1 | /* 2 | 136. Single Number 3 | https://leetcode.com/problems/single-number/ 4 | 5 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 6 | */ 7 | // time: 2019-02-01 8 | 9 | package sn 10 | 11 | // time complexity: O(n) 12 | // space complexity: O(n) 13 | func singleNumber(nums []int) int { 14 | record := make(map[int]int) 15 | for _, num := range nums { 16 | if _, ok := record[num]; ok { 17 | delete(record, num) 18 | } else { 19 | record[num] = 1 20 | } 21 | } 22 | var res int 23 | for key := range record { 24 | res = key 25 | } 26 | return res 27 | } 28 | 29 | // time complexity: O(n) 30 | // space complexity: O(1) 31 | func singleNumber1(nums []int) int { 32 | res := 0 33 | for _, num := range nums { 34 | res ^= num 35 | } 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0136_single_number/single_number_test.go: -------------------------------------------------------------------------------- 1 | package sn 2 | 3 | import "testing" 4 | 5 | func TestSingleNumber(t *testing.T) { 6 | testCases := [][]int{ 7 | {2, 2, 1}, 8 | {4, 1, 2, 1, 2}, 9 | } 10 | expected := []int{1, 4} 11 | testFuncs := []func([]int) int{ 12 | singleNumber, singleNumber1, 13 | } 14 | 15 | for _, testFunc := range testFuncs { 16 | for index, nums := range testCases { 17 | if res := testFunc(nums); res != expected[index] { 18 | t.Errorf("expected %d, got %d", expected[index], res) 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go: -------------------------------------------------------------------------------- 1 | /* 2 | 144. Binary Tree Preorder Traversal 3 | https://leetcode.com/problems/binary-tree-preorder-traversal/ 4 | 5 | Given a binary tree, return the preorder traversal of its nodes' values. 6 | */ 7 | // time: 2019-01-06 8 | 9 | package btpot 10 | 11 | // TreeNode Definition for a binary tree node. 12 | type TreeNode struct { 13 | Val int 14 | Left *TreeNode 15 | Right *TreeNode 16 | } 17 | 18 | // recursive 19 | // time complexity: O(n), where n is nodes numbers in the tree. 20 | // space complexity: O(h), where h is the height of the tree. 21 | func preorderTraversal(root *TreeNode) []int { 22 | if root == nil { 23 | return []int{} 24 | } 25 | 26 | if root.Left == nil && root.Right == nil { 27 | return []int{root.Val} 28 | } 29 | 30 | left := preorderTraversal(root.Left) 31 | right := preorderTraversal(root.Right) 32 | 33 | res := []int{root.Val} 34 | res = append(res, left...) 35 | res = append(res, right...) 36 | return res 37 | } 38 | 39 | // iterative 40 | // time complexity: O(n), where n is nodes numbers in the tree. 41 | // space complexity: O(h), where h is the height of the tree. 42 | func preorderTraversal1(root *TreeNode) []int { 43 | if root == nil { 44 | return []int{} 45 | } 46 | 47 | var stack []*TreeNode 48 | var res []int 49 | stack = append(stack, root) 50 | 51 | for len(stack) > 0 { 52 | node := stack[len(stack)-1] 53 | stack = stack[:len(stack)-1] 54 | 55 | res = append(res, node.Val) 56 | 57 | if node.Right != nil { 58 | stack = append(stack, node.Right) 59 | } 60 | 61 | if node.Left != nil { 62 | stack = append(stack, node.Left) 63 | } 64 | } 65 | return res 66 | } 67 | -------------------------------------------------------------------------------- /solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal_test.go: -------------------------------------------------------------------------------- 1 | package btpot 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []int) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []int, index int) *TreeNode { 13 | if index >= len(nums) { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{Val: nums[index]} 18 | tree.Left = performCreate(nums, 2*index+1) 19 | tree.Right = performCreate(nums, 2*index+2) 20 | return &tree 21 | } 22 | 23 | func TestPreorderTraversal(t *testing.T) { 24 | testCases := []*TreeNode{ 25 | nil, 26 | createBinaryTree([]int{1, 2, 3, 4, 5, 6, 7, 8}), 27 | } 28 | expected := [][]int{ 29 | {}, 30 | {1, 2, 4, 8, 5, 3, 6, 7}, 31 | } 32 | testFuncs := []func(node *TreeNode) []int{ 33 | preorderTraversal, 34 | preorderTraversal1, 35 | } 36 | 37 | for _, testFunc := range testFuncs { 38 | for index, root := range testCases { 39 | if res := testFunc(root); !reflect.DeepEqual(res, expected[index]) { 40 | t.Errorf("expected %v, got %v", expected[index], res) 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go: -------------------------------------------------------------------------------- 1 | /* 2 | 150. Evaluate Reverse Polish Notation 3 | https://leetcode.com/problems/evaluate-reverse-polish-notation/ 4 | 5 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 6 | 7 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 8 | 9 | Note: 10 | 11 | Division between two integers should truncate toward zero. 12 | The given RPN expression is always valid. 13 | That means the expression would always evaluate to a result and there won't be any divide by zero operation. 14 | */ 15 | // time: 2019-01-07 16 | 17 | package evaluatereversepolishnotation 18 | 19 | import "strconv" 20 | 21 | // stack 22 | // time complexity: O(n) 23 | // space complexity: O(n) 24 | func evalRPN(tokens []string) int { 25 | stack := make([]int, len(tokens)) 26 | top := -1 27 | for i := 0; i < len(tokens); i++ { 28 | switch ch := tokens[i]; ch { 29 | case "+": 30 | stack[top-1] += stack[top] 31 | top-- 32 | case "-": 33 | stack[top-1] -= stack[top] 34 | top-- 35 | case "*": 36 | stack[top-1] *= stack[top] 37 | top-- 38 | case "/": 39 | stack[top-1] /= stack[top] 40 | top-- 41 | default: 42 | top++ 43 | stack[top], _ = strconv.Atoi(ch) 44 | } 45 | } 46 | return stack[0] 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation_test.go: -------------------------------------------------------------------------------- 1 | package evaluatereversepolishnotation 2 | 3 | import "testing" 4 | 5 | func TestEvalRPN(t *testing.T) { 6 | testCases := [][]string{ 7 | {"2", "1", "+", "3", "*"}, 8 | {"4", "13", "5", "/", "+"}, 9 | {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}, 10 | {"4", "3", "-"}, 11 | } 12 | 13 | expected := []int{9, 6, 22, 1} 14 | 15 | for index, tokens := range testCases { 16 | if res := evalRPN(tokens); res != expected[index] { 17 | t.Errorf("expected %d, got %d", expected[index], res) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go: -------------------------------------------------------------------------------- 1 | /* 2 | 153. Find Minimum in Rotated Sorted Array 3 | https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 4 | 5 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 6 | 7 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 8 | 9 | Find the minimum element. 10 | 11 | You may assume no duplicate exists in the array. 12 | */ 13 | // time: 2019-01-07 14 | 15 | package fmirsa 16 | 17 | // binary search 18 | // time complexity: O( log n) 19 | // space complexity: O(1) 20 | func findMin(nums []int) int { 21 | var ( 22 | low int 23 | high = len(nums) - 1 24 | mid int 25 | ) 26 | for low < high { 27 | mid = low + (high-low)>>1 28 | if nums[high] < nums[mid] { 29 | low = mid + 1 30 | } else { 31 | high = mid 32 | } 33 | } 34 | return nums[low] 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa_test.go: -------------------------------------------------------------------------------- 1 | package fmirsa 2 | 3 | import "testing" 4 | 5 | func TestFindMin(t *testing.T) { 6 | nums := []int{3, 4, 5, 1, 2} 7 | expected := 1 8 | if res := findMin(nums); res != expected { 9 | t.Errorf("expected %d, got %d", expected, res) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /solutions/0155_min_stack/min_stack_test.go: -------------------------------------------------------------------------------- 1 | package minstack 2 | 3 | import "testing" 4 | 5 | func TestMinStack(t *testing.T) { 6 | obj := Constructor() 7 | obj.Push(-2) 8 | obj.Push(0) 9 | obj.Push(-3) 10 | if res := obj.GetMin(); res != -3 { 11 | t.Errorf("expected %d, got %d", -3, res) 12 | } 13 | 14 | obj.Pop() 15 | if res := obj.Top(); res != 0 { 16 | t.Errorf("expected %d, got %d", 0, res) 17 | } 18 | if res := obj.GetMin(); res != -2 { 19 | t.Errorf("expected %d, got %d", -2, res) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/0165_compare_version_numbers/compare_version_numbers_test.go: -------------------------------------------------------------------------------- 1 | package compareversionnumbers 2 | 3 | import "testing" 4 | 5 | func TestCompareVersion(t *testing.T) { 6 | type arg struct { 7 | version1 string 8 | version2 string 9 | } 10 | 11 | testCases := []arg{ 12 | {version1: "0.1", version2: "1.1"}, 13 | {version1: "1.0.1", version2: "1"}, 14 | {version1: "1.01", version2: "1.001"}, 15 | } 16 | expected := []int{-1, 1, 0} 17 | 18 | for index, data := range testCases { 19 | if res := compareVersion(data.version1, data.version2); res != expected[index] { 20 | t.Errorf("expected %d, got %d", expected[index], res) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/0167_two_sum2/two_sum2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 167. Two Sum II - Input array is sorted 3 | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 4 | 5 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 6 | 7 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 8 | 9 | Note: 10 | Your returned answers (both index1 and index2) are not zero-based. 11 | You may assume that each input would have exactly one solution and you may not use the same element twice. 12 | 13 | Example: 14 | 15 | Input: numbers = [2,7,11,15], target = 9 16 | Output: [1,2] 17 | Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 18 | */ 19 | 20 | package twosum2 21 | 22 | func twoSum2(numbers []int, target int) []int { 23 | n := len(numbers) 24 | var ( 25 | l = 0 26 | r = n - 1 27 | ) 28 | 29 | for l < r { 30 | if numbers[l]+numbers[r] == target { 31 | return []int{l + 1, r + 1} 32 | } else if numbers[l]+numbers[r] < target { 33 | l++ 34 | } else { 35 | r-- 36 | } 37 | } 38 | panic("The input has no solution.") 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0167_two_sum2/two_sum2_test.go: -------------------------------------------------------------------------------- 1 | package twosum2 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | type arg struct { 9 | numbers []int 10 | target int 11 | } 12 | 13 | func TestTwoSum2(t *testing.T) { 14 | testData := []arg{ 15 | { 16 | numbers: []int{2, 7, 11, 15}, 17 | target: 9, 18 | }, 19 | } 20 | 21 | expectedData := [][]int{ 22 | {1, 2}, 23 | } 24 | 25 | for index, data := range testData { 26 | if res := twoSum2(data.numbers, data.target); !reflect.DeepEqual(res, expectedData[index]) { 27 | t.Errorf("expected %v, got %v", expectedData[index], res) 28 | } 29 | } 30 | 31 | defer func() { 32 | if err := recover(); err == nil { 33 | t.Errorf("there should throw a panic") 34 | } 35 | }() 36 | 37 | twoSum2([]int{2, 7, 11, 15}, 90) 38 | } 39 | -------------------------------------------------------------------------------- /solutions/0179_largest_number/ln.go: -------------------------------------------------------------------------------- 1 | /* 2 | 179. Largest Number 3 | https://leetcode.com/problems/largest-number/ 4 | 5 | Given a list of non negative integers, arrange them such that they form the largest number. 6 | Note: The result may be very large, so you need to return a string instead of an integer. 7 | */ 8 | // time: 2019-01-14 9 | 10 | package ln 11 | 12 | import ( 13 | "sort" 14 | "strconv" 15 | "strings" 16 | ) 17 | 18 | type sliceString []string 19 | 20 | // Len is the number of elements in the collection. 21 | func (s sliceString) Len() int { return len(s) } 22 | 23 | // Swap swaps the elements with indexes i and j. 24 | func (s sliceString) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 25 | 26 | // Less reports whether the element with 27 | // index i should sort before the element with index j. 28 | func (s sliceString) Less(i, j int) bool { return (s[i] + s[j]) > (s[j] + s[i]) } 29 | 30 | // time complexity: O(n log n), dominated by the complexity of sort. 31 | // space complexity: O(n) 32 | func largestNumber(nums []int) string { 33 | numsString := make([]string, 0) 34 | for _, num := range nums { 35 | numsString = append(numsString, strconv.Itoa(num)) 36 | } 37 | 38 | sort.Sort(sliceString(numsString)) 39 | numStr := strings.Join(numsString, "") 40 | 41 | if strings.HasPrefix(numStr, "0") { 42 | return "0" 43 | } 44 | return numStr 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0179_largest_number/ln_test.go: -------------------------------------------------------------------------------- 1 | package ln 2 | 3 | import "testing" 4 | 5 | func TestLargestNumber(t *testing.T) { 6 | testCases := [][]int{ 7 | {10, 2}, 8 | {3, 30, 34, 5, 9}, 9 | {0}, 10 | } 11 | 12 | expected := []string{ 13 | "210", 14 | "9534330", 15 | "0", 16 | } 17 | 18 | for index, nums := range testCases { 19 | if res := largestNumber(nums); res != expected[index] { 20 | t.Errorf("expected %s, got %s", expected[index], res) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/0198_house_robber/house_robber_test.go: -------------------------------------------------------------------------------- 1 | package houserobber 2 | 3 | import "testing" 4 | 5 | func TestHouseRobber(t *testing.T) { 6 | testData := [][]int{ 7 | {1, 2, 3, 1}, 8 | {9, 1, 293, 5986, 81, 384}, 9 | {1, 2}, 10 | {}, 11 | } 12 | expectedData := []int{4, 6379, 2, 0} 13 | 14 | for index, data := range testData { 15 | if res := rob(data); res != expectedData[index] { 16 | t.Errorf("expected %d, got %d", expectedData[index], res) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/0200_number_of_island/number_of_island.go: -------------------------------------------------------------------------------- 1 | /* 2 | 200. Number of Islands 3 | https://leetcode.com/problems/number-of-islands/ 4 | 5 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. 6 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. 7 | You may assume all four edges of the grid are all surrounded by water. 8 | */ 9 | // time: 2019-01-07 10 | 11 | package noi 12 | 13 | var ( 14 | d = [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} 15 | m, n int 16 | visited [][]bool 17 | ) 18 | 19 | // flood-fill 20 | // time complexity: O(n*m) 21 | // space complexity: O(n*m) 22 | func numIslands(grid [][]byte) int { 23 | m = len(grid) 24 | if m <= 0 { 25 | return 0 26 | } 27 | n = len(grid[0]) 28 | 29 | visited = make([][]bool, m) 30 | for i := 0; i < m; i++ { 31 | visited[i] = make([]bool, n) 32 | } 33 | 34 | var res int 35 | 36 | for i := 0; i < m; i++ { 37 | for j := 0; j < n; j++ { 38 | if grid[i][j] == '1' && !visited[i][j] { 39 | res++ 40 | dfs(grid, i, j) 41 | } 42 | } 43 | } 44 | return res 45 | } 46 | 47 | // 从grid[x][y]的位置开始,进行floodfill。 48 | func dfs(grid [][]byte, x, y int) { 49 | visited[x][y] = true 50 | for i := 0; i < len(d); i++ { 51 | newX := x + d[i][0] 52 | newY := y + d[i][1] 53 | if inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1' { 54 | dfs(grid, newX, newY) 55 | } 56 | } 57 | } 58 | 59 | func inArea(x, y int) bool { 60 | return x >= 0 && x < m && y >= 0 && y < n 61 | } 62 | -------------------------------------------------------------------------------- /solutions/0200_number_of_island/number_of_island_test.go: -------------------------------------------------------------------------------- 1 | package noi 2 | 3 | import "testing" 4 | 5 | func TestNumIslands(t *testing.T) { 6 | grids := [][][]byte{ 7 | { 8 | {'1', '1', '0', '0', '0'}, 9 | {'1', '1', '0', '0', '0'}, 10 | {'0', '0', '1', '0', '0'}, 11 | {'0', '0', '0', '1', '1'}, 12 | }, 13 | {}, 14 | } 15 | expected := []int{3, 0} 16 | 17 | for index, grid := range grids { 18 | if res := numIslands(grid); res != expected[index] { 19 | t.Errorf("expected %d, got %d", expected[index], res) 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go: -------------------------------------------------------------------------------- 1 | /* 2 | 203. Remove Linked List Elements 3 | https://leetcode.com/problems/remove-linked-list-elements/ 4 | 5 | Remove all elements from a linked list of integers that have value val. 6 | */ 7 | // time: 2019-01-07 8 | 9 | package rlle 10 | 11 | // ListNode Definition for singly-linked list. 12 | type ListNode struct { 13 | Val int 14 | Next *ListNode 15 | } 16 | 17 | // time complexity: O(n) 18 | // space complexity: O(1) 19 | func removeElements(head *ListNode, val int) *ListNode { 20 | dummyHead := &ListNode{} 21 | dummyHead.Next = head 22 | 23 | cur := dummyHead 24 | 25 | for cur.Next != nil { 26 | if val == cur.Next.Val { 27 | cur.Next = cur.Next.Next 28 | } else { 29 | cur = cur.Next 30 | } 31 | } 32 | return dummyHead.Next 33 | } 34 | 35 | // recursive 36 | // time complexity: O(n) 37 | // space complexity: O(n) 38 | func removeElements1(head *ListNode, val int) *ListNode { 39 | if head == nil { 40 | return head 41 | } 42 | head.Next = removeElements1(head.Next, val) 43 | if head.Val == val { 44 | return head.Next 45 | } 46 | return head 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0203_remove_linked_list_elements/remove_linked_list_elements_test.go: -------------------------------------------------------------------------------- 1 | package rlle 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestRemoveElements(t *testing.T) { 9 | head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6}) 10 | val := 6 11 | expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) 12 | 13 | if res := removeElements(head, val); !reflect.DeepEqual(res, expected) { 14 | t.Errorf("expected %v, got %v", expected, res) 15 | } 16 | } 17 | 18 | func TestRemoveElements1(t *testing.T) { 19 | head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6}) 20 | val := 6 21 | expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) 22 | 23 | if res := removeElements1(head, val); !reflect.DeepEqual(res, expected) { 24 | t.Errorf("expected %v, got %v", expected, res) 25 | } 26 | } 27 | 28 | func createSinglyLinkedList(nums []int) *ListNode { 29 | head := &ListNode{} 30 | cur := head 31 | 32 | for _, num := range nums { 33 | cur.Next = &ListNode{Val: num} 34 | cur = cur.Next 35 | } 36 | return head.Next 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0206_reverse_linked_list/reverse_linked_list.go: -------------------------------------------------------------------------------- 1 | /* 2 | 206. Reverse Linked List 3 | https://leetcode.com/problems/reverse-linked-list/ 4 | 5 | Reverse a singly linked list. 6 | */ 7 | // time: 2019-01-07 8 | 9 | package rll 10 | 11 | // ListNode Definition for singly-linked list. 12 | type ListNode struct { 13 | Val int 14 | Next *ListNode 15 | } 16 | 17 | // recursive 18 | // time complexity: O(n) 19 | // space complexity: O(n) 20 | func reverseList(head *ListNode) *ListNode { 21 | if head == nil || head.Next == nil { 22 | return head 23 | } 24 | 25 | tail := reverseList(head.Next) 26 | head.Next.Next = head 27 | head.Next = nil 28 | return tail 29 | } 30 | 31 | // iterative 32 | // time complexity: O(n) 33 | // space complexity: O(1) 34 | func reverseList1(head *ListNode) *ListNode { 35 | var ( 36 | pre *ListNode 37 | cur = head 38 | ) 39 | for cur != nil { 40 | next := cur.Next 41 | cur.Next = pre 42 | pre = cur 43 | cur = next 44 | } 45 | return pre 46 | } 47 | -------------------------------------------------------------------------------- /solutions/0206_reverse_linked_list/reverse_linked_list_test.go: -------------------------------------------------------------------------------- 1 | package rll 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestReverseList(t *testing.T) { 9 | head := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) 10 | expected := createSinglyLinkedList([]int{5, 4, 3, 2, 1}) 11 | if res := reverseList(head); !reflect.DeepEqual(res, expected) { 12 | t.Errorf("expected %v, got %v", expected, res) 13 | } 14 | } 15 | 16 | func TestReverseList1(t *testing.T) { 17 | head := createSinglyLinkedList([]int{1, 2, 3, 4, 5}) 18 | expected := createSinglyLinkedList([]int{5, 4, 3, 2, 1}) 19 | if res := reverseList1(head); !reflect.DeepEqual(res, expected) { 20 | t.Errorf("expected %v, got %v", expected, res) 21 | } 22 | } 23 | 24 | func createSinglyLinkedList(nums []int) *ListNode { 25 | head := &ListNode{} 26 | cur := head 27 | 28 | for _, num := range nums { 29 | cur.Next = &ListNode{Val: num} 30 | cur = cur.Next 31 | } 32 | return head.Next 33 | } 34 | -------------------------------------------------------------------------------- /solutions/0208_implement_trie_prefix_tree/impltrie_test.go: -------------------------------------------------------------------------------- 1 | package impltree 2 | 3 | import "testing" 4 | 5 | func TestImplTrie(t *testing.T) { 6 | trie := Constructor() 7 | trie.Insert("apple") 8 | 9 | for i, j := range map[string]bool{"apple": true, "app": false, "hello": false} { 10 | if res := trie.Search(i); res != j { 11 | t.Errorf("expected %t, got %t", j, res) 12 | } 13 | } 14 | 15 | for i, j := range map[string]bool{"app": true, "as": false} { 16 | if res := trie.StartsWith(i); res != j { 17 | t.Errorf("expected %t, got %t", j, res) 18 | } 19 | } 20 | 21 | trie.Insert("app") 22 | if res := trie.Search("app"); res != true { 23 | t.Errorf("expected %t, got %t", true, res) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go: -------------------------------------------------------------------------------- 1 | /* 2 | 209. Minimum Size Subarray Sum 3 | https://leetcode.com/problems/minimum-size-subarray-sum/ 4 | 5 | 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. 6 | 7 | Example: 8 | 9 | Input: s = 7, nums = [2,3,1,2,4,3] 10 | Output: 2 11 | Explanation: the subarray [4,3] has the minimal length under the problem constraint. 12 | 13 | Follow up: 14 | If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 15 | */ 16 | 17 | package minimumsizesubarraysum 18 | 19 | func minSubArrayLen(s int, nums []int) int { 20 | var ( 21 | l = 0 22 | r = -1 23 | res = len(nums) + 1 24 | sum = 0 25 | ) 26 | 27 | for l < len(nums) { 28 | if sum < s && r+1 < len(nums) { 29 | r++ 30 | sum += nums[r] 31 | } else { 32 | sum -= nums[l] 33 | l++ 34 | } 35 | if sum >= s && res > r-l+1 { 36 | res = r - l + 1 37 | } 38 | } 39 | if res == len(nums)+1 { 40 | return 0 41 | } 42 | return res 43 | } 44 | -------------------------------------------------------------------------------- /solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum_test.go: -------------------------------------------------------------------------------- 1 | package minimumsizesubarraysum 2 | 3 | import "testing" 4 | 5 | func TestMinSubArrayLen(t *testing.T) { 6 | type arg struct { 7 | s int 8 | nums []int 9 | } 10 | testData := []arg{ 11 | { 12 | s: 7, 13 | nums: []int{2, 3, 1, 2, 4, 3}, 14 | }, 15 | { 16 | s: 7, 17 | nums: []int{7, 4, 3, 2}, 18 | }, 19 | { 20 | s: 66, 21 | nums: []int{7, 4, 3, 2}, 22 | }, 23 | } 24 | 25 | expectedData := []int{2, 1, 0} 26 | 27 | for index, data := range testData { 28 | if res := minSubArrayLen(data.s, data.nums); res != expectedData[index] { 29 | t.Errorf("expected %d, got %d", expectedData[index], res) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /solutions/0211_add_and_search_word/add_and_search_word.go: -------------------------------------------------------------------------------- 1 | /* 2 | 211. Add and Search Word - Data structure design 3 | https://leetcode.com/problems/add-and-search-word-data-structure-design/ 4 | */ 5 | // time: 2019-01-31 6 | 7 | package aasw 8 | 9 | type node struct { 10 | isWord bool 11 | next map[byte]*node 12 | } 13 | 14 | // WordDictionary supports two operations(addWord, search) 15 | type WordDictionary struct { 16 | root *node 17 | } 18 | 19 | // Constructor initialize data structure here. 20 | func Constructor() WordDictionary { 21 | return WordDictionary{&node{next: make(map[byte]*node)}} 22 | } 23 | 24 | // AddWord adds a word into the trie. 25 | func (trie *WordDictionary) AddWord(word string) { 26 | cur := trie.root 27 | for i := 0; i < len(word); i++ { 28 | if _, ok := cur.next[word[i]]; !ok { 29 | cur.next[word[i]] = &node{next: make(map[byte]*node)} 30 | } 31 | cur = cur.next[word[i]] 32 | } 33 | if !cur.isWord { 34 | cur.isWord = true 35 | } 36 | } 37 | 38 | // Search returns if the word is in the trie. 39 | // a word could contain the dot character '.' to represent any ont letter. 40 | func (trie *WordDictionary) Search(word string) bool { 41 | return match(trie.root, word, 0) 42 | } 43 | 44 | func match(n *node, word string, index int) bool { 45 | if index == len(word) { 46 | return n.isWord 47 | } 48 | if word[index] != '.' { 49 | if _, ok := n.next[word[index]]; !ok { 50 | return false 51 | } 52 | return match(n.next[word[index]], word, index+1) 53 | } else { 54 | for _, nextNode := range n.next { 55 | if match(nextNode, word, index+1) { 56 | return true 57 | } 58 | } 59 | return false 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /solutions/0211_add_and_search_word/add_and_search_word_test.go: -------------------------------------------------------------------------------- 1 | package aasw 2 | 3 | import "testing" 4 | 5 | func TestAddAndSearchWord(t *testing.T) { 6 | obj := Constructor() 7 | 8 | for _, word := range []string{"bad", "dad", "mad"} { 9 | obj.AddWord(word) 10 | } 11 | 12 | for i, j := range map[string]bool{"pad": false, "bad": true, ".ad": true, "b..": true, "b..d": false} { 13 | if res := obj.Search(i); res != j { 14 | t.Errorf("expected %t, got %t", j, res) 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /solutions/0215_kth_largest_element_in_an_array/kthleiaa.go: -------------------------------------------------------------------------------- 1 | /* 2 | 215. Kth Largest Element in an Array 3 | https://leetcode.com/problems/kth-largest-element-in-an-array/ 4 | 5 | Find the kth largest element in an unsorted array. 6 | Note that it is the kth largest element in the sorted order, not the kth distinct element. 7 | 8 | You may assume k is always valid, 1 ≤ k ≤ array's length. 9 | 10 | */ 11 | 12 | // time: 2018-12-22 13 | 14 | package kthleiaa 15 | 16 | // heap sort 17 | // time complexity: O(k * logn) 18 | // sapce complexity: O(1) 19 | func findKthLargest(nums []int, k int) int { 20 | // heapify 21 | for i := (len(nums) - 1) / 2; i >= 0; i-- { 22 | siftDown(nums, len(nums), i) 23 | } 24 | 25 | for i := len(nums) - 1; i >= len(nums)-k; i-- { 26 | nums[i], nums[0] = nums[0], nums[i] 27 | siftDown(nums, i, 0) 28 | } 29 | return nums[len(nums)-k] 30 | } 31 | 32 | func siftDown(nums []int, n int, i int) { 33 | for 2*i+1 < n { 34 | j := 2*i + 1 35 | if j+1 < n && nums[j+1] > nums[j] { 36 | j++ 37 | } 38 | 39 | if nums[i] >= nums[j] { 40 | break 41 | } 42 | nums[j], nums[i] = nums[i], nums[j] 43 | i = j 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0215_kth_largest_element_in_an_array/kthleiaa_test.go: -------------------------------------------------------------------------------- 1 | package kthleiaa 2 | 3 | import "testing" 4 | 5 | func TestFindKthLargest(t *testing.T) { 6 | type arg struct { 7 | nums []int 8 | k int 9 | } 10 | 11 | testCases := []arg{ 12 | {nums: []int{3, 2, 1, 5, 6, 4}, k: 2}, 13 | {nums: []int{3, 2, 3, 1, 2, 4, 5, 5, 6}, k: 4}, 14 | } 15 | 16 | expected := []int{5, 4} 17 | 18 | for index, data := range testCases { 19 | if res := findKthLargest(data.nums, data.k); res != expected[index] { 20 | t.Errorf("expected %d, got %d", expected[index], res) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/0217_contains_duplicate/contains_duplicate.go: -------------------------------------------------------------------------------- 1 | /* 2 | 217. Contains Duplicate 3 | https://leetcode.com/problems/contains-duplicate/ 4 | 5 | Given an array of integers, find if the array contains any duplicates. 6 | 7 | Your function should return true if any value appears at least twice in the array, 8 | and it should return false if every element is distinct. 9 | */ 10 | // time: 2019-01-07 11 | 12 | package cd 13 | 14 | // using HashTable 15 | // time complexity: O(n) 16 | // space complexity: O(n) 17 | func containsDuplicate(nums []int) bool { 18 | record := make(map[int]int) 19 | 20 | for _, num := range nums { 21 | if _, ok := record[num]; !ok { 22 | record[num] = 1 23 | } else { 24 | return true 25 | } 26 | } 27 | return false 28 | } 29 | -------------------------------------------------------------------------------- /solutions/0217_contains_duplicate/contains_duplicate_test.go: -------------------------------------------------------------------------------- 1 | package cd 2 | 3 | import "testing" 4 | 5 | func TestContainsDuplicate(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 2, 3, 1}, 8 | {1, 2, 3, 4}, 9 | } 10 | expected := []bool{true, false} 11 | 12 | for index, nums := range testCases { 13 | if res := containsDuplicate(nums); res != expected[index] { 14 | t.Errorf("expected %t, got %t", expected[index], res) 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /solutions/0219_contains_duplicate_2/contains_duplicate_2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 219. Contains Duplicate II 3 | https://leetcode.com/problems/contains-duplicate-ii/ 4 | 5 | Given an array of integers and an integer k, 6 | find out whether there are two distinct indices i and j in the array 7 | such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 8 | */ 9 | // time: 2019-01-07 10 | 11 | package cond 12 | 13 | // using hash table 14 | // time complexity: O(n) 15 | // space complexity: O(n) 16 | func containsNearbyDuplicate(nums []int, k int) bool { 17 | record := make(map[int]int, len(nums)) 18 | for i, v := range nums { 19 | if j, ok := record[v]; ok { 20 | if i-j <= k { 21 | return true 22 | } 23 | } 24 | record[v] = i 25 | } 26 | return false 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0219_contains_duplicate_2/contains_duplicate_2_test.go: -------------------------------------------------------------------------------- 1 | package cond 2 | 3 | import "testing" 4 | 5 | func TestContainsNearbyDuplicate(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 2, 3, 1}, 8 | {1, 0, 1, 1}, 9 | {1, 2, 3, 1, 2, 3}, 10 | } 11 | ks := []int{3, 1, 2} 12 | expected := []bool{true, true, false} 13 | 14 | for index, nums := range testCases { 15 | if res := containsNearbyDuplicate(nums, ks[index]); res != expected[index] { 16 | t.Errorf("expected %t, got %t", expected[index], res) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/0226_invert_binary_tree/invert_binary_tree.go: -------------------------------------------------------------------------------- 1 | /* 2 | 226. Invert Binary Tree 3 | https://leetcode.com/problems/invert-binary-tree/ 4 | 5 | Invert a binary tree. 6 | */ 7 | 8 | package invertbinarytree 9 | 10 | // TreeNode binary tree node 11 | type TreeNode struct { 12 | Val int 13 | Left *TreeNode 14 | Right *TreeNode 15 | } 16 | 17 | // Recursion 18 | // Time complexity: O(n), where n is the node's number of the tree. 19 | // Space complexity: O(h), where h is the height of the tree. 20 | func invertTree(root *TreeNode) *TreeNode { 21 | if root == nil { 22 | return nil 23 | } 24 | root.Right, root.Left = root.Left, root.Right 25 | invertTree(root.Left) 26 | invertTree(root.Right) 27 | return root 28 | } 29 | -------------------------------------------------------------------------------- /solutions/0226_invert_binary_tree/invert_binary_tree_test.go: -------------------------------------------------------------------------------- 1 | package invertbinarytree 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []interface{}) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []interface{}, index int) *TreeNode { 13 | if !(index < len(nums)) || nums[index] == nil { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{} 18 | if num, ok := nums[index].(int); ok { // type assertion 19 | tree.Val = num 20 | } 21 | tree.Left = performCreate(nums, 2*index+1) 22 | tree.Right = performCreate(nums, 2*index+2) 23 | return &tree 24 | } 25 | 26 | func levelOrderTraversal(root *TreeNode) []interface{} { 27 | res := make([]interface{}, 0) 28 | queue := make([]*TreeNode, 0) 29 | queue = append(queue, root) 30 | for len(queue) > 0 { 31 | node := queue[0] 32 | queue = queue[1:] 33 | res = append(res, node.Val) 34 | if node.Left != nil { 35 | queue = append(queue, node.Left) 36 | } 37 | if node.Right != nil { 38 | queue = append(queue, node.Right) 39 | } 40 | } 41 | return res 42 | } 43 | 44 | func TestInvertTree(t *testing.T) { 45 | testData := [][]interface{}{ 46 | {4, 2, 7, 1, 3, 6, 9}, 47 | } 48 | 49 | expectedData := [][]interface{}{ 50 | {4, 7, 2, 9, 6, 3, 1}, 51 | } 52 | 53 | for index, data := range testData { 54 | tree := createBinaryTree(data) 55 | if res := levelOrderTraversal(invertTree(tree)); !reflect.DeepEqual(res, expectedData[index]) { 56 | t.Errorf("expected %v, got %v", expectedData[index], res) 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go: -------------------------------------------------------------------------------- 1 | /* 2 | 235. Lowest Common Ancestor of a Binary Search Tree 3 | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 4 | 5 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 6 | 7 | According to the definition of LCA on Wikipedia: 8 | “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has 9 | both p and q as descendants (where we allow a node to be a descendant of itself).” 10 | 11 | Note: 12 | All of the nodes' values will be unique. 13 | p and q are different and both values will exist in the BST. 14 | */ 15 | // time: 2019-01-07 16 | 17 | package lcaoabst 18 | 19 | // TreeNode Definition for TreeNode. 20 | type TreeNode struct { 21 | Val int 22 | Left *TreeNode 23 | Right *TreeNode 24 | } 25 | 26 | // recursive 27 | // time complexity: O(log n), where n is the nodes number of the tree. 28 | // space complexity: O(h), where h is the height of the tree. 29 | func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { 30 | if root == nil { 31 | return root 32 | } 33 | 34 | if root.Val > p.Val && root.Val > q.Val { 35 | return lowestCommonAncestor(root.Left, p, q) 36 | } 37 | 38 | if root.Val < p.Val && root.Val < q.Val { 39 | return lowestCommonAncestor(root.Right, p, q) 40 | } 41 | return root 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst_test.go: -------------------------------------------------------------------------------- 1 | package lcaoabst 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLowestCommonAncestor(t *testing.T) { 8 | type arg struct { 9 | root, p, q *TreeNode 10 | } 11 | 12 | testCases := []arg{ 13 | {root: createBinaryTree([]int{6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5}), p: &TreeNode{Val: 3}, q: &TreeNode{Val: 5}}, 14 | {p: &TreeNode{Val: 2}, q: &TreeNode{Val: 8}}, 15 | } 16 | expected := []*TreeNode{{Val: 4}, nil} 17 | 18 | for index, data := range testCases { 19 | if res := lowestCommonAncestor(data.root, data.p, data.q); res != nil && res.Val != expected[index].Val { 20 | t.Errorf("expected %v, got %v", expected[index], res) 21 | } else if res == nil && res != expected[index] { 22 | t.Errorf("expected %v, got %v", expected[index], res) 23 | } 24 | } 25 | } 26 | 27 | func createBinaryTree(nums []int) *TreeNode { 28 | return performCreate(nums, 0) 29 | } 30 | 31 | func performCreate(nums []int, index int) *TreeNode { 32 | if index >= len(nums) { 33 | return nil 34 | } 35 | root := &TreeNode{Val: nums[index]} 36 | root.Left = performCreate(nums, 2*index+1) 37 | root.Right = performCreate(nums, 2*index+2) 38 | return root 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go: -------------------------------------------------------------------------------- 1 | /* 2 | 236. Lowest Common Ancestor of a Binary Tree 3 | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 4 | */ 5 | // 2019-02-21 6 | 7 | package lca 8 | 9 | // TreeNode Definition for TreeNode. 10 | type TreeNode struct { 11 | Val int 12 | Left *TreeNode 13 | Right *TreeNode 14 | } 15 | 16 | func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { 17 | if root == nil || root == p || root == q { 18 | return root 19 | } 20 | left := lowestCommonAncestor(root.Left, p, q) 21 | right := lowestCommonAncestor(root.Right, p, q) 22 | 23 | if left != nil && right != nil { 24 | return root 25 | } 26 | if left != nil { 27 | return left 28 | } 29 | return right 30 | } 31 | -------------------------------------------------------------------------------- /solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca_test.go: -------------------------------------------------------------------------------- 1 | package lca 2 | 3 | import "testing" 4 | 5 | func TestLCA(t *testing.T) { 6 | type arg struct { 7 | root, p, q *TreeNode 8 | } 9 | 10 | tree := createBinaryTree([]int{6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5}) 11 | 12 | testCases := []arg{ 13 | {root: tree, p: tree.Left.Right.Left, q: tree.Left.Right.Right}, 14 | {p: &TreeNode{Val: 2}, q: &TreeNode{Val: 8}}, 15 | } 16 | expected := []*TreeNode{{Val: 4}, nil} 17 | 18 | for index, data := range testCases { 19 | if res := lowestCommonAncestor(data.root, data.p, data.q); res != nil && res.Val != expected[index].Val { 20 | t.Errorf("expected %v, got %v", expected[index], res) 21 | } else if res == nil && res != expected[index] { 22 | t.Errorf("expected %v, got %v", expected[index], res) 23 | } 24 | } 25 | } 26 | 27 | func createBinaryTree(nums []int) *TreeNode { 28 | return performCreate(nums, 0) 29 | } 30 | 31 | func performCreate(nums []int, index int) *TreeNode { 32 | if index >= len(nums) { 33 | return nil 34 | } 35 | root := &TreeNode{Val: nums[index]} 36 | root.Left = performCreate(nums, 2*index+1) 37 | root.Right = performCreate(nums, 2*index+2) 38 | return root 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0237_delete_node_in_a_linked_list/dniall.go: -------------------------------------------------------------------------------- 1 | /* 2 | 237. Delete Node in a Linked List 3 | https://leetcode.com/problems/delete-node-in-a-linked-list/ 4 | 5 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 6 | 7 | Note: 8 | The linked list will have at least two elements. 9 | All of the nodes' values will be unique. 10 | The given node will not be the tail and it will always be a valid node of the linked list. 11 | Do not return anything from your function. 12 | */ 13 | // time: 2019-01-07 14 | 15 | package dniall 16 | 17 | // ListNode Definition for singly-linked list. 18 | type ListNode struct { 19 | Val int 20 | Next *ListNode 21 | } 22 | 23 | // time complexity: O(1) 24 | // space complexity: O(1) 25 | func deleteNode(node *ListNode) { 26 | // The linked list will have at least two elements. 27 | // All the nodes' values will be unique. 28 | // The given node will not be the tail and it will always be a valid node of the linked list. 29 | node.Val = node.Next.Val 30 | node.Next = node.Next.Next 31 | } 32 | -------------------------------------------------------------------------------- /solutions/0237_delete_node_in_a_linked_list/dniall_test.go: -------------------------------------------------------------------------------- 1 | package dniall 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSinglyLinkedList(nums []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | 12 | for _, num := range nums { 13 | cur.Next = &ListNode{Val: num} 14 | cur = cur.Next 15 | } 16 | return head.Next 17 | } 18 | 19 | func TestDeleteNode(t *testing.T) { 20 | root := createSinglyLinkedList([]int{4, 5, 1, 9}) 21 | node := root.Next 22 | expected := createSinglyLinkedList([]int{4, 1, 9}) 23 | if deleteNode(node); !reflect.DeepEqual(expected, root) { 24 | t.Errorf("expected %v, got %v", expected, root) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /solutions/0257_binary_tree_paths/binary_tree_paths.go: -------------------------------------------------------------------------------- 1 | /* 2 | 257. Binary Tree Paths 3 | https://leetcode.com/problems/binary-tree-paths/ 4 | 5 | Given a binary tree, return all root-to-leaf paths. 6 | 7 | Note: A leaf is a node with no children. 8 | */ 9 | // time: 2019-01-07 10 | 11 | package btp 12 | 13 | import "strconv" 14 | 15 | // TreeNode Definition for a binary tree node. 16 | type TreeNode struct { 17 | Val int 18 | Left *TreeNode 19 | Right *TreeNode 20 | } 21 | 22 | // recursive 23 | // time complexity: O(n), where n is the nodes number in the tree. 24 | // space complexity: O(h), where h is the height of the tree. 25 | func binaryTreePaths(root *TreeNode) []string { 26 | if root == nil { 27 | return []string{} 28 | } 29 | 30 | var res []string 31 | 32 | if root.Left == nil && root.Right == nil { 33 | return append(res, strconv.Itoa(root.Val)) 34 | } 35 | 36 | if root.Left != nil { 37 | for _, i := range binaryTreePaths(root.Left) { 38 | res = append(res, strconv.Itoa(root.Val)+"->"+i) 39 | } 40 | } 41 | if root.Right != nil { 42 | for _, i := range binaryTreePaths(root.Right) { 43 | res = append(res, strconv.Itoa(root.Val)+"->"+i) 44 | } 45 | } 46 | return res 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0257_binary_tree_paths/binary_tree_paths_test.go: -------------------------------------------------------------------------------- 1 | package btp 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []int) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []int, index int) *TreeNode { 13 | if index >= len(nums) { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{Val: nums[index]} 18 | tree.Left = performCreate(nums, 2*index+1) 19 | tree.Right = performCreate(nums, 2*index+2) 20 | return &tree 21 | } 22 | 23 | func TestBinaryTreePaths(t *testing.T) { 24 | testCases := []*TreeNode{ 25 | createBinaryTree([]int{1, 2, 3, 4, 5}), 26 | nil, 27 | } 28 | expected := [][]string{ 29 | {"1->2->4", "1->2->5", "1->3"}, 30 | {}, 31 | } 32 | for index, root := range testCases { 33 | if res := binaryTreePaths(root); !reflect.DeepEqual(res, expected[index]) { 34 | t.Errorf("expected %v, got %v", expected[index], res) 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0258_add_digits/add_digits.go: -------------------------------------------------------------------------------- 1 | /* 2 | 258. Add Digits 3 | https://leetcode.com/problems/add-digits/ 4 | 5 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 6 | */ 7 | // time: 2019-01-07 8 | 9 | package ad 10 | 11 | // time complexity: O( log num ) 12 | // space complexity: O(1) 13 | func addDigits(num int) int { 14 | // num is a non-negative integer 15 | for num > 9 { 16 | num = performAdd(num) 17 | } 18 | return num 19 | } 20 | 21 | func performAdd(num int) (res int) { 22 | for num > 0 { 23 | res += num % 10 24 | num /= 10 25 | } 26 | return 27 | } 28 | 29 | // time complexity: O(1) 30 | // space complexity: O(1) 31 | func addDigits1(num int) int { 32 | /* 33 | 0 1 2 3 4 5 6 7 8 9 34 | 0 1 2 3 4 5 6 7 8 9 35 | 10 11 12 13 14 15 16 17 18 19 36 | 1 2 3 4 5 6 7 8 9 10/1 37 | 20 21 22 23 24 25 26 27 28 29 38 | 2 3 4 5 6 7 8 9 10/1 11/2 39 | */ 40 | return (num-1)%9 + 1 41 | } 42 | -------------------------------------------------------------------------------- /solutions/0258_add_digits/add_digits_test.go: -------------------------------------------------------------------------------- 1 | package ad 2 | 3 | import "testing" 4 | 5 | func TestAddDigits(t *testing.T) { 6 | num := 38 7 | expected := 2 8 | 9 | testFuncs := []func(int) int{ 10 | addDigits, 11 | addDigits1, 12 | } 13 | 14 | for _, function := range testFuncs { 15 | if res := function(num); res != expected { 16 | t.Errorf("expected %d, got %d", expected, res) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/0283_move_zeroes/move_zeroes.go: -------------------------------------------------------------------------------- 1 | /* 2 | 283. Move Zeroes 3 | https://leetcode.com/problems/move-zeroes/ 4 | 5 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 6 | */ 7 | 8 | package movezeroes 9 | 10 | // Time complexity: O(n) 11 | // Space complexity: O(1) 12 | func moveZeroes(nums []int) { 13 | var k int 14 | for i := range nums { 15 | if nums[i] != 0 { 16 | if k != i { 17 | nums[i], nums[k] = nums[k], nums[i] 18 | } 19 | k++ 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0283_move_zeroes/move_zeroes2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 283. Move Zeroes 3 | https://leetcode.com/problems/move-zeroes/ 4 | 5 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 6 | */ 7 | 8 | package movezeroes 9 | 10 | // Time complexity: O(n) 11 | // Space complexity: O(1) 12 | func moveZeroes2(nums []int) { 13 | var k int 14 | for i := range nums { 15 | if nums[i] != 0 { 16 | if k != i { 17 | nums[k] = nums[i] 18 | } 19 | k++ 20 | } 21 | } 22 | 23 | for i := k; i < len(nums); i++ { 24 | nums[i] = 0 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /solutions/0283_move_zeroes/move_zeroes2_test.go: -------------------------------------------------------------------------------- 1 | package movezeroes 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestMoveZeroes2(t *testing.T) { 9 | testData := [][]int{ 10 | {0, 1, 0, 3, 12}, 11 | } 12 | 13 | expectedData := [][]int{ 14 | {1, 3, 12, 0, 0}, 15 | } 16 | 17 | for index, data := range testData { 18 | if moveZeroes2(data); !reflect.DeepEqual(data, expectedData[index]) { 19 | t.Errorf("expected %v, got %v", expectedData[index], data) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0283_move_zeroes/move_zeroes_test.go: -------------------------------------------------------------------------------- 1 | package movezeroes 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestMoveZeroes(t *testing.T) { 9 | testData := [][]int{ 10 | {0, 1, 0, 3, 12}, 11 | } 12 | 13 | expectedData := [][]int{ 14 | {1, 3, 12, 0, 0}, 15 | } 16 | 17 | for index, data := range testData { 18 | if moveZeroes(data); !reflect.DeepEqual(data, expectedData[index]) { 19 | t.Errorf("expected %v, got %v", expectedData[index], data) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0300_longest_increasing_subsequence/lis.go: -------------------------------------------------------------------------------- 1 | /* 2 | 300. Longest Increasing Subsequence 3 | https://leetcode.com/problems/longest-increasing-subsequence/ 4 | 5 | Given an unsorted array of integers, find the length of longest increasing subsequence. 6 | 7 | Example: 8 | 9 | Input: [10,9,2,5,3,7,101,18] 10 | Output: 4 11 | Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 12 | Note: 13 | 14 | There may be more than one LIS combination, it is only necessary for you to return the length. 15 | Your algorithm should run in O(n2) complexity. 16 | 17 | Follow up: 18 | Could you improve it to O(n log n) time complexity? 19 | */ 20 | 21 | package lis 22 | 23 | import "leetcode/utils" 24 | 25 | // Dynamic Programming 26 | // TIme complexity: O(n^2) 27 | // Space Complexity: O(n) 28 | func lengthOfLIS(nums []int) int { 29 | n := len(nums) 30 | if n == 0 { 31 | return 0 32 | } 33 | 34 | memo := make([]int, n) 35 | for i := 0; i < n; i++ { 36 | memo[i] = 1 37 | } 38 | 39 | for i := 1; i < n; i++ { 40 | for j := 0; j < i; j++ { 41 | if nums[j] < nums[i] { 42 | memo[i] = utils.CalcMaxInt(memo[i], 1+memo[j]) 43 | } 44 | } 45 | } 46 | return utils.CalcMaxInt(memo...) 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0300_longest_increasing_subsequence/lis_test.go: -------------------------------------------------------------------------------- 1 | package lis 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | func TestLIS(t *testing.T) { 9 | testData := [][]int{ 10 | {10, 9, 2, 5, 3, 7, 101, 18}, 11 | {}, 12 | } 13 | expectedData := []int{4, 0} 14 | 15 | for index, data := range testData { 16 | if res := lengthOfLIS(data); res != expectedData[index] { 17 | t.Errorf("expected %d, got %d", expectedData[index], res) 18 | } 19 | } 20 | } 21 | 22 | func TestMain(m *testing.M) { 23 | os.Exit(m.Run()) 24 | } 25 | -------------------------------------------------------------------------------- /solutions/0303_range_sum_query/rsqim.go: -------------------------------------------------------------------------------- 1 | /* 2 | 303. Range Sum Query - Immutable 3 | https://leetcode.com/problems/range-sum-query-immutable/ 4 | 5 | Given an integer array nums, 6 | find the sum of the elements between indices i and j (i ≤ j), inclusive. 7 | */ 8 | // time: 2018-12-28 9 | 10 | package rsqim 11 | 12 | // NumArray store sum of nums sub-list. 13 | type NumArray struct { 14 | sum []int 15 | } 16 | 17 | // Constructor make NumArray instance. 18 | func Constructor(nums []int) NumArray { 19 | nA := NumArray{sum: make([]int, 1)} 20 | for _, num := range nums { 21 | nA.sum = append(nA.sum, nA.sum[len(nA.sum)-1]+num) 22 | } 23 | return nA 24 | } 25 | 26 | // SumRange find the sum of the elements between indices i and j(i <= j), inclusive. 27 | func (na *NumArray) SumRange(i int, j int) int { 28 | j++ 29 | return na.sum[j] - na.sum[i] 30 | } 31 | -------------------------------------------------------------------------------- /solutions/0303_range_sum_query/rsqim_test.go: -------------------------------------------------------------------------------- 1 | package rsqim 2 | 3 | import "testing" 4 | 5 | func TestSumRange(t *testing.T) { 6 | nums := []int{-2, 0, 3, -5, 2, -1} 7 | ranges := [][]int{ 8 | {0, 2}, 9 | {2, 5}, 10 | {0, 5}, 11 | } 12 | 13 | expected := []int{1, -1, -3} 14 | 15 | obj := Constructor(nums) 16 | 17 | for index, section := range ranges { 18 | if res := obj.SumRange(section[0], section[1]); res != expected[index] { 19 | t.Errorf("expected %d, got %d", expected[index], res) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut_test.go: -------------------------------------------------------------------------------- 1 | package rsqm 2 | 3 | import "testing" 4 | 5 | func TestNumArray(t *testing.T) { 6 | nums := []int{1, 2, 3, 6, 7, 8, 9, 3, 4, 2, 5} 7 | na := Constructor(nums) 8 | if res := na.SumRange(4, 9); res != 33 { 9 | t.Errorf("expected %d, got %d", 43, res) 10 | } 11 | na.Update(6, 10) 12 | if res := na.SumRange(4, 9); res != 34 { 13 | t.Errorf("expected %d, got %d", 44, res) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /solutions/0328_odd_even_linked_list/odd_even_linked_list.go: -------------------------------------------------------------------------------- 1 | /* 2 | 328. Odd Even Linked List 3 | https://leetcode.com/problems/odd-even-linked-list/ 4 | 5 | Given a singly linked list, group all odd nodes together followed by the even nodes. 6 | Please note here we are talking about the node number and not the value in the nodes. 7 | 8 | You should try to do it in place. 9 | The program should run in O(1) space complexity and O(nodes) time complexity. 10 | 11 | Note: 12 | The relative order inside both the even and odd groups should remain as it was in the input. 13 | The first node is considered odd, the second node even and so on ... 14 | */ 15 | // time: 2019-01-07 16 | 17 | package oddevenlinkedlist 18 | 19 | // ListNode Definition for singly-linked list. 20 | type ListNode struct { 21 | Val int 22 | Next *ListNode 23 | } 24 | 25 | // time complexity: O(n) 26 | // space complexity: O(1) 27 | func oddEvenList(head *ListNode) *ListNode { 28 | if head == nil { 29 | return head 30 | } 31 | var ( 32 | odd = head 33 | evenHead = head.Next 34 | even = evenHead 35 | ) 36 | for even != nil && even.Next != nil { 37 | odd.Next = even.Next 38 | odd = odd.Next 39 | even.Next = odd.Next 40 | even = even.Next 41 | } 42 | odd.Next = evenHead 43 | return head 44 | } 45 | -------------------------------------------------------------------------------- /solutions/0328_odd_even_linked_list/odd_even_linked_list_test.go: -------------------------------------------------------------------------------- 1 | package oddevenlinkedlist 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createSinglyLinkedList(nums []int) *ListNode { 9 | head := &ListNode{} 10 | cur := head 11 | 12 | for _, num := range nums { 13 | cur.Next = &ListNode{Val: num} 14 | cur = cur.Next 15 | } 16 | return head.Next 17 | } 18 | 19 | func TestOddEvenList(t *testing.T) { 20 | testCases := []*ListNode{ 21 | createSinglyLinkedList([]int{2, 1, 3, 5, 6, 4, 7}), 22 | nil, 23 | } 24 | expected := []*ListNode{ 25 | createSinglyLinkedList([]int{2, 3, 6, 7, 1, 5, 4}), 26 | nil, 27 | } 28 | 29 | for index, head := range testCases { 30 | if res := oddEvenList(head); !reflect.DeepEqual(res, expected[index]) { 31 | t.Errorf("expected %v, got %v", expected[index], res) 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /solutions/0343_integer_break/integer_break_test.go: -------------------------------------------------------------------------------- 1 | package integerbreak 2 | 3 | import "testing" 4 | 5 | func TestIntegerBreak(t *testing.T) { 6 | testData := []int{2, 10, 34} 7 | expectedData := []int{1, 36, 236196} 8 | 9 | for index, data := range testData { 10 | if res := integerBreak(data); res != expectedData[index] { 11 | t.Errorf("expected %d, got %d", expectedData[index], res) 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /solutions/0344_reverse_string/reverse_string.go: -------------------------------------------------------------------------------- 1 | /* 2 | 344. Reverse String 3 | https://leetcode.com/problems/reverse-string/ 4 | 5 | Write a function that takes a string as input and returns the string reversed. 6 | */ 7 | // time: 2018-12-26 8 | 9 | package reversestring 10 | 11 | // double index 12 | // time complexity: O(n) 13 | // space complexity: O(1) 14 | func reverseString(s string) string { 15 | var ( 16 | l int 17 | r = len(s) - 1 18 | ) 19 | 20 | for r > l { 21 | charL := s[l] 22 | charR := s[r] 23 | s = s[:r] + string(charL) + s[r+1:] 24 | s = s[:l] + string(charR) + s[l+1:] 25 | r-- 26 | l++ 27 | } 28 | return s 29 | } 30 | 31 | // double index 32 | // time complexity: O(n) 33 | // space complexity: O(n) 34 | func reverseString1(s string) string { 35 | sLen := len(s) 36 | bytes := []byte(s) 37 | for i := 0; i < sLen/2; i++ { 38 | bytes[i], bytes[sLen-i-1] = bytes[sLen-i-1], bytes[i] 39 | } 40 | return string(bytes) 41 | } 42 | -------------------------------------------------------------------------------- /solutions/0344_reverse_string/reverse_string_test.go: -------------------------------------------------------------------------------- 1 | package reversestring 2 | 3 | import "testing" 4 | 5 | func TestReverseString(t *testing.T) { 6 | testCases := []string{ 7 | "hello", 8 | "A man, a plan, a canal: Panama", 9 | "", 10 | "ab", 11 | } 12 | expected := []string{ 13 | "olleh", 14 | "amanaP :lanac a ,nalp a ,nam A", 15 | "", 16 | "ba", 17 | } 18 | 19 | for index, data := range testCases { 20 | if res := reverseString(data); res != expected[index] { 21 | t.Errorf("expected %s, got %s", expected[index], res) 22 | } 23 | } 24 | } 25 | 26 | func TestReverseString1(t *testing.T) { 27 | testCases := []string{ 28 | "hello", 29 | "A man, a plan, a canal: Panama", 30 | "", 31 | "ab", 32 | } 33 | expected := []string{ 34 | "olleh", 35 | "amanaP :lanac a ,nalp a ,nam A", 36 | "", 37 | "ba", 38 | } 39 | 40 | for index, data := range testCases { 41 | if res := reverseString1(data); res != expected[index] { 42 | t.Errorf("expected %s, got %s", expected[index], res) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go: -------------------------------------------------------------------------------- 1 | /* 2 | 345. Reverse Vowels of a String 3 | https://leetcode.com/problems/reverse-vowels-of-a-string/ 4 | 5 | Write a function that takes a string as input and reverse only the vowels of a string. 6 | 7 | */ 8 | // time: 2018-12-26 9 | 10 | package reversevowels 11 | 12 | // time complexity: O(n) 13 | // space complexity: O(1) 14 | func reverseVowels(s string) string { 15 | var ( 16 | l int 17 | r = len(s) - 1 18 | ) 19 | 20 | for r > l { 21 | for r >= 0 && !isVowel(s[r]) { 22 | r-- 23 | } 24 | 25 | for l < len(s) && !isVowel(s[l]) { 26 | l++ 27 | } 28 | 29 | if l >= r { 30 | break 31 | } 32 | charL := s[l] 33 | charR := s[r] 34 | s = s[:r] + string(charL) + s[r+1:] 35 | s = s[:l] + string(charR) + s[l+1:] 36 | r-- 37 | l++ 38 | } 39 | return s 40 | } 41 | 42 | // time complexity: O(n) 43 | // space complexity: O(n) 44 | func reverseVowels1(s string) string { 45 | bytes := []byte(s) 46 | var ( 47 | l int 48 | r = len(bytes) - 1 49 | ) 50 | for r > l { 51 | for r >= 0 && !isVowel(s[r]) { 52 | r-- 53 | } 54 | for l < len(bytes) && !isVowel(s[l]) { 55 | l++ 56 | } 57 | if l >= r { 58 | break 59 | } 60 | 61 | bytes[l], bytes[r] = bytes[r], bytes[l] 62 | l++ 63 | r-- 64 | } 65 | return string(bytes) 66 | } 67 | 68 | func isVowel(char byte) bool { 69 | vowels := [...]byte{'a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U'} 70 | 71 | for _, k := range vowels { 72 | if char == k { 73 | return true 74 | } 75 | } 76 | return false 77 | } 78 | -------------------------------------------------------------------------------- /solutions/0345_reverse_vowels_of_a_string/reverse_vowels_test.go: -------------------------------------------------------------------------------- 1 | package reversevowels 2 | 3 | import "testing" 4 | 5 | func TestReverseVowels(t *testing.T) { 6 | testCases := []string{ 7 | "hello", 8 | "leetcode", 9 | "aA", 10 | "a.b,.", 11 | } 12 | 13 | expected := []string{ 14 | "holle", 15 | "leotcede", 16 | "Aa", 17 | "a.b,.", 18 | } 19 | 20 | for index, data := range testCases { 21 | if res := reverseVowels(data); res != expected[index] { 22 | t.Errorf("expected %s, got %s", expected[index], res) 23 | } 24 | } 25 | } 26 | 27 | func TestReverseVowels1(t *testing.T) { 28 | testCases := []string{ 29 | "hello", 30 | "leetcode", 31 | "aA", 32 | "a.b,.", 33 | } 34 | 35 | expected := []string{ 36 | "holle", 37 | "leotcede", 38 | "Aa", 39 | "a.b,.", 40 | } 41 | 42 | for index, data := range testCases { 43 | if res := reverseVowels1(data); res != expected[index] { 44 | t.Errorf("expected %s, got %s", expected[index], res) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0347_top_k_frequent_elements/topkfe_test.go: -------------------------------------------------------------------------------- 1 | package topkfe 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestTopKFrequent(t *testing.T) { 9 | nums := []int{1, 1, 1, 2, 2, 3} 10 | k := 2 11 | expected := []int{1, 2} 12 | if res := topKFrequent(nums, k); !reflect.DeepEqual(res, expected) { 13 | t.Errorf("expected %v, got %v", expected, res) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays.go: -------------------------------------------------------------------------------- 1 | /* 2 | 349. Intersection of Two Arrays 3 | https://leetcode.com/problems/intersection-of-two-arrays 4 | 5 | Given two arrays, write a function to compute their intersection. 6 | 7 | Example 1: 8 | 9 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 10 | Output: [2] 11 | Example 2: 12 | 13 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 14 | Output: [9,4] 15 | 16 | Note: 17 | Each element in the result must be unique. 18 | The result can be in any order. 19 | */ 20 | 21 | package intersectionof2arrays 22 | 23 | import "leetcode/utils" 24 | 25 | func intersection(nums1 []int, nums2 []int) []int { 26 | set1 := utils.NewSet() 27 | for _, num := range nums1 { 28 | set1.Add(num) 29 | } 30 | set2 := utils.NewSet() 31 | for _, num := range nums2 { 32 | set2.Add(num) 33 | } 34 | 35 | var res []int 36 | for item := range set1 { 37 | if set2.Contains(item) { 38 | if value, ok := item.(int); ok { 39 | res = append(res, value) 40 | } 41 | } 42 | } 43 | return res 44 | } 45 | -------------------------------------------------------------------------------- /solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays_test.go: -------------------------------------------------------------------------------- 1 | package intersectionof2arrays 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestIntersection(t *testing.T) { 9 | nums1 := []int{1, 2, 2, 1} 10 | nums2 := []int{2, 2} 11 | expectedData := []int{2} 12 | 13 | if res := intersection(nums1, nums2); !reflect.DeepEqual(res, expectedData) { 14 | t.Errorf("expected %v, got %v", expectedData, res) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 350. Intersection of Two Arrays II 3 | https://leetcode.com/problems/intersection-of-two-arrays-ii/ 4 | 5 | */ 6 | 7 | package intersectionof2arrays2 8 | 9 | func intersect(nums1 []int, nums2 []int) []int { 10 | record := make(map[int]int) 11 | res := make([]int, 0) 12 | for _, num := range nums1 { 13 | if _, ok := record[num]; !ok { 14 | record[num] = 1 15 | } else { 16 | record[num]++ 17 | } 18 | } 19 | 20 | for _, num := range nums2 { 21 | if count, ok := record[num]; ok && count > 0 { 22 | res = append(res, num) 23 | record[num]-- 24 | } 25 | } 26 | return res 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2_test.go: -------------------------------------------------------------------------------- 1 | package intersectionof2arrays2 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestInteract(t *testing.T) { 9 | nums1 := []int{1, 2, 2, 1} 10 | nums2 := []int{2, 2} 11 | 12 | expectedData := []int{2, 2} 13 | 14 | if res := intersect(nums1, nums2); !reflect.DeepEqual(res, expectedData) { 15 | t.Errorf("expected %v, got %v", expectedData, res) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /solutions/0392_is_subsequence/is_subsequence.go: -------------------------------------------------------------------------------- 1 | /* 2 | 392. Is Subsequence 3 | https://leetcode.com/problems/is-subsequence/ 4 | 5 | Given a string s and a string t, check if s is subsequence of t. 6 | 7 | You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). 8 | 9 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not). 10 | 11 | Example 1: 12 | s = "abc", t = "ahbgdc" 13 | 14 | Return true. 15 | 16 | Example 2: 17 | s = "axc", t = "ahbgdc" 18 | 19 | Return false. 20 | 21 | Follow up: 22 | If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? 23 | 24 | Credits: 25 | Special thanks to @pbrother for adding this problem and creating all test cases. 26 | */ 27 | 28 | package issubsequence 29 | 30 | // greedy 31 | // Time complexity: O(n), where n is min( len(s), len(t) ) 32 | // Space complexity: O(1) 33 | func isSubsequence(s string, t string) bool { 34 | var si, ti int 35 | 36 | for si < len(s) && ti < len(t) { 37 | if s[si] == t[ti] { 38 | si++ 39 | ti++ 40 | } else { 41 | ti++ 42 | } 43 | } 44 | return si == len(s) 45 | } 46 | -------------------------------------------------------------------------------- /solutions/0392_is_subsequence/is_subsequence_test.go: -------------------------------------------------------------------------------- 1 | package issubsequence 2 | 3 | import "testing" 4 | 5 | type args struct { 6 | s string 7 | t string 8 | } 9 | 10 | func TestAssignCookies(t *testing.T) { 11 | testData := []args{ 12 | { 13 | s: "abc", 14 | t: "ahbgdc", 15 | }, 16 | { 17 | s: "acb", 18 | t: "ahbgdc", 19 | }, 20 | } 21 | expectedData := []bool{true, false} 22 | 23 | for index, data := range testData { 24 | if res := isSubsequence(data.s, data.t); res != expectedData[index] { 25 | t.Errorf("expected %t, got %t", expectedData[index], res) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /solutions/0404_sum_of_left_leaves/sum_of_left_leaves.go: -------------------------------------------------------------------------------- 1 | /* 2 | 404. Sum of Left Leaves 3 | https://leetcode.com/problems/sum-of-left-leaves/ 4 | 5 | Find the sum of all left leaves in a given binary tree. 6 | */ 7 | // time: 2019-01-07 8 | 9 | package soll 10 | 11 | // TreeNode Definition for a binary tree node. 12 | type TreeNode struct { 13 | Val int 14 | Left *TreeNode 15 | Right *TreeNode 16 | } 17 | 18 | // time complexity: O(n), where n is nodes number in the tree. 19 | // space complexity: O(h), where h is height of the tree. 20 | func sumOfLeftLeaves(root *TreeNode) int { 21 | return performSum(root, false) 22 | } 23 | 24 | func performSum(root *TreeNode, isLeft bool) int { 25 | if root == nil { 26 | return 0 27 | } 28 | 29 | if root.Left == nil && root.Right == nil && isLeft { 30 | return root.Val 31 | } 32 | 33 | return performSum(root.Left, true) + performSum(root.Right, false) 34 | } 35 | -------------------------------------------------------------------------------- /solutions/0404_sum_of_left_leaves/sum_of_left_leaves_test.go: -------------------------------------------------------------------------------- 1 | package soll 2 | 3 | import "testing" 4 | 5 | func createBinaryTree(nums []int) *TreeNode { 6 | return performCreate(nums, 0) 7 | } 8 | 9 | func performCreate(nums []int, index int) *TreeNode { 10 | if index >= len(nums) { 11 | return nil 12 | } 13 | 14 | tree := TreeNode{Val: nums[index]} 15 | tree.Left = performCreate(nums, 2*index+1) 16 | tree.Right = performCreate(nums, 2*index+2) 17 | return &tree 18 | } 19 | 20 | func TestSumOfLeftLeaves(t *testing.T) { 21 | root := createBinaryTree([]int{3, 9, 20, 15, 7, 2}) 22 | expected := 17 23 | 24 | if res := sumOfLeftLeaves(root); res != expected { 25 | t.Errorf("expected %d, got %d", expected, res) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum.go: -------------------------------------------------------------------------------- 1 | /* 2 | 416. Partition Equal Subset Sum 3 | https://leetcode.com/problems/partition-equal-subset-sum/ 4 | 5 | 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. 6 | 7 | Note: 8 | 1. Each of the array element will not exceed 100. 9 | 2. The array size will not exceed 200. 10 | */ 11 | 12 | package partitionequalsubsetsum 13 | 14 | /* 15 | 此问题可以使用0-1背包问题的思路求解 16 | 17 | c是数组和的一半。 18 | 19 | 状态定义:F(n c) 20 | 21 | 状态转移方程:F(n c) = max( F(n-1, c) , n + F(n-1, c-n) ) 22 | */ 23 | func canPartition(nums []int) bool { 24 | var sum int 25 | for _, num := range nums { 26 | sum += num 27 | } 28 | 29 | if sum%2 != 0 { 30 | return false 31 | } 32 | 33 | c := sum / 2 34 | n := len(nums) 35 | memo := make([]bool, c+1) 36 | 37 | for i := 0; i <= c; i++ { 38 | memo[i] = nums[0] == i 39 | } 40 | 41 | for i := 0; i < n; i++ { 42 | for j := c; j >= nums[i]; j-- { 43 | memo[j] = memo[j] || memo[j-nums[i]] 44 | } 45 | } 46 | return memo[c] 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum_test.go: -------------------------------------------------------------------------------- 1 | package partitionequalsubsetsum 2 | 3 | import "testing" 4 | 5 | func TestPartitionEqualSubsetSum(t *testing.T) { 6 | testData := [][]int{ 7 | {1, 5, 11, 5}, 8 | {1, 2, 3, 5}, 9 | } 10 | 11 | expectedData := []bool{true, false} 12 | 13 | for index, data := range testData { 14 | if res := canPartition(data); res != expectedData[index] { 15 | t.Errorf("expected %t, got %t", expectedData[index], res) 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solutions/0435_non_overlapping_intervals/dp_solution.go: -------------------------------------------------------------------------------- 1 | /* 2 | 435. Non-overlapping Intervals 3 | https://leetcode.com/problems/non-overlapping-intervals/ 4 | 5 | Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. 6 | 7 | Note: 8 | 1. You may assume the interval's end point is always bigger than its start point. 9 | 2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. 10 | */ 11 | 12 | package nonoverlappingintervals 13 | 14 | import ( 15 | "leetcode/utils" 16 | "sort" 17 | ) 18 | 19 | func eraseOverlapIntervalsDp(intervals []Interval) int { 20 | n := len(intervals) 21 | if n == 0 { 22 | return 0 23 | } 24 | 25 | sort.Sort(IntervalSliceCompareWithStart(intervals)) 26 | 27 | // memo[i]表示使用intervals[0...i]的区间能构成的最长不重叠区间序列 28 | memo := make([]int, n) 29 | for i := 0; i < n; i++ { 30 | memo[i] = 1 31 | } 32 | 33 | for i := 1; i < n; i++ { 34 | // memo[i] 35 | for j := 0; j < i; j++ { 36 | if intervals[i].Start >= intervals[j].End { 37 | memo[i] = utils.CalcMaxInt(memo[i], 1+memo[j]) 38 | } 39 | } 40 | } 41 | 42 | var res int 43 | for i := 0; i < n; i++ { 44 | res = utils.CalcMaxInt(res, memo[i]) 45 | } 46 | return n - res 47 | } 48 | -------------------------------------------------------------------------------- /solutions/0435_non_overlapping_intervals/greedy_solution.go: -------------------------------------------------------------------------------- 1 | /* 2 | 435. Non-overlapping Intervals 3 | https://leetcode.com/problems/non-overlapping-intervals/ 4 | 5 | Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. 6 | 7 | Note: 8 | 1. You may assume the interval's end point is always bigger than its start point. 9 | 2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. 10 | */ 11 | 12 | package nonoverlappingintervals 13 | 14 | import "sort" 15 | 16 | func eraseOverlapIntervalsGreedy(intervals []Interval) int { 17 | n := len(intervals) 18 | if n == 0 { 19 | return 0 20 | } 21 | 22 | sort.Sort(IntervalSliceCompareWithEnd(intervals)) 23 | var ( 24 | res = 1 25 | pre = 0 26 | ) 27 | 28 | for i := 1; i < n; i++ { 29 | if intervals[i].Start >= intervals[pre].End { 30 | res++ 31 | pre = i 32 | } 33 | } 34 | return n - res 35 | } 36 | -------------------------------------------------------------------------------- /solutions/0435_non_overlapping_intervals/interval.go: -------------------------------------------------------------------------------- 1 | package nonoverlappingintervals 2 | 3 | // Interval Definition for an interval. 4 | type Interval struct { 5 | Start int 6 | End int 7 | } 8 | 9 | // IntervalSliceCompareWithStart slice of Interval sort with start 10 | type IntervalSliceCompareWithStart []Interval 11 | 12 | // Len is the number of elements in the collection. 13 | func (i IntervalSliceCompareWithStart) Len() int { return len(i) } 14 | 15 | // Less compare Interval with start 16 | func (i IntervalSliceCompareWithStart) Less(j, k int) bool { 17 | if i[j].Start != i[k].Start { 18 | return i[j].Start < i[k].Start 19 | } 20 | return i[j].End < i[k].End 21 | } 22 | 23 | func (i IntervalSliceCompareWithStart) Swap(j, k int) { i[j], i[k] = i[k], i[j] } 24 | 25 | // IntervalSliceCompareWithEnd slice of Interval sort with end 26 | type IntervalSliceCompareWithEnd []Interval 27 | 28 | // Len is the number of elements in the collection. 29 | func (i IntervalSliceCompareWithEnd) Len() int { return len(i) } 30 | 31 | // Less compare Interval with end 32 | func (i IntervalSliceCompareWithEnd) Less(j, k int) bool { 33 | if i[j].End != i[k].End { 34 | return i[j].End < i[k].End 35 | } 36 | return i[j].Start < i[k].Start 37 | } 38 | 39 | func (i IntervalSliceCompareWithEnd) Swap(j, k int) { i[j], i[k] = i[k], i[j] } 40 | -------------------------------------------------------------------------------- /solutions/0435_non_overlapping_intervals/solution_test.go: -------------------------------------------------------------------------------- 1 | package nonoverlappingintervals 2 | 3 | import "testing" 4 | 5 | func TestEraseOverlapIntervals(t *testing.T) { 6 | testData := [][]Interval{ 7 | { 8 | Interval{Start: 1, End: 2}, 9 | Interval{Start: 1, End: 2}, 10 | Interval{Start: 1, End: 2}, 11 | }, 12 | { 13 | Interval{Start: 1, End: 2}, 14 | Interval{Start: 2, End: 3}, 15 | }, 16 | { 17 | Interval{Start: 1, End: 2}, 18 | Interval{Start: 2, End: 3}, 19 | Interval{Start: 3, End: 4}, 20 | Interval{Start: 1, End: 3}, 21 | }, 22 | } 23 | expectedData := []int{2, 0, 1} 24 | 25 | testFuncs := []func([]Interval) int{ 26 | eraseOverlapIntervalsGreedy, 27 | eraseOverlapIntervalsDp, 28 | } 29 | 30 | for index, data := range testData { 31 | for _, testFunc := range testFuncs { 32 | if res := testFunc(data); res != expectedData[index] { 33 | t.Errorf("expected %d, got %d", expectedData[index], res) 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /solutions/0437_path_sum_3/path_sum_3.go: -------------------------------------------------------------------------------- 1 | /* 2 | 437. Path Sum III 3 | https://leetcode.com/problems/path-sum-iii/ 4 | 5 | You are given a binary tree in which each node contains an integer value. 6 | 7 | Find the number of paths that sum to a given value. 8 | 9 | The path does not need to start or end at the root or a leaf, 10 | but it must go downwards (traveling only from parent nodes to child nodes). 11 | 12 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. 13 | */ 14 | // 2019-01-08 15 | 16 | package ps3 17 | 18 | // TreeNode Definition for a binary tree node. 19 | type TreeNode struct { 20 | Val int 21 | Left *TreeNode 22 | Right *TreeNode 23 | } 24 | 25 | // recursive 26 | // time complexity: O(n), where n is the nodes number of the tree. 27 | // space complexity: O(h), where h is the height of the tree. 28 | func pathSum(root *TreeNode, sum int) int { 29 | if nil == root { 30 | return 0 31 | } 32 | return findPath(root, sum) + pathSum(root.Left, sum) + pathSum(root.Right, sum) 33 | } 34 | 35 | func findPath(node *TreeNode, val int) int { 36 | if node == nil { 37 | return 0 38 | } 39 | 40 | res := 0 41 | if val == node.Val { 42 | res += 1 43 | } 44 | 45 | res += findPath(node.Left, val-node.Val) 46 | res += findPath(node.Right, val-node.Val) 47 | return res 48 | } 49 | -------------------------------------------------------------------------------- /solutions/0437_path_sum_3/path_sum_3_test.go: -------------------------------------------------------------------------------- 1 | package ps3 2 | 3 | import "testing" 4 | 5 | func createBinaryTree(nums []int) *TreeNode { 6 | return performCreate(nums, 0) 7 | } 8 | 9 | func performCreate(nums []int, index int) *TreeNode { 10 | if index >= len(nums) { 11 | return nil 12 | } 13 | 14 | tree := TreeNode{Val: nums[index]} 15 | tree.Left = performCreate(nums, 2*index+1) 16 | tree.Right = performCreate(nums, 2*index+2) 17 | return &tree 18 | } 19 | 20 | func TestPathSum(t *testing.T) { 21 | root := createBinaryTree([]int{10, 5, -3, 3, 2, 9, 11, 3, -2, 3, 1}) 22 | sum := 8 23 | expected := 3 24 | 25 | if res := pathSum(root, sum); res != expected { 26 | t.Errorf("expected %d, got %d", expected, res) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string_test.go: -------------------------------------------------------------------------------- 1 | package allanagramsinastring 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestFindAnagrams(t *testing.T) { 9 | type arg struct { 10 | s string 11 | p string 12 | } 13 | cases := []arg{ 14 | { 15 | s: "cbaebabacd", 16 | p: "abc", 17 | }, 18 | { 19 | s: "abab", 20 | p: "ab", 21 | }, 22 | { 23 | p: "abab", 24 | s: "ab", 25 | }, 26 | } 27 | 28 | expected := [][]int{ 29 | {0, 6}, 30 | {0, 1, 2}, 31 | {}, 32 | } 33 | 34 | for index, args := range cases { 35 | if res := findAnagrams(args.s, args.p); !reflect.DeepEqual(res, expected[index]) { 36 | t.Errorf("expected %v, got %v", expected[index], res) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0447_number_of_boomerangs/number_of_boomerangs.go: -------------------------------------------------------------------------------- 1 | /* 2 | 447. Number of Boomerangs 3 | https://leetcode.com/problems/number-of-boomerangs/ 4 | 5 | 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). 6 | 7 | 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). 8 | */ 9 | 10 | package numberofboomerangs 11 | 12 | import ( 13 | "math" 14 | ) 15 | 16 | // Time complexity: O(n^2) 17 | // Space complexity: O(n) 18 | func numberOfBoomerangs(points [][]int) int { 19 | var ( 20 | res int 21 | n = len(points) 22 | ) 23 | 24 | for i := 0; i < n; i++ { 25 | record := make(map[int]int) 26 | for j := 0; j < n; j++ { 27 | if j != i { 28 | dis := dis(points[i], points[j]) 29 | record[dis]++ 30 | } 31 | } 32 | 33 | for _, j := range record { 34 | res += j * (j - 1) 35 | } 36 | } 37 | return res 38 | } 39 | 40 | func dis(point1 []int, point2 []int) int { 41 | return int(math.Pow(float64(point1[0]-point2[0]), float64(2)) + math.Pow(float64(point1[1]-point2[1]), float64(2))) 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0454_4sum2/4sum2.go: -------------------------------------------------------------------------------- 1 | /* 2 | 454. 4Sum II 3 | https://leetcode.com/problems/4sum-ii/ 4 | 5 | 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. 6 | 7 | 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. 8 | */ 9 | 10 | package foursum2 11 | 12 | // Time complexity: O(n^2) 13 | // Space complexity: O(n^2) 14 | func fourSumCount(A []int, B []int, C []int, D []int) int { 15 | var ( 16 | record = make(map[int]int) 17 | res int 18 | ) 19 | 20 | for _, i := range A { 21 | for _, j := range B { 22 | record[i+j]++ 23 | } 24 | } 25 | 26 | for _, i := range C { 27 | for _, j := range D { 28 | if s, ok := record[-i-j]; ok && s > 0 { 29 | res += s 30 | } 31 | } 32 | } 33 | return res 34 | } 35 | -------------------------------------------------------------------------------- /solutions/0454_4sum2/4sum2_test.go: -------------------------------------------------------------------------------- 1 | package foursum2 2 | 3 | import "testing" 4 | 5 | func TestFourSumCount(t *testing.T) { 6 | A := []int{1, 2} 7 | B := []int{-2, -1} 8 | C := []int{-1, 2} 9 | D := []int{0, 2} 10 | 11 | expectedData := 2 12 | 13 | if res := fourSumCount(A, B, C, D); res != expectedData { 14 | t.Errorf("expected %d, got %d", expectedData, res) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /solutions/0455_assign_cookies/assign_cookies.go: -------------------------------------------------------------------------------- 1 | /* 2 | 455. Assign Cookies 3 | https://leetcode.com/problems/assign-cookies/ 4 | 5 | Assume you are an awesome parent and want to give your children some cookies. 6 | But, you should give each child at most one cookie. 7 | Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; 8 | 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. 9 | Your goal is to maximize the number of your content children and output the maximum number. 10 | 11 | Note: 12 | 1. You may assume the greed factor is always positive. 13 | 2. You cannot assign more than one cookie to one child. 14 | */ 15 | 16 | package assigncookies 17 | 18 | import "sort" 19 | 20 | // greedy 21 | // Time complexity: O(n), where n is min ( len(g), len(s) ) 22 | // Space complexity: O(1) 23 | func findContentChildren(g []int, s []int) int { 24 | sort.Sort(sort.Reverse(sort.IntSlice(s))) 25 | sort.Sort(sort.Reverse(sort.IntSlice(g))) 26 | 27 | var ( 28 | si, gi, res int 29 | ) 30 | 31 | for gi < len(g) && si < len(s) { 32 | if s[si] >= g[gi] { 33 | res++ 34 | gi++ 35 | si++ 36 | } else { 37 | gi++ 38 | } 39 | } 40 | 41 | return res 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0455_assign_cookies/assign_cookies_test.go: -------------------------------------------------------------------------------- 1 | package assigncookies 2 | 3 | import "testing" 4 | 5 | type args struct { 6 | g []int 7 | s []int 8 | } 9 | 10 | func TestAssignCookies(t *testing.T) { 11 | testData := []args{ 12 | { 13 | g: []int{1, 2, 3}, 14 | s: []int{1, 1}, 15 | }, 16 | { 17 | g: []int{1, 2}, 18 | s: []int{1, 2, 3}, 19 | }, 20 | } 21 | expectedData := []int{1, 2} 22 | 23 | for index, data := range testData { 24 | if res := findContentChildren(data.g, data.s); res != expectedData[index] { 25 | t.Errorf("expected %d, got %d", expectedData[index], res) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3.go: -------------------------------------------------------------------------------- 1 | /* 2 | 557. Reverse Words in a String III 3 | https://leetcode.com/problems/reverse-words-in-a-string-iii/ 4 | 5 | Given a string, you need to reverse the order of characters in each word within a sentence 6 | while still preserving whitespace and initial word order. 7 | 8 | Note: In the string, each word is separated by single space and there will not be any extra space in the string. 9 | */ 10 | // time: 2019-01-08 11 | 12 | package rwias3 13 | 14 | import "strings" 15 | 16 | // split and reverse 17 | // time complexity: O(len(s)) 18 | // space complexity: O(n) 19 | func reverseWords(s string) string { 20 | words := strings.Split(s, " ") 21 | 22 | var temp []string 23 | for _, word := range words { 24 | temp = append(temp, reverseString(word)) 25 | } 26 | return strings.Join(temp, " ") 27 | } 28 | 29 | func reverseString(s string) string { 30 | runes := []rune(s) 31 | 32 | for start, end := 0, len(runes)-1; start < end; start, end = start+1, end-1 { 33 | runes[start], runes[end] = runes[end], runes[start] 34 | } 35 | return string(runes) 36 | } 37 | -------------------------------------------------------------------------------- /solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3_test.go: -------------------------------------------------------------------------------- 1 | package rwias3 2 | 3 | import "testing" 4 | 5 | func TestReverseWords(t *testing.T) { 6 | s := "Let's take LeetCode contest" 7 | expected := "s'teL ekat edoCteeL tsetnoc" 8 | 9 | if res := reverseWords(s); res != expected { 10 | t.Errorf("expected %s, got %s", expected, res) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /solutions/0674_longest_continuous_increasing_subsequence/lcis.go: -------------------------------------------------------------------------------- 1 | /* 2 | 674. Longest Continuous Increasing Subsequence 3 | https://leetcode.com/problems/longest-continuous-increasing-subsequence/ 4 | 5 | Given an unsorted array of integers, 6 | find the length of longest continuous increasing subsequence (subarray). 7 | */ 8 | // time: 2018-12-29 9 | 10 | package lcis 11 | 12 | // time complexity: O(n), where n is nums's length. 13 | // space complexity: O(1) 14 | func findLengthOfLCIS(nums []int) int { 15 | n := len(nums) 16 | if 0 == n || 1 == n { 17 | return n 18 | } 19 | 20 | var res, l, r int 21 | 22 | for r < n { 23 | if res < r-l+1 { 24 | res = r - l + 1 25 | } 26 | if r+1 < n && nums[r+1] <= nums[r] { 27 | l = r + 1 28 | } 29 | r++ 30 | } 31 | return res 32 | } 33 | 34 | // time complexity: O(n), where n is nums's length. 35 | // space complexity: O(1) 36 | func findLengthOfLCIS1(nums []int) int { 37 | n := len(nums) 38 | if 0 == n || 1 == n { 39 | return n 40 | } 41 | 42 | var ( 43 | maxLen int 44 | count = 1 45 | ) 46 | 47 | for i := 1; i < n; i++ { 48 | if nums[i] > nums[i-1] { 49 | count++ 50 | } else { 51 | count = 1 52 | } 53 | 54 | if count > maxLen { 55 | maxLen = count 56 | } 57 | } 58 | return maxLen 59 | } 60 | -------------------------------------------------------------------------------- /solutions/0674_longest_continuous_increasing_subsequence/lcis_test.go: -------------------------------------------------------------------------------- 1 | package lcis 2 | 3 | import "testing" 4 | 5 | func TestFindLengthOfLCIS(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 3, 5, 4, 7}, 8 | {2, 2, 2, 2, 2}, 9 | {}, 10 | {2}, 11 | } 12 | testFuncs := []func([]int) int{ 13 | findLengthOfLCIS, 14 | findLengthOfLCIS1, 15 | } 16 | 17 | expected := []int{3, 1, 0, 1} 18 | for _, tfn := range testFuncs { 19 | for index, data := range testCases { 20 | if res := tfn(data); res != expected[index] { 21 | t.Errorf("expected %d, got %d", expected[index], res) 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /solutions/0677_map_sum_pairs/map_sum_pairs.go: -------------------------------------------------------------------------------- 1 | /* 2 | 677. Map Sum Pairs 3 | https://leetcode.com/problems/map-sum-pairs/ 4 | 5 | Implement a MapSum class with insert, and sum methods. 6 | 7 | For the method insert, you'll be given a pair of (string, integer). 8 | The string represents the key and the integer represents the value. 9 | If the key already existed, then the original key-value pair will be overridden to the new one. 10 | 11 | For the method sum, you'll be given a string representing the prefix, 12 | and you need to return the sum of all the pairs' value whose key starts with the prefix. 13 | */ 14 | // time: 2019-02-01 15 | 16 | package mapsumpairs 17 | 18 | type node struct { 19 | val int 20 | next map[rune]*node 21 | } 22 | 23 | // MapSum data structure for solution. 24 | type MapSum struct { 25 | root *node 26 | } 27 | 28 | // Constructor initialize data structure here. 29 | func Constructor() MapSum { 30 | return MapSum{&node{next: make(map[rune]*node)}} 31 | } 32 | 33 | // Insert inserts a word into the trie. 34 | func (ms *MapSum) Insert(key string, val int) { 35 | cur := ms.root 36 | for _, c := range key { 37 | if _, ok := cur.next[c]; !ok { 38 | cur.next[c] = &node{next: make(map[rune]*node)} 39 | } 40 | cur = cur.next[c] 41 | } 42 | cur.val = val 43 | } 44 | 45 | // Sum sum of all the pairs' value whose key starts with the prefix. 46 | func (ms *MapSum) Sum(prefix string) int { 47 | cur := ms.root 48 | for _, c := range prefix { 49 | if _, ok := cur.next[c]; !ok { 50 | return 0 51 | } 52 | cur = cur.next[c] 53 | } 54 | return sum(cur) 55 | } 56 | 57 | func sum(n *node) int { 58 | res := n.val 59 | for _, nextNode := range n.next { 60 | res += sum(nextNode) 61 | } 62 | return res 63 | } 64 | -------------------------------------------------------------------------------- /solutions/0677_map_sum_pairs/map_sum_pairs_test.go: -------------------------------------------------------------------------------- 1 | package mapsumpairs 2 | 3 | import "testing" 4 | 5 | func TestMapSumPairs(t *testing.T) { 6 | obj := Constructor() 7 | obj.Insert("apple", 3) 8 | if res := obj.Sum("ap"); res != 3 { 9 | t.Errorf("expected %d, got %d", 3, res) 10 | } 11 | 12 | obj.Insert("app", 2) 13 | if res := obj.Sum("ap"); res != 5 { 14 | t.Errorf("expected %d, got %d", 5, res) 15 | } 16 | 17 | if res := obj.Sum("al"); res != 0 { 18 | t.Errorf("expected %d, got %d", 0, res) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/0704_binary_search/binary_search.go: -------------------------------------------------------------------------------- 1 | /* 2 | 704. Binary Search 3 | https://leetcode.com/problems/binary-search/ 4 | 5 | Given a sorted (in ascending order) integer array nums of n elements and a target value, 6 | write a function to search target in nums. If target exists, then return its index, otherwise return -1. 7 | 8 | Note: 9 | 1. You may assume that all elements in nums are unique. 10 | 2. n will be in the range [1, 10000]. 11 | 3. The value of each element in nums will be in the range [-9999, 9999]. 12 | */ 13 | 14 | // time: 2018-12-19 15 | 16 | package binarysearch 17 | 18 | // iterative 19 | // Time complexity: O(log(n)) 20 | // Space complexity: O(1) 21 | func search(nums []int, target int) int { 22 | var ( 23 | l int 24 | r = len(nums) - 1 25 | ) // 在[l...r]区间寻找target 26 | 27 | for l <= r { // 当l==r时,区间依然是有效的。 28 | mid := l + (r-l)/2 // (l+r)/2 可能会整型益处 29 | if nums[mid] == target { 30 | return mid 31 | } 32 | if nums[mid] > target { 33 | r = mid - 1 34 | } else { 35 | l = mid + 1 36 | } 37 | } 38 | return -1 39 | } 40 | -------------------------------------------------------------------------------- /solutions/0704_binary_search/binary_search_test.go: -------------------------------------------------------------------------------- 1 | package binarysearch 2 | 3 | import "testing" 4 | 5 | func TestSearch(t *testing.T) { 6 | type arg struct { 7 | nums []int 8 | target int 9 | } 10 | 11 | testCases := []arg{ 12 | { 13 | nums: []int{-1, 0, 3, 5, 9, 12}, 14 | target: 9, 15 | }, 16 | { 17 | nums: []int{-1, 0, 3, 5, 9, 12}, 18 | target: -3, 19 | }, 20 | } 21 | 22 | expected := []int{4, -1} 23 | 24 | for index, data := range testCases { 25 | if res := search(data.nums, data.target); res != expected[index] { 26 | t.Errorf("expected %d, got %d", expected[index], res) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /solutions/0713_subarray_product_less_than_k/spltk.go: -------------------------------------------------------------------------------- 1 | /* 2 | 713. Subarray Product Less Than K 3 | https://leetcode.com/problems/subarray-product-less-than-k/ 4 | 5 | Your are given an array of positive integers nums. 6 | 7 | Count and print the number of (contiguous) subarrays 8 | where the product of all the elements in the subarray is less than k. 9 | */ 10 | 11 | // time: 2018-12-27 12 | 13 | package spltk 14 | 15 | // sliding window 16 | // time complexity: O(n), where n = len(nums) 17 | // space complexity: O(1) 18 | func numSubArrayProductLessThanK(nums []int, k int) int { 19 | if k <= 1 { 20 | return 0 21 | } 22 | 23 | var ( 24 | n = len(nums) 25 | l, r int 26 | res int 27 | prod = 1 28 | ) 29 | 30 | for l < n { 31 | if r < n && prod*nums[r] < k { 32 | prod *= nums[r] 33 | r++ 34 | } else if l == r { 35 | l++ 36 | r++ 37 | } else { 38 | res += r - l 39 | prod /= nums[l] 40 | l++ 41 | } 42 | } 43 | return res 44 | } 45 | 46 | // 2019-06-16 47 | func numSubArrayProductLessThanK2(nums []int, k int) int { 48 | if k <= 1 { 49 | return 0 50 | } 51 | var ( 52 | prod = 1 53 | res = 0 54 | left = 0 55 | ) 56 | 57 | for right, val := range nums { 58 | prod *= val 59 | for prod >= k { 60 | prod /= nums[left] 61 | left++ 62 | } 63 | res += right - left + 1 64 | } 65 | return res 66 | } 67 | -------------------------------------------------------------------------------- /solutions/0713_subarray_product_less_than_k/spltk_test.go: -------------------------------------------------------------------------------- 1 | package spltk 2 | 3 | import "testing" 4 | 5 | func TestNumSubArrayProductLessThanK(t *testing.T) { 6 | testCases := [][]int{ 7 | {10, 5, 2, 6}, 8 | {10, 5, 2, 6}, 9 | {10, 5, 100, 6}, 10 | } 11 | 12 | ks := []int{100, 0, 100} 13 | expected := []int{8, 0, 4} 14 | 15 | functions := []func([]int, int) int{ 16 | numSubArrayProductLessThanK, 17 | numSubArrayProductLessThanK2, 18 | } 19 | for _, testFunc := range functions { 20 | for index, data := range testCases { 21 | if res := testFunc(data, ks[index]); res != expected[index] { 22 | t.Errorf("expected %d, got %d", expected[index], res) 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc.go: -------------------------------------------------------------------------------- 1 | /* 2 | 717. 1-bit and 2-bit Characters 3 | https://leetcode.com/problems/1-bit-and-2-bit-characters/ 4 | 5 | We have two special characters. 6 | The first character can be represented by one bit 0. 7 | The second character can be represented by two bits (10 or 11). 8 | 9 | Now given a string represented by several bits. 10 | Return whether the last character must be a one-bit character or not. 11 | The given string will always end with a zero. 12 | 13 | Note: 14 | 1 <= len(bits) <= 1000. 15 | bits[i] is always 0 or 1. 16 | */ 17 | // time: 2018-12-28 18 | 19 | package onebitandtwobitcharacters 20 | 21 | // time complexity: O(n) 22 | // space complexity: O(1) 23 | func isOneBitCharacter(bits []int) bool { 24 | n := len(bits) 25 | if 1 == n { 26 | return true 27 | } 28 | 29 | cur := 0 30 | flag := false 31 | 32 | for cur < n { 33 | if 0 == bits[cur] { 34 | cur++ 35 | } else { 36 | cur += 2 37 | } 38 | if cur == n-1 { 39 | flag = true 40 | } 41 | } 42 | return flag 43 | } 44 | -------------------------------------------------------------------------------- /solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc_test.go: -------------------------------------------------------------------------------- 1 | package onebitandtwobitcharacters 2 | 3 | import "testing" 4 | 5 | func TestIsOneBitCharacter(t *testing.T) { 6 | testCases := [][]int{ 7 | {1, 0, 0}, 8 | {1, 1, 1, 0}, 9 | {0}, 10 | } 11 | expected := []bool{true, false, true} 12 | 13 | for index, bits := range testCases { 14 | if res := isOneBitCharacter(bits); res != expected[index] { 15 | t.Errorf("expected %t, got %t", expected[index], res) 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solutions/0728_self_dividing_numbers/self_dividing_numbers.go: -------------------------------------------------------------------------------- 1 | /* 2 | 728. Self Dividing Numbers 3 | 4 | Source: https://leetcode.com/problems/self-dividing-numbers/ 5 | 6 | A self-dividing number is a number that is divisible by every digit it contains. 7 | 8 | For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. 9 | 10 | Also, a self-dividing number is not allowed to contain the digit zero. 11 | 12 | Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. 13 | 14 | Example 1: 15 | Input: 16 | left = 1, right = 22 17 | Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] 18 | Note: 19 | 20 | The boundaries of each input argument are 1 <= left <= right <= 10000. 21 | 22 | Time: 2018-12-18 23 | */ 24 | 25 | package selfdividingnumbers 26 | 27 | import "strconv" 28 | 29 | //Time complexity: O(right-left+1) 30 | // Space complexity: O(1) 31 | func selfDividingNumbers(left int, right int) []int { 32 | res := make([]int, 0) 33 | 34 | for num := left; num <= right; num++ { 35 | flag := true 36 | strNum := strconv.Itoa(num) 37 | 38 | for j := 0; j < len(strNum); j++ { 39 | if divisor := int(strNum[j] - '0'); divisor == 0 || num%divisor != 0 { 40 | flag = false 41 | } 42 | } 43 | if flag { 44 | res = append(res, num) 45 | } 46 | } 47 | return res 48 | } 49 | -------------------------------------------------------------------------------- /solutions/0728_self_dividing_numbers/self_dividing_numbers_test.go: -------------------------------------------------------------------------------- 1 | package selfdividingnumbers 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSelfDividingNumbers(t *testing.T) { 9 | expected := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22} 10 | if res := selfDividingNumbers(1, 22); !reflect.DeepEqual(res, expected) { 11 | t.Errorf("expected %v, got %v", expected, res) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /solutions/0735_asteroid_collision/ac.go: -------------------------------------------------------------------------------- 1 | /* 2 | 735. Asteroid Collision 3 | https://leetcode.com/problems/asteroid-collision/ 4 | 5 | We are given an array asteroids of integers representing asteroids in a row. 6 | 7 | For each asteroid, the absolute value represents its size, 8 | and the sign represents its direction (positive meaning right, negative meaning left). 9 | Each asteroid moves at the same speed. 10 | 11 | Find out the state of the asteroids after all collisions. 12 | If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. 13 | Two asteroids moving in the same direction will never meet. 14 | 15 | Note: 16 | The length of asteroids will be at most 10000. 17 | Each asteroid will be a non-zero integer in the range [-1000, 1000].. 18 | */ 19 | // time: 2019-01-14 20 | 21 | package ac 22 | 23 | // stack 24 | // time complexity: O(N), where NN is the number of asteroids. Our stack pushes and pops each asteroid at most once. 25 | // space complexity: O(N), the size of stack. 26 | func asteroidCollision(asteroids []int) []int { 27 | stack := make([]int, 0) 28 | 29 | for _, asteroid := range asteroids { 30 | flag := true 31 | for len(stack) > 0 && asteroid < 0 && stack[len(stack)-1] > 0 { 32 | if stack[len(stack)-1] == -asteroid { 33 | stack = stack[:len(stack)-1] 34 | } else if stack[len(stack)-1] < -asteroid { 35 | stack = stack[:len(stack)-1] 36 | continue 37 | } 38 | flag = false 39 | break 40 | } 41 | if flag { 42 | stack = append(stack, asteroid) 43 | } 44 | } 45 | return stack 46 | } 47 | -------------------------------------------------------------------------------- /solutions/0735_asteroid_collision/ac_test.go: -------------------------------------------------------------------------------- 1 | package ac 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestAsteroidCollision(t *testing.T) { 9 | testCases := [][]int{ 10 | {5, 10, -5}, 11 | {-2, 2, -1, -2}, 12 | {-2, -1, 1, 2}, 13 | {8, -8}, 14 | {10, 2, -5}, 15 | } 16 | 17 | expected := [][]int{ 18 | {5, 10}, 19 | {-2}, 20 | {-2, -1, 1, 2}, 21 | {}, 22 | {10}, 23 | } 24 | 25 | for index, asteroids := range testCases { 26 | if res := asteroidCollision(asteroids); !reflect.DeepEqual(res, expected[index]) { 27 | t.Errorf("expected %v, got %v", expected[index], res) 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others.go: -------------------------------------------------------------------------------- 1 | /* 2 | 747. Largest Number At Least Twice of Others 3 | 4 | Source: https://leetcode.com/problems/largest-number-at-least-twice-of-others/ 5 | 6 | In a given integer array nums, there is always exactly one largest element. 7 | 8 | Find whether the largest element in the array is at least twice as much as every other number in the array. 9 | 10 | If it is, return the index of the largest element, otherwise return -1. 11 | 12 | Example 1: 13 | 14 | Input: nums = [3, 6, 1, 0] 15 | Output: 1 16 | Explanation: 6 is the largest integer, and for every other number in the array x, 17 | 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. 18 | 19 | 20 | Example 2: 21 | 22 | Input: nums = [1, 2, 3, 4] 23 | Output: -1 24 | Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. 25 | 26 | 27 | Note: 28 | 29 | 1. nums will have a length in the range [1, 50]. 30 | 2. Every nums[i] will be an integer in the range [0, 99]. 31 | 32 | */ 33 | // 2018-12-18 34 | 35 | package largestnumberatleasttwiceofothers 36 | 37 | import "leetcode/utils" 38 | 39 | // Time complexity: O(n) 40 | // Space complexity: O(1) 41 | func dominantIndex(nums []int) int { 42 | var ( 43 | maxNum = utils.MinInt 44 | res int 45 | ) 46 | 47 | for i, j := range nums { 48 | if j > maxNum { 49 | maxNum = j 50 | res = i 51 | } 52 | } 53 | 54 | for _, j := range nums { 55 | if maxNum < 2*j && j != maxNum { 56 | return -1 57 | } 58 | } 59 | return res 60 | } 61 | -------------------------------------------------------------------------------- /solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others_test.go: -------------------------------------------------------------------------------- 1 | package largestnumberatleasttwiceofothers 2 | 3 | import "testing" 4 | 5 | func TestDominantIndex(t *testing.T) { 6 | testCases := [][]int{ 7 | {0, 0, 0, 1}, 8 | {0, 0, 1, 1}, 9 | {1, 2, 3, 4}, 10 | {3, 6, 1, 0}, 11 | } 12 | expected := []int{3, 2, -1, 1} 13 | for index, data := range testCases { 14 | if res := dominantIndex(data); res != expected[index] { 15 | t.Errorf("expected %d, got %d", expected[index], res) 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /solutions/0872_leaf_similar_trees/leaf_similar_trees.go: -------------------------------------------------------------------------------- 1 | /* 2 | 872. Leaf-Similar Trees 3 | https://leetcode.com/problems/leaf-similar-trees/ 4 | */ 5 | // time: 2019-01-08 6 | 7 | package lst 8 | 9 | import ( 10 | "reflect" 11 | ) 12 | 13 | // TreeNode Definition for a binary tree node. 14 | type TreeNode struct { 15 | Val int 16 | Left *TreeNode 17 | Right *TreeNode 18 | } 19 | 20 | // time complexity: O(n1 + n2), where n is nodes number in the tree. 21 | // space complexity: O(h1 + h2), where h is height of the tree. 22 | func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { 23 | l1 := make([]int, 0) 24 | l2 := make([]int, 0) 25 | 26 | dfs(root1, &l1) 27 | dfs(root2, &l2) 28 | 29 | return reflect.DeepEqual(l1, l2) 30 | } 31 | 32 | func dfs(root *TreeNode, l *[]int) { 33 | if nil == root { 34 | return 35 | } 36 | 37 | if root.Left == nil && root.Right == nil { 38 | *l = append(*l, root.Val) 39 | } 40 | dfs(root.Left, l) 41 | dfs(root.Right, l) 42 | } 43 | -------------------------------------------------------------------------------- /solutions/0872_leaf_similar_trees/leaf_similar_trees_test.go: -------------------------------------------------------------------------------- 1 | package lst 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func createBinaryTree(nums []int) *TreeNode { 9 | return performCreate(nums, 0) 10 | } 11 | 12 | func performCreate(nums []int, index int) *TreeNode { 13 | if index >= len(nums) { 14 | return nil 15 | } 16 | 17 | tree := TreeNode{Val: nums[index]} 18 | tree.Left = performCreate(nums, 2*index+1) 19 | tree.Right = performCreate(nums, 2*index+2) 20 | return &tree 21 | } 22 | 23 | func TestLeafSimilar(t *testing.T) { 24 | type arg struct { 25 | root1, root2 *TreeNode 26 | } 27 | 28 | testCases := []arg{ 29 | {root1: createBinaryTree([]int{3, 5, 1, 6, 2, 9, 8}), root2: createBinaryTree([]int{6, 4, 1, 6, 2, 9, 8})}, 30 | {root1: createBinaryTree([]int{3, 5, 1, 6, 2, 9, 4}), root2: createBinaryTree([]int{6, 4, 1, 6, 2, 9, 8})}, 31 | } 32 | 33 | expected := []bool{true, false} 34 | 35 | for index, data := range testCases { 36 | if res := leafSimilar(data.root1, data.root2); !reflect.DeepEqual(res, expected[index]) { 37 | t.Errorf("expected %t, got %t", expected[index], res) 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses_test.go: -------------------------------------------------------------------------------- 1 | package removeoutmostparentheses 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestRemoveOuterParentheses(t *testing.T) { 8 | testCases := []map[string]string{ 9 | {"case": "(()())(())", "expected": "()()()"}, 10 | {"case": "(()())(())(()(()))", "expected": "()()()()(())"}, 11 | {"case": "", "expected": ""}, 12 | {"case": "()()", "expected": ""}, 13 | } 14 | 15 | for _, testCase := range testCases { 16 | if testCase["expected"] != removeOuterParentheses(testCase["case"]) { 17 | t.Errorf("hello") 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /solutions/148_Sort_List/sortlist.go: -------------------------------------------------------------------------------- 1 | /* 2 | 148. Sort List 3 | https://leetcode.com/problems/sort-list/ 4 | */ 5 | // time: 2019-03-04 6 | 7 | package sortlist 8 | 9 | // ListNode Definition for singly-linked list. 10 | type ListNode struct { 11 | Val int 12 | Next *ListNode 13 | } 14 | 15 | // merge sort 16 | // time complexity: O(n * log(n)) 17 | // using recursion, the system stack is used. 18 | func sortList(head *ListNode) *ListNode { 19 | if head == nil || head.Next == nil { 20 | return head 21 | } 22 | 23 | prev, slow, fast := head, head, head 24 | for fast != nil && fast.Next != nil { 25 | prev = slow 26 | slow = slow.Next 27 | fast = fast.Next.Next 28 | } 29 | prev.Next = nil 30 | return merge(sortList(head), sortList(slow)) 31 | } 32 | 33 | func merge(headA, headB *ListNode) *ListNode { 34 | dummy := &ListNode{} 35 | tail := dummy 36 | 37 | for headA != nil && headB != nil { 38 | if headA.Val > headB.Val { 39 | tail.Next = headB 40 | headB = headB.Next 41 | } else { 42 | tail.Next = headA 43 | headA = headA.Next 44 | } 45 | tail = tail.Next 46 | } 47 | if headA != nil { 48 | tail.Next = headA 49 | } else { 50 | tail.Next = headB 51 | } 52 | return dummy.Next 53 | } 54 | -------------------------------------------------------------------------------- /solutions/148_Sort_List/sortlist_test.go: -------------------------------------------------------------------------------- 1 | package sortlist 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSortList(t *testing.T) { 9 | head := createSingleLinkedList([]int{-1, 5, 3, 4, 0}) 10 | expected := createSingleLinkedList([]int{-1, 0, 3, 4, 5}) 11 | if res := sortList(head); !reflect.DeepEqual(res, expected) { 12 | t.Errorf("expected %v, got %v", expected, res) 13 | } 14 | } 15 | 16 | func createSingleLinkedList(nums []int) *ListNode { 17 | dummy := ListNode{} 18 | cur := &dummy 19 | for _, val := range nums { 20 | cur.Next = &ListNode{Val: val} 21 | cur = cur.Next 22 | } 23 | return dummy.Next 24 | } 25 | -------------------------------------------------------------------------------- /solutions/304_Range_Sum_Query_2D/rsq.go: -------------------------------------------------------------------------------- 1 | /* 2 | 304. Range Sum Query 2D - Immutable 3 | https://leetcode.com/problems/range-sum-query-2d-immutable/ 4 | */ 5 | // 2019-02-27 6 | 7 | package rsq 8 | 9 | // NumMatrix 累计区域和的数组 10 | type NumMatrix struct { 11 | dp [][]int 12 | } 13 | 14 | // Constructor 初始化构造函数 15 | func Constructor(matrix [][]int) NumMatrix { 16 | if len(matrix) == 0 || len(matrix[0]) == 0 { 17 | return NumMatrix{} 18 | } 19 | numMatrix := NumMatrix{dp: make([][]int, len(matrix)+1)} 20 | for i := 0; i < len(numMatrix.dp); i++ { 21 | numMatrix.dp[i] = make([]int, len(matrix[0])+1) 22 | } 23 | 24 | for i := 1; i <= len(matrix); i++ { 25 | for j := 1; j <= len(matrix[0]); j++ { 26 | 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] 27 | } 28 | } 29 | return numMatrix 30 | } 31 | 32 | // SumRegion 求区域和 33 | func (nm *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { 34 | return nm.dp[row2+1][col2+1] - nm.dp[row1][col2+1] - nm.dp[row2+1][col1] + nm.dp[row1][col1] 35 | } 36 | -------------------------------------------------------------------------------- /solutions/304_Range_Sum_Query_2D/rsq_test.go: -------------------------------------------------------------------------------- 1 | package rsq 2 | 3 | import "testing" 4 | 5 | func TestSunRegion(t *testing.T) { 6 | matrix := [][]int{ 7 | {3, 0, 1, 4, 2}, 8 | {5, 6, 3, 2, 1}, 9 | {1, 2, 0, 1, 5}, 10 | {4, 1, 0, 1, 7}, 11 | {1, 0, 3, 0, 5}, 12 | } 13 | 14 | obj := Constructor(matrix) 15 | 16 | testData := [][]int{ 17 | {2, 1, 4, 3}, 18 | {1, 1, 2, 2}, 19 | {1, 2, 2, 4}, 20 | } 21 | expected := []int{8, 11, 12} 22 | 23 | for index, data := range testData { 24 | if res := obj.SumRegion(data[0], data[1], data[2], data[3]); res != expected[index] { 25 | t.Errorf("expected %d, got %d", expected[index], res) 26 | } 27 | } 28 | 29 | if res := Constructor([][]int{}); res.dp != nil { 30 | t.Errorf("expected nil, got %v", res.dp) 31 | } 32 | if res := Constructor(make([][]int, 3)); res.dp != nil { 33 | t.Errorf("expected nil, got %v", res.dp) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ut.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function cleanTestCache() { 4 | go clean -testcache; 5 | } 6 | 7 | function test_() { 8 | go test ./...; 9 | } 10 | 11 | case $1 in 12 | clean) cleanTestCache; 13 | ;; 14 | esac 15 | 16 | test_; 17 | -------------------------------------------------------------------------------- /utils/infinite.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | const ( 4 | // MaxUint max unsigned int. 5 | MaxUint = ^uint(0) 6 | // MaxInt max int. 7 | MaxInt = int(MaxUint >> 1) 8 | 9 | // MinUint min unsigned int. 10 | MinUint = 0 11 | 12 | // MinInt min int 13 | MinInt = -MaxInt - 1 14 | ) 15 | -------------------------------------------------------------------------------- /utils/maxint.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | // CalcMaxInt calc max int from multi nums. 4 | func CalcMaxInt(nums ...int) (res int) { 5 | // 此处也可使用堆排序,构建大顶堆,heapify之后直接取最大值. 6 | if len(nums) == 0 { 7 | return 0 8 | } 9 | 10 | res = nums[0] 11 | 12 | for _, num := range nums { 13 | if num > res { 14 | res = num 15 | } 16 | } 17 | return 18 | } 19 | -------------------------------------------------------------------------------- /utils/maxint_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "testing" 4 | 5 | func TestCalcMaxInt(t *testing.T) { 6 | testData := [][]int{ 7 | {}, 8 | {3, 4, 67, 8}, 9 | } 10 | expectedData := []int{0, 67} 11 | 12 | for index, data := range testData { 13 | if res := CalcMaxInt(data...); res != expectedData[index] { 14 | t.Errorf("expected %d, got %d", expectedData[index], res) 15 | } 16 | } 17 | } 18 | 19 | func BenchmarkCalcMaxInt(b *testing.B) { 20 | data := []int{3, 4, 67, 8} 21 | for i := 0; i < b.N; i++ { 22 | CalcMaxInt(data...) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /utils/minint.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | // CalcMinInt calc min int from multi nums. 4 | func CalcMinInt(nums ...int) (res int) { 5 | // 此处也可使用堆排序,构建小顶堆,heapify之后直接取最小值. 6 | if len(nums) == 0 { 7 | return 0 8 | } 9 | 10 | res = nums[0] 11 | 12 | for _, num := range nums { 13 | if num < res { 14 | res = num 15 | } 16 | } 17 | return 18 | } 19 | -------------------------------------------------------------------------------- /utils/minint_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "testing" 4 | 5 | func TestCalcMinInt(t *testing.T) { 6 | testData := [][]int{ 7 | {3, 4, 67, 8}, 8 | {}, 9 | {54, 3, 12, 1}, 10 | } 11 | expectedData := []int{3, 0, 1} 12 | 13 | for index, data := range testData { 14 | if res := CalcMinInt(data...); res != expectedData[index] { 15 | t.Errorf("expected %d, got %d", expectedData[index], res) 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /utils/set.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | // Exists 空结构体 4 | var Exists = struct{}{} 5 | 6 | // Set data structure implement by go. 7 | type Set map[interface{}]struct{} 8 | 9 | // NewSet 初始化set 10 | func NewSet(items ...interface{}) Set { 11 | s := make(Set) 12 | s.Add(items...) 13 | return s 14 | } 15 | 16 | // Add 向set中添加元素 17 | func (s Set) Add(items ...interface{}) error { 18 | for _, item := range items { 19 | s[item] = Exists 20 | } 21 | return nil 22 | } 23 | 24 | // Contains 查看set中是否存在item 25 | func (s Set) Contains(item interface{}) bool { 26 | _, ok := s[item] 27 | return ok 28 | } 29 | 30 | // Size 集合的大小 31 | func (s Set) Size() int { 32 | return len(s) 33 | } 34 | 35 | // Clear 清空集合 36 | func (s *Set) Clear() { 37 | *s = make(Set) 38 | } 39 | 40 | // Equal 判断两个set是否相等 41 | func (s Set) Equal(other Set) bool { 42 | if s.Size() != other.Size() { 43 | return false 44 | } 45 | for key := range s { 46 | if !other.Contains(key) { 47 | return false 48 | } 49 | } 50 | return true 51 | } 52 | 53 | //IsSubset 判断s是否是other的子集 54 | func (s Set) IsSubset(other Set) bool { 55 | if s.Size() > other.Size() { 56 | return false 57 | } 58 | for key := range s { 59 | if !other.Contains(key) { 60 | return false 61 | } 62 | } 63 | return true 64 | } 65 | -------------------------------------------------------------------------------- /utils/set_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "testing" 5 | "unsafe" 6 | ) 7 | 8 | func TestEmptyStruct(t *testing.T) { 9 | if unsafe.Sizeof(Exists) != 0 { 10 | t.Error("Exists size must be zero.") 11 | } 12 | } 13 | 14 | func TestContains(t *testing.T) { 15 | set := NewSet(3, 4) 16 | set.Add(5) 17 | if set.Contains(3) != true { 18 | t.Error("should contains 4.") 19 | } 20 | 21 | if set.Contains(6) != false { 22 | t.Error("should not contains 6.") 23 | } 24 | } 25 | 26 | func TestSize(t *testing.T) { 27 | set := NewSet(3, 4) 28 | set.Add(5) 29 | if set.Size() != 3 { 30 | t.Error("size should be 3.") 31 | } 32 | } 33 | 34 | func TestEqual(t *testing.T) { 35 | set := NewSet(3, 4) 36 | set.Add(5) 37 | 38 | set1 := NewSet(3, 4, 5) 39 | if set.Equal(set1) != true { 40 | t.Error("set should equal with set1.") 41 | } 42 | set1.Add(6) 43 | if set.Equal(set1) == true { 44 | t.Error("set shouldn't equal with set1.") 45 | } 46 | } 47 | 48 | func TestIsSubset(t *testing.T) { 49 | set := NewSet(3, 4) 50 | set.Add(5) 51 | 52 | set1 := NewSet(3, 4, 5, 6) 53 | 54 | if set1.IsSubset(set) == true { 55 | t.Error("set1 shouldn't be set's subset.") 56 | } 57 | 58 | if set.IsSubset(set1) == false { 59 | t.Error("set should be set1's subset.") 60 | } 61 | } 62 | 63 | func TestClear(t *testing.T) { 64 | set := NewSet(3, 4) 65 | set.Clear() 66 | if set.Size() != 0 { 67 | t.Error("set should be clear.") 68 | } 69 | } 70 | --------------------------------------------------------------------------------