├── README.md ├── add_and_search_word └── add_and_search_word.cpp ├── add_binary ├── add_binary.go └── add_binary_test.go ├── add_digits └── add_digits.go ├── add_two_numbers ├── add_two_numbers.go └── add_two_numbers_test.go ├── additive_number └── additive_number.cpp ├── balanced_bianry_tree └── balanced_bianry_tree.go ├── basic_calculator └── basic_calculator.go ├── basic_calculator_II └── basic_calculator_II.go ├── best_time_to_buy_and_sell_stock └── best_time_to_buy_and_sell_stock.cpp ├── best_time_to_buy_and_sell_stock_II └── best_time_to_buy_and_sell_stock_II.cpp ├── best_time_to_buy_and_sell_stock_III └── best_time_to_buy_and_sell_stock_III.cpp ├── best_time_to_buy_and_sell_stock_IV └── best_time_to_buy_and_sell_stock_IV.cpp ├── best_time_to_buy_and_sell_stock_with_cooldown └── best_time_to_buy_and_sell_stock_with_cooldown.cpp ├── binary_search_tree_iterator └── binary_search_tree_iterator.cpp ├── binary_tree_inorder_traversal └── binary_tree_inorder_traversal.go ├── binary_tree_level_order_traversal └── binary_tree_level_order_traversal.go ├── binary_tree_level_order_traversal_II └── binary_tree_level_order_traversal_II.go ├── binary_tree_maximum_path_sum └── binary_tree_maximum_path_sum.go ├── binary_tree_paths └── binary_tree_paths.go ├── binary_tree_postorder_traversal └── binary_tree_postorder_traversal.go ├── binary_tree_preorder_traversal └── binary_tree_preorder_traversal.go ├── binary_tree_right_side_view └── binary_tree_right_side_view.go ├── binary_tree_zigzag_level_order_traversal └── binary_tree_zigzag_level_order_traversal.go ├── bitwise_AND_of_numbers_range └── bitwise_AND_of_numbers_range.go ├── bulb_switcher └── bulb_switcher.cpp ├── bulls_and_cows └── bulls_and_cows.cpp ├── burst_balloons └── burst_balloons.cpp ├── candy └── candy.go ├── climbing_stairs └── climbing_stairs.go ├── clone_graph └── clone_graph.cpp ├── coin_change └── coin_change.cpp ├── combination_sum ├── combination_sum.go └── combination_sum_test.go ├── combination_sum_II └── combination_sum_II.go ├── combination_sum_IV └── combination_sum_IV.cpp ├── combinations └── combinations.go ├── combinations_sum_III └── combinations_sum_III.go ├── compare_version_numbers └── compare_version_numbers.go ├── construct_binary_tree_from_inorder_and_postorder_traversal └── construct_binary_tree_from_inorder_and_postorder_traversal.go ├── construct_binary_tree_from_preorder_and_inorder_traversal └── construct_binary_tree_from_preorder_and_inorder_traversal.go ├── container_with_most_water ├── container_with_most_water.go └── container_with_most_water_test.go ├── contains_duplicate └── contains_duplicate.go ├── contains_duplicate_II └── contains_duplicate_II.go ├── contains_duplicate_III └── contains_duplicate_III.go ├── convert_sorted_array_to_binary_search_tree └── convert_sorted_array_to_binary_search_tree.go ├── convert_sorted_list_to_binary_search_tree └── convert_sorted_list_to_binary_search_tree.go ├── copy_list_with_random_pointer └── copy_list_with_random_pointer.cpp ├── count_and_say ├── count_and_say.go └── count_and_test.go ├── count_complete_tree_nodes └── count_complete_tree_nodes.cpp ├── count_of_range_sum └── count_of_range_sum.cpp ├── count_of_smaller_numbers_after_self └── count_of_smaller_numbers_after_self.cpp ├── count_primes └── count_primes.go ├── counting_bits ├── counting_bits.cpp └── t ├── course_schedule └── course_schedule.go ├── course_schedule_II └── course_schedule_II.go ├── decode_string └── decode_string.cpp ├── decode_ways └── decode_ways.go ├── delete_node_in_a_linked_list └── delete_node_in_a_linked_list.cpp ├── different_ways_to_add_parentheses └── different_ways_to_add_parentheses.go ├── distinct_subsequences └── distinct_subsequences.go ├── dungeon_game └── dungeon_game.go ├── edit_distance ├── edit_distance.go └── edit_distance_test.go ├── elimination_game └── elimination_game.cpp ├── evaluate_reverse_polish_notation └── evaluate_reverse_polish_notation.go ├── excel_sheet_column_number └── excel_sheet_column_number.go ├── excel_sheet_column_title └── excel_sheet_column_title.go ├── expression_add_operators └── expression_add_operators.cpp ├── factorial_trailing_zeroes └── factorial_trailing_zeroes.go ├── find_k_pairs_with_smallest_sums └── find_k_pairs_with_smallest_sums.cpp ├── find_median_from_data_stream └── find_median_from_data_stream.cpp ├── find_minimum_in_rotated_sorted_array └── find_minimum_in_rotated_sorted_array.go ├── find_minimum_in_rotated_sorted_array_II └── find_minimum_in_rotated_sorted_array_II.go ├── find_peak_element └── find_peak_element.go ├── find_the_difference └── find_the_difference.cpp ├── find_the_duplicate_number └── find_the_duplicate_number.cpp ├── first_bad_version └── first_bad_version.cpp ├── first_missing_positive └── first_missing_positive.go ├── first_unique_character_in_a_string └── first_unique_character_in_a_string.cpp ├── flatten_binary_tree_to_linked_list └── flatten_binary_tree_to_linked_list.go ├── flatten_nested_list_iterator └── flatten_nested_list_iterator.cpp ├── four_sum └── four_sum.go ├── fraction_to_recurring_decimal └── fraction_to_recurring_decimal.go ├── gas_station └── gas_station.go ├── generate_parentheses └── generate_parentheses.go ├── gray_code └── gray_code.go ├── group_anagrams └── group_anagrams.go ├── guess_number_higher_or_lower └── guess_number_higher_or_lower.cpp ├── guess_number_higher_or_lower_II └── guess_number_higher_or_lower_II.cpp ├── happy_number └── happy_number.go ├── house_robber └── house_robber.go ├── house_robber_II └── house_robber_II.go ├── house_robber_III └── house_robber_III.cpp ├── implement_queue_using_stacks └── implement_queue_using_stacks.cpp ├── implement_stack_using_queues └── implement_stack_using_queues.cpp ├── implement_trie └── implement_trie.cpp ├── increasing_triplet_subsequence └── increasing_triplet_subsequence.cpp ├── insertion_sort_list ├── insertion_sort_list.go └── insertion_sort_list_test.go ├── integer_break └── integer_break.cpp ├── integer_to_roman ├── integer_to_roman.go └── integer_to_roman_test.go ├── intersection_of_two_arrays └── intersection_of_two_arrays.cpp ├── intersection_of_two_arrays_II └── intersection_of_two_arrays_II.cpp ├── intersection_of_two_linked_lists └── intersection_of_two_linked_lists.cpp ├── invert_binary_tree └── invert_binary_tree.go ├── is_subsequence └── is_subsequence.cpp ├── isomorphic_strings └── isomorphic_strings.go ├── jump_game └── jump_game.go ├── kth_largest_element_in_an_array └── kth_largest_element_in_an_array.go ├── kth_smallest_element_in_a_BST └── kth_smallest_element_in_a_BST.go ├── kth_smallest_element_in_a_sorted_matrix └── kth_smallest_element_in_a_sorted_matrix.cpp ├── largest_divisible_subset └── largest_divisible_subset.cpp ├── largest_number └── largest_number.go ├── largest_rectangle_in_histogram ├── largest_rectangle_in_histogram.go └── largest_rectangle_in_histogram_test.go ├── length_of_last_word ├── length_of_last_word.go └── length_of_last_word_test.go ├── letter_combinations_of_a_phone_number └── letter_combinations_of_a_phone_number.go ├── lexicographical_numbers └── lexicographical_numbers.cpp ├── linked_list_cycle └── linked_list_cycle.cpp ├── linked_list_cycle_II └── linked_list_cycle_II.cpp ├── longest_absolute_file_path └── longest_absolute_file_path.cpp ├── longest_common_prefix ├── longest_common_prefix.go └── longest_common_prefix_test.go ├── longest_consecutive_sequence └── longest_consecutive_sequence.go ├── longest_increasing_path_in_a_matrix └── longest_increasing_path_in_a_matrix.cpp ├── longest_increasing_subsequence └── longest_increasing_subsequence.cpp ├── longest_palindromic_substring ├── longest_palindromic_substring.go └── longest_palindromic_substring_test.go ├── longest_substring_with_at_least_k_repeating_characters └── longest_substring_with_at_least_k_repeating_characters.cpp ├── longest_substring_without_repeating_characters ├── longest_substring_without_repeating_characters.go └── longest_substring_without_repeating_characters_test.go ├── longest_valid_parentheses ├── longest_valid_parentheses.go └── longest_valid_parentheses_test.go ├── lowest_common_ancestor_of_a_binary_search_tree └── lowest_common_ancestor_of_a_binary_search_tree.cpp ├── lowest_common_ancestor_of_a_binary_tree └── lowest_common_ancestor_of_a_binary_tree.cpp ├── lru_cache └── lru_cache.cpp ├── majority_element └── majority_element.go ├── majority_element_II └── majority_element_II.go ├── max_points_on_a_line └── max_points_on_a_line.go ├── maximal_rectangle └── maximal_rectangle.go ├── maximal_square └── maximal_square.go ├── maximum_depth_of_binary_tree └── maximum_depth_of_binary_tree.go ├── maximum_gap └── maximum_gap.go ├── maximum_product_of_word_lengths └── maximum_product_of_word_lengths.cpp ├── maximum_product_subarray └── maximum_product_subarray.go ├── maximum_subarray └── maximum_subarray.go ├── median_of_two_sorted_arrays ├── median_of_two_sorted_arrays.go └── median_of_two_sorted_arrays_test.go ├── merge_k_sorted_lists ├── merge_k_sorted_lists.go └── merge_k_sorted_lists_test.go ├── merge_sorted_array └── merge_sorted_array.go ├── merge_two_sorted_lists └── merge_two_sorted_lists.go ├── min_stack └── min_stack.cpp ├── minimum_depth_of_binary_tree └── minimum_depth_of_binary_tree.go ├── minimum_height_trees └── minimum_height_trees.cpp ├── minimum_path_sum └── minimum_path_sum.go ├── minimum_size_subarray_sum └── minimum_size_subarray_sum.go ├── minimum_window_substring └── minimum_window_substring.go ├── missing_number └── missing_number.go ├── move_zeroes └── move_zeroes.cpp ├── multiply_strings ├── multiply_strings.go └── multiply_strings_test.go ├── n_queens └── n_queens.cpp ├── n_queens_II └── n_queens_II.go ├── next_permutation └── next_permutation.go ├── nim_game └── nim_game.cpp ├── nth_digit └── nth_digit.cpp ├── number_of_1bits └── number_of_1bits.cpp ├── number_of_islands └── number_of_islands.go ├── palindrome_lined_list └── palindrome_lined_list.go ├── palindrome_number ├── palindrome_number.go └── palindrome_number_test.go ├── palindrome_pairs └── palindrome_pairs.cpp ├── palindrome_partitioning └── palindrome_partitioning.cpp ├── palindrome_partitioning_II └── palindrome_partitioning_II.go ├── partition_list └── partition_list.go ├── pascals_triangle └── pascals_triangle.go ├── pascals_triangle_II └── pascals_triangle_II.go ├── path_sum └── path_sum.go ├── path_sum_II └── path_sum_II.go ├── peeking_iterator └── peeking_iterator.cpp ├── perfect_squares └── perfect_squares.cpp ├── permutation_sequence ├── permutation_sequence.go └── permutation_sequence_test.go ├── permutations ├── permutations.go └── permutations_test.go ├── permutations_II └── permutations_II.go ├── plus_one └── plus_one.go ├── populating_next_right_pointers_in_each_node └── populating_next_right_pointers_in_each_node.cpp ├── populating_next_right_pointers_in_each_node_II └── populating_next_right_pointers_in_each_node_II.cpp ├── pow_x_n └── pow_x_n.go ├── power_of_four └── power_of_four.cpp ├── power_of_three └── power_of_three.cpp ├── power_of_two └── power_of_two.go ├── product_of_array_except_self └── product_of_array_except_self.go ├── range_sum_query_2d_immutable └── range_sum_query_2d_immutable.cpp ├── range_sum_query_immutable └── range_sum_query_immutable.cpp ├── range_sum_query_mutable └── range_sum_query_mutable.cpp ├── ransom_note └── ransom_note.cpp ├── reconstruct_ltinerary └── reconstruct_ltinerary.cpp ├── rectangle_area └── rectangle_area.go ├── regular_expression_matching └── regular_expression_matching.cpp ├── remove_duplicate_letters └── remove_duplicate_letters.cpp ├── remove_duplicates_from_sorted_array └── remove_duplicates_from_sorted_array.go ├── remove_duplicates_from_sorted_array_II └── remove_duplicates_from_sorted_array_II.go ├── remove_duplicates_from_sorted_list └── remove_duplicates_from_sorted_list.go ├── remove_duplicates_from_sorted_list_II └── remove_duplicates_from_sorted_list_II.go ├── remove_element └── remove_element.go ├── remove_invalid_parentheses └── remove_invalid_parentheses.cpp ├── remove_linked_list_elements └── remove_linked_list_elements.go ├── remove_nth_node_from_end_of_list └── remove_nth_node_from_end_of_list.go ├── reorder_list └── reorder_list.go ├── repeated_dna_sequences └── repeated_dna_sequences.go ├── restore_IP_addresses ├── restore_IP_addresses.go └── restore_IP_addresses_test.go ├── reverse_bits └── reverse_bits.cpp ├── reverse_integer ├── reverse_integer.go └── reverse_integer_test.go ├── reverse_linked_list └── reverse_linked_list.go ├── reverse_linked_list_II └── reverse_linked_list_II.go ├── reverse_nodes_in_k_group ├── reverse_nodes_in_k_group.go └── reverse_nodes_in_k_group_test.go ├── reverse_string └── reverse_string.cpp ├── reverse_vowels_of_a_string └── reverse_vowels_of_a_string.cpp ├── reverse_words_in_a_string └── reverse_words_in_a_string.cpp ├── roman_to_integer ├── roman_to_integer.go └── roman_to_integer_test.go ├── rotate_array └── rotate_array.go ├── rotate_function └── rotate_function.cpp ├── rotate_image └── rotate_image.go ├── rotate_list └── rotate_list.go ├── russian_doll_envelopes └── russian_doll_envelopes.cpp ├── same_tree └── same_tree.go ├── search_a_2D_matrix └── search_a_2D_matrix.go ├── search_a_2D_matrix_II └── search_a_2D_matrix_II.go ├── search_for_a_range ├── search_for_a_range.go └── search_for_a_range_test.go ├── search_in_rotated_sorted_array ├── search_in_rotated_sorted_array.go └── search_in_rotated_sorted_array_test.go ├── search_in_rotated_sorted_array_II └── search_in_rotated_sorted_array_II.go ├── search_insert_position └── search_insert_position.go ├── self_crossing └── self_crossing.cpp ├── serialize_and_deserialize_binary_tree └── serialize_and_deserialize_binary_tree.cpp ├── set_matrix_zeroes └── set_matrix_zeroes.go ├── shortest_palindrome └── shortest_palindrome.go ├── shuffle_an_array └── shuffle_an_array.cpp ├── single_number └── single_number.go ├── single_number_II └── single_number_II.go ├── single_number_III └── single_number_III.go ├── sliding_window_maximum └── sliding_window_maximum.go ├── sort_colors └── sort_colors.go ├── sort_list └── sort_list.go ├── spiral_matrix ├── spiral_matrix.go └── spiral_matrix_test.go ├── spiral_matrix_II └── spiral_matrix_II.go ├── string_to_integer ├── string_to_integer.go └── string_to_integer_test.go ├── subsets └── subsets.go ├── subsets_II └── subsets_II.go ├── sum_of_two_integers └── sum_of_two_integers.cpp ├── sum_root_to_leaf_numbers └── sum_root_to_leaf_numbers.go ├── summary_ranges └── summary_ranges.go ├── super_ugly_number └── super_ugly_number.cpp ├── surrounded_regions └── surrounded_regions.go ├── swap_nodes_in_pairs └── swap_nodes_in_pairs.go ├── symmetric_tree └── symmetric_tree.go ├── three_sum ├── three_sum.go └── three_sum_test.go ├── three_sum_closest ├── three_sum_closest.go └── three_sum_closest_test.go ├── top_k_frequent_elements └── top_k_frequent_elements.cpp ├── trapping_rain_water └── trapping_rain_water.go ├── triangle └── triangle.cpp ├── two_sum ├── two_sum.go └── two_sum_test.go ├── two_sum_II └── two_sum_II.go ├── ugly_number └── ugly_number.go ├── ugly_number_II └── ugly_number_II.go ├── unique_binary_search_trees └── unique_binary_search_trees.go ├── unique_binary_search_trees_II └── unique_binary_search_trees_II.go ├── unique_paths └── unique_paths.go ├── unique_paths_II └── unique_paths_II.go ├── valid_anagram └── valid_anagram.go ├── valid_number ├── valid_number.go └── valid_number_test.go ├── valid_palindrome └── valid_palindrome.go ├── valid_parentheses ├── valid_parentheses.go └── valid_parentheses_test.go ├── valid_perfect_square └── valid_perfect_square.cpp ├── valid_sudoku ├── valid_sudoku.go └── valid_sudoku_test.go ├── validate_binary_search_tree └── validate_binary_search_tree.go ├── verify_preorder_serialization_of_a_binary_tree └── verify_preorder_serialization_of_a_binary_tree.cpp ├── wiggle_subsequence └── wiggle_subsequence.cpp ├── word_break └── word_break.cpp ├── word_break_II └── word_break_II.cpp ├── word_ladder └── word_ladder.cpp ├── word_ladder_II └── word_ladder_II.cpp ├── word_pattern └── word_pattern.cpp ├── word_search ├── word_search.go └── word_search_test.go └── zigzag_conversion ├── zigzag_conversion.go └── zigzag_conversion_test.go /add_binary/add_binary.go: -------------------------------------------------------------------------------- 1 | package add_binary 2 | 3 | func addBinary(a string, b string) string { 4 | aBytes, bBytes := []byte(a), []byte(b) 5 | var carry, sum byte = '0', '0' 6 | short, long := aBytes, bBytes 7 | if len(aBytes) > len(bBytes) { 8 | short, long = bBytes, aBytes 9 | } 10 | newShort := make([]byte, len(long)-len(short)) 11 | for i := range newShort { 12 | newShort[i] = '0' 13 | } 14 | newShort = append(newShort, short...) 15 | ret := make([]byte, len(long)+1) 16 | for i := len(long) - 1; i >= 0; i-- { 17 | sum, carry = add(newShort[i], long[i], carry) 18 | ret[i+1] = sum 19 | } 20 | if carry == '1' { 21 | ret[0] = carry 22 | } else { 23 | ret = ret[1:] 24 | } 25 | return string(ret) 26 | } 27 | 28 | func add(a, b, c byte) (byte, byte) { 29 | if a == '0' && b == '0' { 30 | return c, '0' 31 | } 32 | if a == '1' && b == '1' { 33 | return c, '1' 34 | } 35 | if c == '1' { 36 | return '0', '1' 37 | } 38 | return '1', '0' 39 | } 40 | -------------------------------------------------------------------------------- /add_binary/add_binary_test.go: -------------------------------------------------------------------------------- 1 | package add_binary 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestAddBinary(t *testing.T) { 8 | println(addBinary("010", "101")) 9 | } 10 | -------------------------------------------------------------------------------- /add_digits/add_digits.go: -------------------------------------------------------------------------------- 1 | package add_digits 2 | 3 | func addDigits(num int) int { 4 | return (num-1)%9 + 1 5 | } 6 | -------------------------------------------------------------------------------- /add_two_numbers/add_two_numbers.go: -------------------------------------------------------------------------------- 1 | package add_two_numbers 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 9 | carry := 0 10 | tmp1, tmp2 := l1, l2 11 | head := new(ListNode) 12 | var walk *ListNode 13 | first := true 14 | for tmp1 != nil && tmp2 != nil { 15 | walk, carry = step(walk, head, first, tmp1.Val+tmp2.Val+carry) 16 | first = false 17 | tmp1, tmp2 = tmp1.Next, tmp2.Next 18 | } 19 | var remain *ListNode 20 | if tmp1 != nil { 21 | remain = tmp1 22 | } else { 23 | remain = tmp2 24 | } 25 | for remain != nil { 26 | walk, carry = step(walk, head, first, remain.Val+carry) 27 | first = false 28 | remain = remain.Next 29 | } 30 | if carry != 0 { 31 | walk.Next = &ListNode{Val: carry} 32 | } 33 | return head 34 | } 35 | 36 | func step(walk, head *ListNode, first bool, val int) (newWalk *ListNode, carry int) { 37 | if first { 38 | newWalk = head 39 | } else { 40 | walk.Next = new(ListNode) 41 | newWalk = walk.Next 42 | } 43 | if val > 9 { 44 | newWalk.Val = val - 10 45 | carry = 1 46 | } else { 47 | newWalk.Val = val 48 | carry = 0 49 | } 50 | return 51 | } 52 | -------------------------------------------------------------------------------- /add_two_numbers/add_two_numbers_test.go: -------------------------------------------------------------------------------- 1 | package add_two_numbers 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestAddTwoNumbers(t *testing.T) { 8 | left := [][]int{ 9 | []int{3, 2, 4}, 10 | []int{8, 7, 3, 1}, 11 | []int{8, 1}, 12 | } 13 | right := [][]int{ 14 | []int{5, 8, 5}, 15 | []int{2, 1}, 16 | []int{1, 2}, 17 | } 18 | results := [][]int{ 19 | []int{8, 0, 0, 1}, 20 | []int{0, 9, 3, 1}, 21 | []int{9, 3}, 22 | } 23 | caseNum := 3 24 | for i := 0; i < caseNum; i++ { 25 | l, r := generateNodeList(left[i]), generateNodeList(right[i]) 26 | if ret := addTwoNumbers(l, r); !equal(ret, generateNodeList(results[i])) { 27 | t.Fatalf("case %d fails: %v\n", i, ret.Val) 28 | } 29 | } 30 | } 31 | 32 | func generateNodeList(list []int) *ListNode { 33 | if len(list) == 0 { 34 | return nil 35 | } 36 | head := new(ListNode) 37 | walk := head 38 | for index, val := range list { 39 | walk.Val = val 40 | if index != len(list)-1 { 41 | walk.Next = new(ListNode) 42 | walk = walk.Next 43 | } 44 | } 45 | return head 46 | } 47 | 48 | func equal(left, right *ListNode) bool { 49 | tmp1, tmp2 := left, right 50 | for tmp1 != nil && tmp2 != nil { 51 | if tmp1.Val != tmp2.Val { 52 | return false 53 | } 54 | tmp1, tmp2 = tmp1.Next, tmp2.Next 55 | } 56 | if tmp1 != nil || tmp2 != nil { 57 | return false 58 | } 59 | return true 60 | } 61 | -------------------------------------------------------------------------------- /additive_number/additive_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isAdditiveNumber(string num) { 7 | return DFS(num, 0, 0, 0, 0); 8 | } 9 | 10 | bool DFS(string& num, int start, int length, int first, int second) { 11 | if (start == num.size()) { 12 | if (length > 2) return true; 13 | else return false; 14 | } 15 | int current_num = 0; 16 | for (int i = start; i < num.size(); ++i) { 17 | if (num[start] == '0' && i != start) break; 18 | current_num = 10*current_num + num[i]-'0'; 19 | if (length == 0) first = current_num; 20 | else if (length == 1) second = current_num; 21 | else if (current_num != first+second) continue; 22 | else { 23 | first = second; 24 | second = current_num; 25 | } 26 | if (DFS(num, i+1, length+1, first, second)) return true; 27 | } 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /balanced_bianry_tree/balanced_bianry_tree.go: -------------------------------------------------------------------------------- 1 | package balanced_bianry_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func isBalanced(root *TreeNode) bool { 10 | _, ret := helper(root) 11 | return ret 12 | } 13 | 14 | func helper(root *TreeNode) (int, bool) { 15 | if root == nil { 16 | return 0, true 17 | } 18 | leftDepth, leftRet := helper(root.Left) 19 | if !leftRet { 20 | return -1, false 21 | } 22 | rightDepth, rightRet := helper(root.Right) 23 | if !rightRet { 24 | return -1, false 25 | } 26 | if leftDepth > 1+rightDepth || rightDepth > 1+leftDepth { 27 | return -1, false 28 | } 29 | depth := 1 + leftDepth 30 | if rightDepth > leftDepth { 31 | depth = 1 + rightDepth 32 | } 33 | return depth, true 34 | } 35 | -------------------------------------------------------------------------------- /basic_calculator/basic_calculator.go: -------------------------------------------------------------------------------- 1 | package basic_calculator 2 | 3 | func calculate(s string) int { 4 | ret := 0 5 | stack := []int{} 6 | sign := 1 7 | for i := 0; i < len(s); i++ { 8 | if s[i] >= '0' && s[i] <= '9' { 9 | num := 0 10 | for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ { 11 | num = 10*num + int(s[i]-'0') 12 | } 13 | ret += sign * num 14 | i-- 15 | } else if s[i] == '+' { 16 | sign = 1 17 | } else if s[i] == '-' { 18 | sign = -1 19 | } else if s[i] == '(' { 20 | stack = append(stack, ret, sign) 21 | ret = 0 22 | sign = 1 23 | } else if s[i] == ')' { 24 | signTmp := stack[len(stack)-1] 25 | retTmp := stack[len(stack)-2] 26 | stack = stack[:len(stack)-2] 27 | ret = signTmp*ret + retTmp 28 | sign = 1 29 | } 30 | } 31 | return ret 32 | } 33 | -------------------------------------------------------------------------------- /best_time_to_buy_and_sell_stock/best_time_to_buy_and_sell_stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | if (prices.size() == 0) return 0; 5 | int min = prices[0]; 6 | int max = 0; 7 | for (int i = 1; i < prices.size(); ++i) { 8 | int diff = prices[i] - min; 9 | if (diff > max) max = diff; 10 | if (prices[i] < min) min = prices[i]; 11 | } 12 | return max; 13 | } 14 | }; -------------------------------------------------------------------------------- /best_time_to_buy_and_sell_stock_II/best_time_to_buy_and_sell_stock_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | if (prices.size() == 0) return 0; 5 | int ret = 0; 6 | for (int i = 0; i < prices.size()-1; ++i) { 7 | if (prices[i+1] > prices[i]) ret += prices[i+1] - prices[i]; 8 | } 9 | return ret; 10 | } 11 | }; -------------------------------------------------------------------------------- /best_time_to_buy_and_sell_stock_III/best_time_to_buy_and_sell_stock_III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | if (prices.size() == 0) return 0; 5 | vector fn1(prices.size(), 0); 6 | vector fn2(prices.size(), 0); 7 | int minV = prices[0]; 8 | for (int i = 1; i < prices.size(); ++i) { 9 | fn1[i] = max(fn1[i-1], prices[i]-minV); 10 | minV = min(minV, prices[i]); 11 | } 12 | int maxV = prices[prices.size()-1]; 13 | for (int i = prices.size()-2; i >= 0; --i) { 14 | fn2[i] = max(fn2[i+1], maxV-prices[i]); 15 | maxV = max(maxV, prices[i]); 16 | } 17 | int ret = 0; 18 | for (int i = 0; i < fn1.size(); ++i) { 19 | ret = max(ret, fn1[i] + fn2[i]); 20 | } 21 | return ret; 22 | } 23 | }; -------------------------------------------------------------------------------- /best_time_to_buy_and_sell_stock_IV/best_time_to_buy_and_sell_stock_IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(int k, vector& prices) { 4 | if (prices.size() < 2) return 0; 5 | if (k > prices.size()/2) { 6 | int ret = 0; 7 | for (int i = 0; i < prices.size()-1; ++i) { 8 | if (prices[i+1] - prices[i] > 0) ret += prices[i+1] - prices[i]; 9 | } 10 | return ret; 11 | } 12 | vector> dp(k+1, vector(prices.size()+1, 0)); 13 | for (int i = 1; i <= k; ++i) { 14 | int maxV = dp[i-1][0] - prices[0]; 15 | for (int j = 1; j <= prices.size(); ++j) { 16 | dp[i][j] = max(dp[i][j-1], maxV + prices[j-1]); 17 | if (j < prices.size() && dp[i-1][j] - prices[j] > maxV) { 18 | maxV = dp[i-1][j] - prices[j]; 19 | } 20 | } 21 | } 22 | return dp[k][prices.size()]; 23 | } 24 | }; -------------------------------------------------------------------------------- /best_time_to_buy_and_sell_stock_with_cooldown/best_time_to_buy_and_sell_stock_with_cooldown.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | if (prices.size() < 2) return 0; 5 | int buy = -prices[0]; 6 | int sell = -1; 7 | int cold = 0; 8 | int tmp; 9 | for (int i = 1; i < prices.size(); ++i) { 10 | tmp = buy; 11 | buy = max(tmp, cold-prices[i]); 12 | cold = max(cold, sell); 13 | sell = tmp+prices[i]; 14 | } 15 | return max(sell, cold); 16 | } 17 | }; -------------------------------------------------------------------------------- /binary_search_tree_iterator/binary_search_tree_iterator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | }; 9 | 10 | class BSTIterator { 11 | private: 12 | stack stk; 13 | public: 14 | BSTIterator(TreeNode *root) { 15 | while (root != NULL){ 16 | stk.push(root); 17 | root = root->left; 18 | } 19 | } 20 | 21 | /** @return whether we have a next smallest number */ 22 | bool hasNext() { 23 | return !stk.empty(); 24 | } 25 | 26 | /** @return the next smallest number */ 27 | int next() { 28 | auto top = stk.top(); 29 | stk.pop(); 30 | int ret = top->val; 31 | top = top->right; 32 | while (top != NULL){ 33 | stk.push(top); 34 | top = top->left; 35 | } 36 | return ret; 37 | } 38 | }; -------------------------------------------------------------------------------- /binary_tree_inorder_traversal/binary_tree_inorder_traversal.go: -------------------------------------------------------------------------------- 1 | package binary_tree_inorder_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func inorderTraversal(root *TreeNode) []int { 10 | p := root 11 | ret := []int{} 12 | stack := []*TreeNode{} 13 | for p != nil || len(stack) != 0 { 14 | for p != nil { 15 | stack = append(stack, p) 16 | p = p.Left 17 | } 18 | if len(stack) != 0 { 19 | tmp := stack[len(stack)-1] 20 | stack = stack[:len(stack)-1] 21 | p = tmp.Right 22 | ret = append(ret, tmp.Val) 23 | } 24 | } 25 | return ret 26 | } 27 | -------------------------------------------------------------------------------- /binary_tree_level_order_traversal/binary_tree_level_order_traversal.go: -------------------------------------------------------------------------------- 1 | package binary_tree_level_order_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func levelOrder(root *TreeNode) [][]int { 10 | if root == nil { 11 | return [][]int{} 12 | } 13 | stack := []*TreeNode{root} 14 | rets := [][]int{} 15 | for len(stack) != 0 { 16 | tmpStack := []*TreeNode{} 17 | ret := []int{} 18 | for i := range stack { 19 | ret = append(ret, stack[i].Val) 20 | if stack[i].Left != nil { 21 | tmpStack = append(tmpStack, stack[i].Left) 22 | } 23 | if stack[i].Right != nil { 24 | tmpStack = append(tmpStack, stack[i].Right) 25 | } 26 | } 27 | rets = append(rets, ret) 28 | stack = tmpStack 29 | } 30 | return rets 31 | } 32 | -------------------------------------------------------------------------------- /binary_tree_level_order_traversal_II/binary_tree_level_order_traversal_II.go: -------------------------------------------------------------------------------- 1 | package binary_tree_level_order_traversal_II 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func levelOrderBottom(root *TreeNode) [][]int { 10 | tmpRets := [][]int{} 11 | if root == nil { 12 | return tmpRets 13 | } 14 | stack := []*TreeNode{root} 15 | for len(stack) != 0 { 16 | tmps := []*TreeNode{} 17 | ret := []int{} 18 | for i := range stack { 19 | ret = append(ret, stack[i].Val) 20 | if stack[i].Left != nil { 21 | tmps = append(tmps, stack[i].Left) 22 | } 23 | if stack[i].Right != nil { 24 | tmps = append(tmps, stack[i].Right) 25 | } 26 | } 27 | tmpRets = append(tmpRets, ret) 28 | stack = tmps 29 | } 30 | rets := make([][]int, len(tmpRets)) 31 | for i := range tmpRets { 32 | rets[len(tmpRets)-1-i] = tmpRets[i] 33 | } 34 | return rets 35 | } 36 | -------------------------------------------------------------------------------- /binary_tree_maximum_path_sum/binary_tree_maximum_path_sum.go: -------------------------------------------------------------------------------- 1 | package binary_tree_maximum_path_sum 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | type solution struct { 10 | max int 11 | first bool 12 | } 13 | 14 | func maxPathSum(root *TreeNode) int { 15 | s := &solution{first: true} 16 | s.helper(root) 17 | return s.max 18 | } 19 | 20 | func (this *solution) helper(root *TreeNode) (max int) { 21 | if root == nil { 22 | return 0 23 | } 24 | tmp := root.Val 25 | left := this.helper(root.Left) 26 | if left > 0 { 27 | tmp += left 28 | } 29 | right := this.helper(root.Right) 30 | if right > 0 { 31 | tmp += right 32 | } 33 | if this.first || tmp > this.max { 34 | this.first = false 35 | this.max = tmp 36 | } 37 | if left > 0 && left > right { 38 | max = root.Val + left 39 | } else if right > 0 && right > left { 40 | max = root.Val + right 41 | } else { 42 | max = root.Val 43 | } 44 | return 45 | } 46 | -------------------------------------------------------------------------------- /binary_tree_paths/binary_tree_paths.go: -------------------------------------------------------------------------------- 1 | package binary_tree_paths 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | type TreeNode struct { 8 | Val int 9 | Left *TreeNode 10 | Right *TreeNode 11 | } 12 | 13 | type solution struct { 14 | path []*TreeNode 15 | ret []string 16 | } 17 | 18 | func binaryTreePaths(root *TreeNode) []string { 19 | if root == nil { 20 | return []string{} 21 | } 22 | s := &solution{path: []*TreeNode{root}} 23 | s.helper() 24 | return s.ret 25 | } 26 | 27 | func (this *solution) helper() { 28 | if len(this.path) == 0 { 29 | return 30 | } 31 | root := this.path[len(this.path)-1] 32 | if root.Left == nil && root.Right == nil { 33 | s := strconv.Itoa(this.path[0].Val) 34 | for i := 1; i < len(this.path); i++ { 35 | s += "->" + strconv.Itoa(this.path[i].Val) 36 | } 37 | this.ret = append(this.ret, s) 38 | return 39 | } 40 | if root.Left != nil { 41 | this.path = append(this.path, root.Left) 42 | this.helper() 43 | this.path = this.path[:len(this.path)-1] 44 | } 45 | if root.Right != nil { 46 | this.path = append(this.path, root.Right) 47 | this.helper() 48 | this.path = this.path[:len(this.path)-1] 49 | } 50 | return 51 | } 52 | -------------------------------------------------------------------------------- /binary_tree_postorder_traversal/binary_tree_postorder_traversal.go: -------------------------------------------------------------------------------- 1 | package binary_tree_postorder_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func postorderTraversal(root *TreeNode) []int { 10 | rets := []int{} 11 | if root == nil { 12 | return rets 13 | } 14 | stack := []*TreeNode{root} 15 | head := root 16 | for len(stack) != 0 { 17 | node := stack[len(stack)-1] 18 | if node.Left == head || node.Right == head || node.Left == nil && node.Right == nil { 19 | rets = append(rets, node.Val) 20 | stack = stack[:len(stack)-1] 21 | head = node 22 | } else { 23 | if node.Right != nil { 24 | stack = append(stack, node.Right) 25 | } 26 | if node.Left != nil { 27 | stack = append(stack, node.Left) 28 | } 29 | } 30 | } 31 | return rets 32 | } 33 | -------------------------------------------------------------------------------- /binary_tree_preorder_traversal/binary_tree_preorder_traversal.go: -------------------------------------------------------------------------------- 1 | package binary_tree_preorder_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func preorderTraversal(root *TreeNode) []int { 10 | rets := []int{} 11 | if root == nil { 12 | return rets 13 | } 14 | stack := []*TreeNode{} 15 | p := root 16 | for len(stack) != 0 || p != nil { 17 | for p != nil { 18 | rets = append(rets, p.Val) 19 | stack = append(stack, p) 20 | p = p.Left 21 | } 22 | if len(stack) != 0 { 23 | p = stack[len(stack)-1] 24 | stack = stack[:len(stack)-1] 25 | p = p.Right 26 | } 27 | } 28 | return rets 29 | } 30 | -------------------------------------------------------------------------------- /binary_tree_right_side_view/binary_tree_right_side_view.go: -------------------------------------------------------------------------------- 1 | package binary_tree_right_side_view 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func rightSideView(root *TreeNode) []int { 10 | if root == nil { 11 | return []int{} 12 | } 13 | rets := []int{} 14 | queue := []*TreeNode{root} 15 | last := root 16 | for len(queue) != 0 { 17 | top := queue[0] 18 | queue = queue[1:] 19 | if top.Left != nil { 20 | queue = append(queue, top.Left) 21 | } 22 | if top.Right != nil { 23 | queue = append(queue, top.Right) 24 | } 25 | if top == last { 26 | rets = append(rets, top.Val) 27 | if len(queue) != 0 { 28 | last = queue[len(queue)-1] 29 | } 30 | } 31 | } 32 | return rets 33 | } 34 | -------------------------------------------------------------------------------- /binary_tree_zigzag_level_order_traversal/binary_tree_zigzag_level_order_traversal.go: -------------------------------------------------------------------------------- 1 | package binary_tree_zigzag_level_order_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func zigzagLevelOrder(root *TreeNode) [][]int { 10 | if root == nil { 11 | return [][]int{} 12 | } 13 | stack := []*TreeNode{root} 14 | rets := [][]int{} 15 | zigzag := false 16 | for len(stack) != 0 { 17 | tmpStack := []*TreeNode{} 18 | ret := []int{} 19 | for i := range stack { 20 | if zigzag { 21 | ret = append(ret, stack[len(stack)-i-1].Val) 22 | } else { 23 | ret = append(ret, stack[i].Val) 24 | } 25 | if stack[i].Left != nil { 26 | tmpStack = append(tmpStack, stack[i].Left) 27 | } 28 | if stack[i].Right != nil { 29 | tmpStack = append(tmpStack, stack[i].Right) 30 | } 31 | } 32 | zigzag = !zigzag 33 | rets = append(rets, ret) 34 | stack = tmpStack 35 | } 36 | return rets 37 | } 38 | -------------------------------------------------------------------------------- /bitwise_AND_of_numbers_range/bitwise_AND_of_numbers_range.go: -------------------------------------------------------------------------------- 1 | package bitwise_AND_of_numbers_range 2 | 3 | func rangeBitwiseAnd(m int, n int) int { 4 | var cnt uint = 0 5 | for m != n { 6 | cnt++ 7 | m >>= 1 8 | n >>= 1 9 | } 10 | return m << cnt 11 | } 12 | -------------------------------------------------------------------------------- /bulb_switcher/bulb_switcher.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bulbSwitch(int n) { 4 | int ret = 0; 5 | for (int i = 1; i*i <= n; ++i) { 6 | ++ret; 7 | } 8 | return ret; 9 | } 10 | }; -------------------------------------------------------------------------------- /bulls_and_cows/bulls_and_cows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string getHint(string secret, string guess) { 7 | int secret_array[10] = {0}; 8 | int bull = 0; 9 | for (int i = 0; i < secret.size(); ++i) { 10 | if (secret[i] == guess[i]) { 11 | ++bull; 12 | continue; 13 | } 14 | ++secret_array[secret[i]-'0']; 15 | } 16 | int cow = 0; 17 | for (int i = 0; i < guess.size(); ++i) { 18 | if (secret[i] == guess[i]) { 19 | continue; 20 | } 21 | if (secret_array[guess[i]-'0'] !=0 ){ 22 | ++cow; 23 | --secret_array[guess[i]-'0']; 24 | } 25 | } 26 | return to_string(bull) + "A" + to_string(cow) + "B"; 27 | } 28 | }; -------------------------------------------------------------------------------- /burst_balloons/burst_balloons.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxCoins(vector& nums) { 4 | nums.insert(nums.begin(), 1); 5 | nums.push_back(1); 6 | vector> matrix(nums.size(), vector(nums.size(), 0)); 7 | for (int k = 2; k < nums.size(); ++k) { 8 | for (int low = 0; low < nums.size()-k; ++low) { 9 | int high = low+k; 10 | for (int i = low+1; i < high; ++i) { 11 | matrix[low][high] = max(matrix[low][high], nums[low]*nums[i]*nums[high] + matrix[low][i] + matrix[i][high]); 12 | } 13 | } 14 | } 15 | return matrix[0][matrix.size()-1]; 16 | } 17 | }; -------------------------------------------------------------------------------- /candy/candy.go: -------------------------------------------------------------------------------- 1 | package candy 2 | 3 | func candy(ratings []int) int { 4 | if len(ratings) == 0 { 5 | return 0 6 | } 7 | reduceLength, growLength := 0, 1 8 | 9 | pre := 1 10 | ret := 1 11 | for i := 1; i < len(ratings); i++ { 12 | if ratings[i] < ratings[i-1] { 13 | reduceLength++ 14 | if reduceLength >= pre { 15 | ret++ 16 | } 17 | ret += reduceLength 18 | growLength = 1 19 | } else { 20 | cur := 1 21 | if ratings[i] > ratings[i-1] { 22 | cur = growLength + 1 23 | } 24 | growLength = cur 25 | ret += cur 26 | reduceLength = 0 27 | pre = cur 28 | } 29 | } 30 | return ret 31 | } 32 | -------------------------------------------------------------------------------- /climbing_stairs/climbing_stairs.go: -------------------------------------------------------------------------------- 1 | package climbing_stairs 2 | 3 | func climbStairs(n int) int { 4 | if n == 0 { 5 | return 0 6 | } 7 | if n == 1 || n == 2 { 8 | return n 9 | } 10 | step := []int{1, 2} 11 | for i := 2; i < n; i++ { 12 | step = append(step, step[i-1]+step[i-2]) 13 | } 14 | return step[n-1] 15 | } 16 | -------------------------------------------------------------------------------- /clone_graph/clone_graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | struct UndirectedGraphNode { 8 | int label; 9 | vector neighbors; 10 | UndirectedGraphNode(int x) : label(x) {}; 11 | }; 12 | 13 | class Solution { 14 | public: 15 | UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 16 | if (node==NULL) return NULL; 17 | queue q; 18 | unordered_set visited; 19 | unordered_map mapping; 20 | q.push(node); 21 | while (!q.empty()){ 22 | UndirectedGraphNode* p = q.front(); 23 | q.pop(); 24 | if (p==NULL) continue; 25 | UndirectedGraphNode* copy; 26 | if (mapping.find(p)!=mapping.end()){ 27 | copy = mapping[p]; 28 | }else { 29 | copy = new UndirectedGraphNode(p->label); 30 | mapping[p] = copy; 31 | } 32 | visited.insert(p); 33 | for (auto child: p->neighbors){ 34 | if (mapping.find(child)!=mapping.end()){ 35 | copy->neighbors.push_back(mapping[child]); 36 | }else{ 37 | UndirectedGraphNode* copy_child = new UndirectedGraphNode(child->label); 38 | copy->neighbors.push_back(copy_child); 39 | mapping[child] = copy_child; 40 | if (visited.find(child)==visited.end()) q.push(child); 41 | } 42 | } 43 | } 44 | return mapping[node]; 45 | } 46 | }; -------------------------------------------------------------------------------- /coin_change/coin_change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | vector dp(amount+1, amount+1); 5 | dp[0] = 0; 6 | for (int i = 1; i < dp.size(); ++i) { 7 | for (auto coin: coins) { 8 | if (i >= coin) dp[i] = min(dp[i], dp[i-coin]+1); 9 | } 10 | } 11 | return dp.back() == amount+1 ? -1: dp.back(); 12 | } 13 | }; -------------------------------------------------------------------------------- /combination_sum/combination_sum.go: -------------------------------------------------------------------------------- 1 | package combination_sum 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func combinationSum(candidates []int, target int) [][]int { 8 | sort.Ints(candidates) 9 | return DFS(candidates, 0, target, []int{}, [][]int{}) 10 | } 11 | 12 | func DFS(candidates []int, start int, target int, solution []int, results [][]int) (rets [][]int) { 13 | rets = results 14 | if target < 0 { 15 | return 16 | } 17 | if target == 0 { 18 | rets = append(rets, solution) 19 | return 20 | } 21 | for i := start; i < len(candidates); i++ { 22 | if i > start && candidates[i] == candidates[i-1] { 23 | continue 24 | } 25 | candidate := candidates[i] 26 | // here we should copy solution to repliaSolution. Directly using slice(solution) in iteration will make results fail. Fucking golang's slice 27 | repliaSolution := make([]int, len(solution)) 28 | copy(repliaSolution, solution) 29 | repliaSolution = append(repliaSolution, candidate) 30 | rets = DFS(candidates, i, target-candidate, repliaSolution, rets) 31 | repliaSolution = repliaSolution[:len(repliaSolution)-1] 32 | } 33 | return 34 | } 35 | -------------------------------------------------------------------------------- /combination_sum/combination_sum_test.go: -------------------------------------------------------------------------------- 1 | package combination_sum 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestCombinationSum(t *testing.T) { 9 | fmt.Printf("%v\n", combinationSum([]int{2, 3, 6, 7}, 7)) 10 | } 11 | -------------------------------------------------------------------------------- /combination_sum_II/combination_sum_II.go: -------------------------------------------------------------------------------- 1 | package combination_sum_II 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func combinationSum2(candidates []int, target int) [][]int { 8 | sort.Ints(candidates) 9 | return DFS(candidates, 0, target, []int{}, [][]int{}) 10 | } 11 | 12 | func DFS(candidates []int, start int, target int, solution []int, results [][]int) (rets [][]int) { 13 | rets = results 14 | if target < 0 { 15 | return 16 | } 17 | if target == 0 { 18 | rets = append(rets, solution) 19 | return 20 | } 21 | for i := start; i < len(candidates); i++ { 22 | if i > start && candidates[i] == candidates[i-1] { 23 | continue 24 | } 25 | candidate := candidates[i] 26 | repliaSolution := make([]int, len(solution)) 27 | copy(repliaSolution, solution) 28 | repliaSolution = append(repliaSolution, candidate) 29 | rets = DFS(candidates, i+1, target-candidate, repliaSolution, rets) 30 | repliaSolution = repliaSolution[:len(repliaSolution)-1] 31 | } 32 | return 33 | } 34 | -------------------------------------------------------------------------------- /combination_sum_IV/combination_sum_IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int combinationSum4(vector& nums, int target) { 4 | vector dp(target+1, 0); 5 | dp[0] = 1; 6 | for (int i = 1; i <= target; ++i) { 7 | for (auto& num: nums) { 8 | if (num <= i) { 9 | dp[i] += dp[i-num]; 10 | } 11 | } 12 | } 13 | return dp[target]; 14 | } 15 | }; -------------------------------------------------------------------------------- /combinations/combinations.go: -------------------------------------------------------------------------------- 1 | package combinations 2 | 3 | func combine(n int, k int) [][]int { 4 | rets := [][]int{} 5 | if n <= 0 || k <= 0 || n < k { 6 | return rets 7 | } 8 | currentInt := make([]int, k) 9 | solution := []int{} 10 | depth := -1 11 | maxDepth := k - 1 12 | for { 13 | L: 14 | for depth < maxDepth { 15 | for { 16 | childDepth := depth + 1 17 | preInt := currentInt[childDepth] 18 | if preInt == n { 19 | currentInt[childDepth] = 0 20 | break L 21 | } 22 | currentInt[childDepth]++ 23 | if depth == -1 || currentInt[childDepth] > currentInt[depth] { 24 | solution = append(solution, currentInt[childDepth]) 25 | break 26 | } 27 | } 28 | depth++ 29 | } 30 | if depth == maxDepth { 31 | cp := make([]int, len(solution)) 32 | copy(cp, solution) 33 | rets = append(rets, cp) 34 | } 35 | if depth == -1 { 36 | break 37 | } 38 | depth-- 39 | solution = solution[:len(solution)-1] 40 | } 41 | return rets 42 | } 43 | -------------------------------------------------------------------------------- /combinations_sum_III/combinations_sum_III.go: -------------------------------------------------------------------------------- 1 | package combinations_sum_III 2 | 3 | func combinationSum3(k int, n int) [][]int { 4 | return DFS(0, 1, k, n, []int{}) 5 | } 6 | 7 | func DFS(level int, start int, k int, n int, path []int) (ret [][]int) { 8 | if level == k && n == 0 { 9 | cp := make([]int, len(path)) 10 | copy(cp, path) 11 | ret = append(ret, cp) 12 | return 13 | } 14 | for i := start; i <= n && i <= 9; i++ { 15 | path = append(path, i) 16 | tmpRet := DFS(level+1, i+1, k, n-i, path) 17 | ret = append(ret, tmpRet...) 18 | path = path[:len(path)-1] 19 | } 20 | return 21 | } 22 | -------------------------------------------------------------------------------- /compare_version_numbers/compare_version_numbers.go: -------------------------------------------------------------------------------- 1 | package compare_version_numbers 2 | 3 | func compareVersion(version1 string, version2 string) int { 4 | bytes1, bytes2 := []byte(version1), []byte(version2) 5 | bToI := map[byte]int{ 6 | '0': 0, 7 | '1': 1, 8 | '2': 2, 9 | '3': 3, 10 | '4': 4, 11 | '5': 5, 12 | '6': 6, 13 | '7': 7, 14 | '8': 8, 15 | '9': 9, 16 | } 17 | i, j := -1, -1 18 | for i < len(bytes1) || j < len(bytes2) { 19 | var num1, num2 int 20 | for i++; i < len(bytes1) && bytes1[i] != '.'; i++ { 21 | num1 = num1*10 + bToI[bytes1[i]] 22 | } 23 | for j++; j < len(bytes2) && bytes2[j] != '.'; j++ { 24 | num2 = num2*10 + bToI[bytes2[j]] 25 | } 26 | if num1 > num2 { 27 | return 1 28 | } else if num1 < num2 { 29 | return -1 30 | } 31 | } 32 | return 0 33 | } 34 | -------------------------------------------------------------------------------- /construct_binary_tree_from_inorder_and_postorder_traversal/construct_binary_tree_from_inorder_and_postorder_traversal.go: -------------------------------------------------------------------------------- 1 | package construct_binary_tree_from_inorder_and_postorder_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func buildTree(inorder []int, postorder []int) *TreeNode { 10 | m := map[int]int{} 11 | for i := range inorder { 12 | m[inorder[i]] = i 13 | } 14 | return helper(inorder, 0, len(inorder)-1, postorder, 0, len(postorder)-1, m) 15 | } 16 | 17 | func helper(inorder []int, inL, inR int, postorder []int, postL, postR int, m map[int]int) *TreeNode { 18 | if inL > inR || postL > postR { 19 | return nil 20 | } 21 | root := &TreeNode{Val: postorder[postR]} 22 | index := m[root.Val] 23 | root.Left = helper(inorder, inL, index-1, postorder, postL, postL+index-inL-1, m) 24 | root.Right = helper(inorder, index+1, inR, postorder, postL+index-inL, postR-1, m) 25 | return root 26 | } 27 | -------------------------------------------------------------------------------- /construct_binary_tree_from_preorder_and_inorder_traversal/construct_binary_tree_from_preorder_and_inorder_traversal.go: -------------------------------------------------------------------------------- 1 | package construct_binary_tree_from_preorder_and_inorder_traversal 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func buildTree(preorder []int, inorder []int) *TreeNode { 10 | m := map[int]int{} 11 | for i := range inorder { 12 | m[inorder[i]] = i 13 | } 14 | return helper(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1, m) 15 | } 16 | 17 | func helper(preorder []int, preL, preR int, inorder []int, inL, inR int, m map[int]int) *TreeNode { 18 | if preL > preR || inL > inR { 19 | return nil 20 | } 21 | root := &TreeNode{Val: preorder[preL]} 22 | index := m[root.Val] 23 | root.Left = helper(preorder, preL+1, preL+index-inL, inorder, inL, index-1, m) 24 | root.Right = helper(preorder, preL+index-inL+1, preR, inorder, index+1, inR, m) 25 | return root 26 | } 27 | -------------------------------------------------------------------------------- /container_with_most_water/container_with_most_water.go: -------------------------------------------------------------------------------- 1 | package container_with_most_water 2 | 3 | func maxArea(height []int) int { 4 | if len(height) < 2 { 5 | return 0 6 | } 7 | max, left, right := 0, 0, len(height)-1 8 | for left < right { 9 | area := minHeight(height[left], height[right]) * (right - left) 10 | if area > max { 11 | max = area 12 | } 13 | if height[left] < height[right] { 14 | for left < len(height)-1 { 15 | left++ 16 | if height[left] > height[left-1] { 17 | break 18 | } 19 | } 20 | } else { 21 | for right > 0 { 22 | right-- 23 | if height[right] > height[right+1] { 24 | break 25 | } 26 | } 27 | } 28 | } 29 | return max 30 | } 31 | 32 | func minHeight(x, y int) int { 33 | if x < y { 34 | return x 35 | } 36 | return y 37 | } 38 | -------------------------------------------------------------------------------- /container_with_most_water/container_with_most_water_test.go: -------------------------------------------------------------------------------- 1 | package container_with_most_water 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMaxArea(t *testing.T) { 8 | tests := [][]int{ 9 | []int{1, 1}, 10 | []int{1, 2}, 11 | []int{1, 2, 4, 3}, 12 | } 13 | results := []int{ 14 | 1, 15 | 1, 16 | 4, 17 | } 18 | caseNums := 3 19 | for i := 0; i < caseNums; i++ { 20 | if ret := maxArea(tests[i]); ret != results[i] { 21 | t.Fatalf("case %d failed\nactual: %+v, expect: %+v\n", i, ret, results[i]) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /contains_duplicate/contains_duplicate.go: -------------------------------------------------------------------------------- 1 | package contains_duplicate 2 | 3 | func containsDuplicate(nums []int) bool { 4 | m := map[int]bool{} 5 | for i := range nums { 6 | if m[nums[i]] { 7 | return true 8 | } 9 | m[nums[i]] = true 10 | } 11 | return false 12 | } 13 | -------------------------------------------------------------------------------- /contains_duplicate_II/contains_duplicate_II.go: -------------------------------------------------------------------------------- 1 | package contains_duplicate_II 2 | 3 | func containsNearbyDuplicate(nums []int, k int) bool { 4 | m := map[int]int{} 5 | for i := range nums { 6 | if j, ok := m[nums[i]]; ok { 7 | if i-j <= k { 8 | return true 9 | } 10 | } 11 | m[nums[i]] = i 12 | } 13 | return false 14 | } 15 | -------------------------------------------------------------------------------- /contains_duplicate_III/contains_duplicate_III.go: -------------------------------------------------------------------------------- 1 | package contains_duplicate_III 2 | 3 | func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /convert_sorted_array_to_binary_search_tree/convert_sorted_array_to_binary_search_tree.go: -------------------------------------------------------------------------------- 1 | package convert_sorted_array_to_binary_search_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func sortedArrayToBST(nums []int) *TreeNode { 10 | return helper(nums, 0, len(nums)-1) 11 | } 12 | 13 | func helper(nums []int, i, j int) *TreeNode { 14 | if len(nums) == 0 || i > j || i < 0 || j >= len(nums) { 15 | return nil 16 | } 17 | if i == j { 18 | return &TreeNode{Val: nums[i]} 19 | } 20 | mid := i + (j-i)/2 21 | root := &TreeNode{Val: nums[mid]} 22 | root.Left = helper(nums, i, mid-1) 23 | root.Right = helper(nums, mid+1, j) 24 | return root 25 | } 26 | -------------------------------------------------------------------------------- /convert_sorted_list_to_binary_search_tree/convert_sorted_list_to_binary_search_tree.go: -------------------------------------------------------------------------------- 1 | package convert_sorted_list_to_binary_search_tree 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | type TreeNode struct { 9 | Val int 10 | Left *TreeNode 11 | Right *TreeNode 12 | } 13 | 14 | func sortedListToBST(head *ListNode) *TreeNode { 15 | n := 0 16 | tmp := head 17 | for tmp != nil { 18 | n++ 19 | tmp = tmp.Next 20 | } 21 | return helper(&head, 0, n-1) 22 | } 23 | 24 | func helper(head **ListNode, i, j int) *TreeNode { 25 | if i > j || *head == nil { 26 | return nil 27 | } 28 | mid := i + (j-i)/2 29 | left := helper(head, i, mid-1) 30 | root := &TreeNode{Val: (*head).Val} 31 | root.Left = left 32 | *head = (*head).Next 33 | root.Right = helper(head, mid+1, j) 34 | return root 35 | } 36 | -------------------------------------------------------------------------------- /copy_list_with_random_pointer/copy_list_with_random_pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct RandomListNode { 5 | int label; 6 | RandomListNode *next, *random; 7 | RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | RandomListNode *copyRandomList(RandomListNode *head) { 13 | if (head==NULL) return NULL; 14 | auto fake = new RandomListNode(0); 15 | unordered_map mapping; 16 | auto ptr = head; 17 | auto pre_copy = fake; 18 | while (ptr!=NULL){ 19 | RandomListNode* copy_node; 20 | if (mapping.find(ptr)!=mapping.end()) 21 | copy_node = mapping[ptr]; 22 | else{ 23 | copy_node = new RandomListNode(ptr->label); 24 | mapping[ptr] = copy_node; 25 | } 26 | pre_copy->next = copy_node; 27 | pre_copy = pre_copy->next; 28 | 29 | if (ptr->random!=NULL){ 30 | RandomListNode* copy_node_random; 31 | if (mapping.find(ptr->random)!=mapping.end()){ 32 | copy_node_random = mapping[ptr->random]; 33 | } 34 | else{ 35 | copy_node_random = new RandomListNode(ptr->random->label); 36 | mapping[ptr->random] = copy_node_random; 37 | } 38 | copy_node->random = copy_node_random; 39 | } 40 | ptr = ptr->next; 41 | } 42 | return fake->next; 43 | } 44 | }; -------------------------------------------------------------------------------- /count_and_say/count_and_say.go: -------------------------------------------------------------------------------- 1 | package count_and_say 2 | 3 | func countAndSay(n int) string { 4 | if n <= 0 { 5 | return "" 6 | } else if n == 1 { 7 | return "1" 8 | } 9 | rets := countAndSayInts(n) 10 | bytes := make([]byte, len(rets)) 11 | intTobyte := []byte("123456789") 12 | for index, ret := range rets { 13 | bytes[index] = intTobyte[ret-1] 14 | } 15 | return string(bytes) 16 | } 17 | 18 | func countAndSayInts(n int) (rets []int) { 19 | if n < 1 { 20 | return []int{} 21 | } else if n == 1 { 22 | return []int{1} 23 | } 24 | rets = []int{1} 25 | for i := 2; i <= n; i++ { 26 | tmps := []int{} 27 | pre, cnt := -1, 0 28 | for index, val := range rets { 29 | if index == 0 { 30 | pre = val 31 | cnt = 1 32 | continue 33 | } 34 | if val != pre { 35 | tmps = append(tmps, cnt, pre) 36 | pre = val 37 | cnt = 1 38 | } else { 39 | cnt++ 40 | } 41 | } 42 | tmps = append(tmps, cnt, pre) 43 | rets = tmps 44 | } 45 | return 46 | } 47 | -------------------------------------------------------------------------------- /count_and_say/count_and_test.go: -------------------------------------------------------------------------------- 1 | package count_and_say 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestCountAndSay(t *testing.T) { 8 | for i := 0; i < 40; i++ { 9 | println(countAndSay(i)) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /count_complete_tree_nodes/count_complete_tree_nodes.cpp: -------------------------------------------------------------------------------- 1 | struct TreeNode { 2 | int val; 3 | TreeNode *left; 4 | TreeNode *right; 5 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 6 | }; 7 | 8 | class Solution { 9 | public: 10 | int countNodes(TreeNode* root) { 11 | int depth = 0; 12 | TreeNode *left, *right; 13 | left = right = root; 14 | while (left!=NULL && right!=NULL){ 15 | left = left->left; 16 | right = right->right; 17 | ++depth; 18 | } 19 | if (left==NULL && right==NULL) 20 | return (1<left); 22 | int cnt2 = countNodes(root->right); 23 | return cnt1 + cnt2 + 1; 24 | } 25 | }; -------------------------------------------------------------------------------- /count_of_range_sum/count_of_range_sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countRangeSum(vector& nums, int lower, int upper) { 4 | vector sums(nums.size()+1, 0); 5 | for (int i = 0; i < nums.size(); ++i) { 6 | sums[i+1] = sums[i] + nums[i]; 7 | } 8 | return count_when_merging_sort(sums, 0, sums.size(), lower, upper); 9 | } 10 | int count_when_merging_sort(vector& array, int start, int end, int lower, int upper) { 11 | if (end-start <= 1) return 0; 12 | int mid = start + (end-start)/2; 13 | int j = mid, k = mid, t = mid; 14 | int count = count_when_merging_sort(array, start, mid, lower, upper) + count_when_merging_sort(array, mid, end, lower, upper); 15 | vector cache(end-start); 16 | for (int i = start, r = 0; i < mid; ++i, ++r) { 17 | while (k < end && array[k]-array[i] <= upper) ++k; 18 | while (j < end && array[j]-array[i] < lower) ++j; 19 | while (t < end && array[t] < array[i]) cache[r++] = array[t++]; 20 | cache[r] = array[i]; 21 | count += k - j; 22 | } 23 | for (int i = start; i < t; ++i) { 24 | array[i] = cache[i-start]; 25 | } 26 | return count; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /count_of_smaller_numbers_after_self/count_of_smaller_numbers_after_self.cpp: -------------------------------------------------------------------------------- 1 | class binary_index_tree { 2 | vector array; 3 | public: 4 | binary_index_tree(int n): array(n+1, 0) {} 5 | int lowbit(int x) { 6 | return x & (-x); 7 | } 8 | int sum(int idx) { 9 | int ret = 0; 10 | while (idx > 0) { 11 | ret += array[idx]; 12 | idx -= lowbit(idx); 13 | } 14 | return ret; 15 | } 16 | void add(int idx, int val) { 17 | while (idx < array.size()) { 18 | array[idx] += val; 19 | idx += lowbit(idx); 20 | } 21 | } 22 | }; 23 | 24 | class Solution { 25 | public: 26 | vector countSmaller(vector& nums) { 27 | vector sorted = nums; 28 | sort(sorted.begin(), sorted.end()); 29 | unordered_map mapping; 30 | for (int i = 0; i < sorted.size(); ++i) { 31 | mapping[sorted[i]] = i+1; 32 | } 33 | binary_index_tree my_bit(nums.size()); 34 | vector ret(nums.size()); 35 | for (int i = nums.size()-1; i >=0; --i) { 36 | ret[i] = my_bit.sum(mapping[nums[i]]-1); 37 | my_bit.add(mapping[nums[i]], 1); 38 | } 39 | return ret; 40 | } 41 | }; -------------------------------------------------------------------------------- /count_primes/count_primes.go: -------------------------------------------------------------------------------- 1 | package count_primes 2 | 3 | func countPrimes(n int) int { 4 | check := make([]bool, n) 5 | for i := 2; i*i < n; i++ { 6 | if check[i] { 7 | continue 8 | } 9 | for j := i; i*j < n; j++ { 10 | if !check[i*j] { 11 | check[i*j] = true 12 | } 13 | } 14 | } 15 | cnt := 0 16 | for i := 2; i < n; i++ { 17 | if !check[i] { 18 | cnt++ 19 | } 20 | } 21 | return cnt 22 | } 23 | -------------------------------------------------------------------------------- /counting_bits/counting_bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int num) { 4 | vector result(num+1); 5 | result[0] = 0; 6 | for (int i = 1; i <= num; ++i) { 7 | result[i] = result[i&(i-1)] + 1; 8 | } 9 | return result; 10 | } 11 | }; -------------------------------------------------------------------------------- /counting_bits/t: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hitzzc/go-leetcode/5ab4abf42cf31cbaed4e1ee295ab8c6ebf0e7c92/counting_bits/t -------------------------------------------------------------------------------- /course_schedule_II/course_schedule_II.go: -------------------------------------------------------------------------------- 1 | package course_schedule_II 2 | 3 | func findOrder(numCourses int, prerequisites [][]int) []int { 4 | graph := map[int][]int{} 5 | inDegree := make([]int, numCourses) 6 | for i := range prerequisites { 7 | graph[prerequisites[i][1]] = append(graph[prerequisites[i][1]], prerequisites[i][0]) 8 | inDegree[prerequisites[i][0]]++ 9 | } 10 | queue := []int{} 11 | for i := range inDegree { 12 | if inDegree[i] == 0 { 13 | queue = append(queue, i) 14 | } 15 | } 16 | ret := []int{} 17 | for len(queue) != 0 { 18 | head := queue[0] 19 | queue = queue[1:] 20 | for i := range graph[head] { 21 | inDegree[graph[head][i]]-- 22 | if inDegree[graph[head][i]] == 0 { 23 | queue = append(queue, graph[head][i]) 24 | } 25 | } 26 | ret = append(ret, head) 27 | } 28 | if len(ret) != numCourses { 29 | return []int{} 30 | } 31 | return ret 32 | } 33 | -------------------------------------------------------------------------------- /decode_string/decode_string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeString(string s) { 4 | int i = 0; 5 | return decode(s, i); 6 | } 7 | 8 | string decode(string& s, int& idx) { 9 | string ret; 10 | while (idx < s.size() && s[idx] != ']') { 11 | if (s[idx] < '0' || s[idx] > '9') { 12 | ret += s[idx++]; 13 | } else { 14 | int num = 0; 15 | while (s[idx] != '[') { 16 | num = 10*num + s[idx++] - '0'; 17 | } 18 | ++idx; 19 | string tmp = decode(s, idx); 20 | while (num-- > 0) { 21 | ret += tmp; 22 | } 23 | ++idx; 24 | } 25 | } 26 | return ret; 27 | } 28 | }; -------------------------------------------------------------------------------- /decode_ways/decode_ways.go: -------------------------------------------------------------------------------- 1 | package decode_ways 2 | 3 | func numDecodings(s string) int { 4 | bytes := []byte(s) 5 | return numDecodingsI(bytes) 6 | } 7 | 8 | func numDecodingsI(bytes []byte) (ret int) { 9 | length := len(bytes) 10 | if length == 0 { 11 | return 0 12 | } 13 | if length == 1 { 14 | if bytes[0] == '0' { 15 | return 0 16 | } 17 | return 1 18 | } 19 | if bytes[length-1] != '0' { 20 | ret = numDecodingsI(bytes[:length-1]) 21 | if ret == 0 { 22 | return 0 23 | } 24 | } 25 | if (bytes[length-2] == '1' && bytes[length-1] >= '0' && bytes[length-1] <= '9') || (bytes[length-2] == '2' && bytes[length-1] >= '0' && bytes[length-1] <= '6') { 26 | if length == 2 { 27 | ret++ 28 | } else { 29 | ret += numDecodingsI(bytes[:length-2]) 30 | } 31 | } else if bytes[length-2] != '1' && bytes[length-2] != '2' && bytes[length-1] == '0' { 32 | ret = 0 33 | } 34 | return 35 | } 36 | -------------------------------------------------------------------------------- /delete_node_in_a_linked_list/delete_node_in_a_linked_list.cpp: -------------------------------------------------------------------------------- 1 | struct TreeNode { 2 | int val; 3 | TreeNode *left; 4 | TreeNode *right; 5 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 6 | }; 7 | 8 | class Solution { 9 | public: 10 | void deleteNode(ListNode* node) { 11 | while (node->next != NULL) { 12 | node->val = node->next->val; 13 | if (node->next->next == NULL) 14 | node->next = NULL; 15 | else 16 | node = node->next; 17 | } 18 | return; 19 | } 20 | }; -------------------------------------------------------------------------------- /different_ways_to_add_parentheses/different_ways_to_add_parentheses.go: -------------------------------------------------------------------------------- 1 | package different_ways_to_add_parentheses 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func diffWaysToCompute(input string) []int { 8 | return helper(input, map[string][]int{}) 9 | } 10 | 11 | func helper(input string, cache map[string][]int) []int { 12 | if v, ok := cache[input]; ok { 13 | return v 14 | } 15 | ret := []int{} 16 | for i := range input { 17 | if input[i] == '+' || input[i] == '-' || input[i] == '*' { 18 | left := helper(input[:i], cache) 19 | right := helper(input[i+1:], cache) 20 | for j := range left { 21 | for k := range right { 22 | switch input[i] { 23 | case '+': 24 | ret = append(ret, left[j]+right[k]) 25 | case '-': 26 | ret = append(ret, left[j]-right[k]) 27 | case '*': 28 | ret = append(ret, left[j]*right[k]) 29 | } 30 | } 31 | } 32 | } 33 | } 34 | if len(ret) == 0 { 35 | num, _ := strconv.Atoi(input) 36 | ret = append(ret, num) 37 | } 38 | cache[input] = ret 39 | return ret 40 | } 41 | -------------------------------------------------------------------------------- /distinct_subsequences/distinct_subsequences.go: -------------------------------------------------------------------------------- 1 | package distinct_subsequences 2 | 3 | func numDistinct(s string, t string) int { 4 | return numDistinctBytes([]byte(s), []byte(t)) 5 | } 6 | 7 | func numDistinctBytes(s []byte, t []byte) int { 8 | if len(s) == 0 { 9 | return 0 10 | } 11 | if len(t) == 0 { 12 | return 1 13 | } 14 | matrix := make([][]int, len(s)+1) 15 | for i := range matrix { 16 | matrix[i] = make([]int, len(t)+1) 17 | matrix[i][0] = 1 18 | } 19 | for i := 1; i < len(matrix); i++ { 20 | for j := 1; j < len(matrix[i]); j++ { 21 | if s[i-1] != t[j-1] { 22 | matrix[i][j] = matrix[i-1][j] 23 | } else { 24 | matrix[i][j] = matrix[i-1][j-1] + matrix[i-1][j] 25 | } 26 | } 27 | } 28 | return matrix[len(s)][len(t)] 29 | } 30 | -------------------------------------------------------------------------------- /dungeon_game/dungeon_game.go: -------------------------------------------------------------------------------- 1 | package dungeon_game 2 | 3 | func calculateMinimumHP(dungeon [][]int) int { 4 | if len(dungeon) == 0 || len(dungeon[0]) == 0 { 5 | return 0 6 | } 7 | matrix := make([][]int, len(dungeon)) 8 | for i := range matrix { 9 | matrix[i] = make([]int, len(dungeon[0])) 10 | } 11 | rows := len(dungeon) - 1 12 | cols := len(dungeon[0]) - 1 13 | matrix[rows][cols] = dungeon[rows][cols] 14 | for i := rows - 1; i >= 0; i-- { 15 | matrix[i][cols] = min(dungeon[i][cols], matrix[i+1][cols]+dungeon[i][cols]) 16 | } 17 | for j := cols - 1; j >= 0; j-- { 18 | matrix[rows][j] = min(dungeon[rows][j], matrix[rows][j+1]+dungeon[rows][j]) 19 | } 20 | for i := rows - 1; i >= 0; i-- { 21 | for j := cols - 1; j >= 0; j-- { 22 | matrix[i][j] = min(dungeon[i][j], dungeon[i][j]+max(matrix[i+1][j], matrix[i][j+1])) 23 | } 24 | } 25 | if matrix[0][0] >= 0 { 26 | return 1 27 | } 28 | return 1 - 1*matrix[0][0] 29 | } 30 | 31 | func max(i, j int) int { 32 | if i > j { 33 | return i 34 | } 35 | return j 36 | } 37 | 38 | func min(i, j int) int { 39 | if i < j { 40 | return i 41 | } 42 | return j 43 | } 44 | -------------------------------------------------------------------------------- /edit_distance/edit_distance.go: -------------------------------------------------------------------------------- 1 | package edit_distance 2 | 3 | func minDistance(word1 string, word2 string) int { 4 | bytes1, bytes2 := []byte(word1), []byte(word2) 5 | if len(bytes1) == 0 { 6 | return len(bytes2) 7 | } 8 | if len(bytes2) == 0 { 9 | return len(bytes1) 10 | } 11 | matrix := make([][]int, len(bytes1)+1) 12 | for i := range matrix { 13 | matrix[i] = make([]int, len(bytes2)+1) 14 | for j := range matrix[i] { 15 | matrix[i][j] = -1 16 | } 17 | } 18 | matrix[0][0] = 0 19 | 20 | for i := 0; i <= len(bytes1); i++ { 21 | for j := 0; j <= len(bytes2); j++ { 22 | if i > 0 { 23 | matrix[i][j] = min(matrix[i][j], matrix[i-1][j]+1) 24 | } 25 | if j > 0 { 26 | matrix[i][j] = min(matrix[i][j], matrix[i][j-1]+1) 27 | } 28 | if i > 0 && j > 0 { 29 | if bytes1[i-1] == bytes2[j-1] { 30 | matrix[i][j] = min(matrix[i][j], matrix[i-1][j-1]) 31 | } else { 32 | matrix[i][j] = min(matrix[i][j], matrix[i-1][j-1]+1) 33 | } 34 | } 35 | } 36 | } 37 | return matrix[len(bytes1)][len(bytes2)] 38 | } 39 | 40 | func min(i, j int) int { 41 | if i == -1 { 42 | return j 43 | } 44 | if j == -1 { 45 | return i 46 | } 47 | if i < j { 48 | return i 49 | } 50 | return j 51 | } 52 | -------------------------------------------------------------------------------- /edit_distance/edit_distance_test.go: -------------------------------------------------------------------------------- 1 | package edit_distance 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMinDistance(t *testing.T) { 8 | println(minDistance("a", "b")) 9 | } 10 | -------------------------------------------------------------------------------- /elimination_game/elimination_game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lastRemaining(int n) { 4 | return n == 1 ? 1 : 2*(n/2 + 1 - lastRemaining(n/2)); 5 | } 6 | }; -------------------------------------------------------------------------------- /evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go: -------------------------------------------------------------------------------- 1 | package evaluate_reverse_polish_notation 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func evalRPN(tokens []string) int { 8 | cache := []int{} 9 | var num1, num2, num int 10 | for i := range tokens { 11 | if tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/" { 12 | num2 = cache[len(cache)-1] 13 | num1 = cache[len(cache)-2] 14 | cache[len(cache)-2] = calculate(num1, num2, tokens[i]) 15 | cache = cache[:len(cache)-1] 16 | } else { 17 | num, _ = strconv.Atoi(tokens[i]) 18 | cache = append(cache, num) 19 | } 20 | } 21 | return cache[0] 22 | } 23 | 24 | func calculate(num1, num2 int, op string) int { 25 | if op == "+" { 26 | return num1 + num2 27 | } 28 | if op == "-" { 29 | return num1 - num2 30 | } 31 | if op == "*" { 32 | return num1 * num2 33 | } 34 | if op == "/" { 35 | return num1 / num2 36 | } 37 | return 0 38 | } 39 | -------------------------------------------------------------------------------- /excel_sheet_column_number/excel_sheet_column_number.go: -------------------------------------------------------------------------------- 1 | package excel_sheet_column_number 2 | 3 | func titleToNumber(s string) int { 4 | bytes := []byte(s) 5 | var ret int 6 | for i := range bytes { 7 | ret = 26*ret + int(bytes[i]-'A'+1) 8 | } 9 | return ret 10 | } 11 | -------------------------------------------------------------------------------- /excel_sheet_column_title/excel_sheet_column_title.go: -------------------------------------------------------------------------------- 1 | package excel_sheet_column_title 2 | 3 | func convertToTitle(n int) string { 4 | if n == 0 { 5 | return "" 6 | } 7 | bytes := []byte{} 8 | var remainder int 9 | for n > 0 { 10 | remainder = (n - 1) % 26 11 | bytes = append(bytes, 'A'+byte(remainder)) 12 | n = (n - 1) / 26 13 | } 14 | for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { 15 | bytes[i], bytes[j] = bytes[j], bytes[i] 16 | } 17 | return string(bytes) 18 | } 19 | -------------------------------------------------------------------------------- /factorial_trailing_zeroes/factorial_trailing_zeroes.go: -------------------------------------------------------------------------------- 1 | package factorial_trailing_zeroes 2 | 3 | func trailingZeroes(n int) int { 4 | ret := 0 5 | for n > 0 { 6 | ret += n / 5 7 | n /= 5 8 | } 9 | return ret 10 | } 11 | -------------------------------------------------------------------------------- /find_k_pairs_with_smallest_sums/find_k_pairs_with_smallest_sums.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { 4 | priority_queue, vector>, CMP> q; 5 | vector> result; 6 | for (int i = 0; i < min(k, (int)nums1.size()); ++i) { 7 | for (int j = 0; j < min(k, (int)nums2.size()); ++j) { 8 | auto node = make_pair(nums1[i], nums2[j]); 9 | if (q.size() == k && node.first + node.second < q.top().first + q.top().second) { 10 | q.pop(); 11 | } 12 | if (q.size() < k) q.push(node); 13 | } 14 | } 15 | while (!q.empty()) { 16 | result.push_back(q.top()); 17 | q.pop(); 18 | } 19 | return result; 20 | } 21 | 22 | struct CMP { 23 | bool operator () (const pair& a, const pair& b) { 24 | return a.first + a.second < b.first + b.second; 25 | } 26 | }; 27 | }; -------------------------------------------------------------------------------- /find_minimum_in_rotated_sorted_array/find_minimum_in_rotated_sorted_array.go: -------------------------------------------------------------------------------- 1 | package find_minimum_in_rotated_sorted_array 2 | 3 | func findMin(nums []int) int { 4 | return helper(nums, 0, len(nums)-1) 5 | } 6 | 7 | func helper(nums []int, i, j int) int { 8 | if i == j { 9 | return nums[i] 10 | } 11 | if nums[i] < nums[j] { 12 | return nums[i] 13 | } 14 | mid := i + (j-i)/2 15 | if i == mid { 16 | return helper(nums, i+1, j) 17 | } 18 | if nums[i] < nums[mid] { 19 | return helper(nums, mid+1, j) 20 | } 21 | return helper(nums, i, mid) 22 | } 23 | -------------------------------------------------------------------------------- /find_minimum_in_rotated_sorted_array_II/find_minimum_in_rotated_sorted_array_II.go: -------------------------------------------------------------------------------- 1 | package find_minimum_in_rotated_sorted_array_II 2 | 3 | func findMin(nums []int) int { 4 | return helper(nums, 0, len(nums)-1) 5 | } 6 | 7 | func helper(nums []int, left, right int) int { 8 | if left == right { 9 | return nums[left] 10 | } 11 | if nums[left] < nums[right] { 12 | return nums[left] 13 | } 14 | mid := left + (right-left)/2 15 | if nums[left] == nums[mid] && nums[mid] == nums[right] { 16 | for ; left < right && nums[left] == nums[right]; left++ { 17 | } 18 | return helper(nums, left, right) 19 | } 20 | if nums[left] <= nums[mid] { 21 | return helper(nums, mid+1, right) 22 | } 23 | return helper(nums, left, mid) 24 | } 25 | -------------------------------------------------------------------------------- /find_peak_element/find_peak_element.go: -------------------------------------------------------------------------------- 1 | package find_peak_element 2 | 3 | func findPeakElement(nums []int) int { 4 | left, right := 0, len(nums)-1 5 | for left <= right { 6 | if left == right { 7 | return left 8 | } 9 | mid := left + (right-left)/2 10 | if nums[mid] < nums[mid+1] { 11 | left = mid + 1 12 | } else { 13 | right = mid 14 | } 15 | } 16 | return -1 17 | } 18 | -------------------------------------------------------------------------------- /find_the_difference/find_the_difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findTheDifference(string s, string t) { 4 | vector vec(26, 0); 5 | for (auto& c: s) { 6 | ++vec[c-'a']; 7 | } 8 | char ret; 9 | for (auto& c: t) { 10 | if (vec[c-'a'] == 0) { 11 | ret = c; 12 | break; 13 | } 14 | --vec[c-'a']; 15 | } 16 | return ret; 17 | } 18 | }; -------------------------------------------------------------------------------- /find_the_duplicate_number/find_the_duplicate_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | int i = 0; 5 | int j = 0; 6 | while (true) { 7 | i = nums[i]; 8 | j = nums[nums[j]]; 9 | if (i == j) break; 10 | } 11 | j = 0; 12 | while (i != j) { 13 | i = nums[i]; 14 | j = nums[j]; 15 | } 16 | return i; 17 | } 18 | }; -------------------------------------------------------------------------------- /first_bad_version/first_bad_version.cpp: -------------------------------------------------------------------------------- 1 | bool isBadVersion(int version); 2 | 3 | class Solution { 4 | public: 5 | int firstBadVersion(int n) { 6 | int i = 1; 7 | int j = n; 8 | int ret; 9 | while (i <= j) { 10 | int mid = i + (j-i)/2; 11 | if (isBadVersion(mid)) { 12 | j = mid; 13 | ret = mid; 14 | }else { 15 | i= mid+1; 16 | ret = mid+1; 17 | } 18 | } 19 | return ret; 20 | } 21 | }; -------------------------------------------------------------------------------- /first_missing_positive/first_missing_positive.go: -------------------------------------------------------------------------------- 1 | package first_missing_positive 2 | 3 | func firstMissingPositive(nums []int) int { 4 | for i := range nums { 5 | for nums[i] > 0 && nums[i] <= len(nums) && nums[i] != nums[nums[i]-1] { 6 | nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] 7 | } 8 | } 9 | for i := range nums { 10 | if nums[i] != i+1 { 11 | return i + 1 12 | } 13 | } 14 | return len(nums) + 1 15 | } 16 | -------------------------------------------------------------------------------- /first_unique_character_in_a_string/first_unique_character_in_a_string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstUniqChar(string s) { 4 | unordered_map m; 5 | for (auto& ch: s) { 6 | ++m[ch]; 7 | } 8 | for (int i = 0; i < s.size(); ++i) { 9 | if (m[s[i]] == 1) return i; 10 | } 11 | return -1; 12 | } 13 | }; -------------------------------------------------------------------------------- /flatten_binary_tree_to_linked_list/flatten_binary_tree_to_linked_list.go: -------------------------------------------------------------------------------- 1 | package flatten_binary_tree_to_linked_list 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func flatten(root *TreeNode) { 10 | var pre *TreeNode 11 | helper(root, &pre) 12 | return 13 | } 14 | 15 | func helper(root *TreeNode, pre **TreeNode) { 16 | if root == nil { 17 | return 18 | } 19 | if *pre != nil { 20 | (*pre).Left = nil 21 | (*pre).Right = root 22 | } 23 | *pre = root 24 | left := root.Left 25 | right := root.Right 26 | if left != nil { 27 | helper(left, pre) 28 | } 29 | if right != nil { 30 | helper(right, pre) 31 | } 32 | return 33 | } 34 | -------------------------------------------------------------------------------- /four_sum/four_sum.go: -------------------------------------------------------------------------------- 1 | package four_sum 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func fourSum(nums []int, target int) [][]int { 8 | sort.Ints(nums) 9 | var ret [][]int 10 | for i := 0; i < len(nums)-3; i++ { 11 | if i > 0 && nums[i-1] == nums[i] { 12 | continue 13 | } 14 | for j := i + 1; j < len(nums)-2; j++ { 15 | if j > i+1 && nums[j-1] == nums[j] { 16 | continue 17 | } 18 | left, right := j+1, len(nums)-1 19 | for left < right { 20 | if left > j+1 && nums[left-1] == nums[left] { 21 | left++ 22 | continue 23 | } 24 | if nums[i]+nums[j]+nums[left]+nums[right] == target { 25 | ret = append(ret, []int{nums[i], nums[j], nums[left], nums[right]}) 26 | left++ 27 | right-- 28 | } else if nums[i]+nums[j]+nums[left]+nums[right] < target { 29 | left++ 30 | } else { 31 | right-- 32 | } 33 | } 34 | } 35 | } 36 | return ret 37 | } 38 | -------------------------------------------------------------------------------- /fraction_to_recurring_decimal/fraction_to_recurring_decimal.go: -------------------------------------------------------------------------------- 1 | package fraction_to_recurring_decimal 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func fractionToDecimal(numerator int, denominator int) string { 8 | if numerator == 0 { 9 | return "0" 10 | } 11 | m := []byte("0123456789") 12 | var ret string 13 | var neg bool 14 | if numerator < 0 { 15 | numerator *= -1 16 | neg = !neg 17 | } 18 | if denominator < 0 { 19 | denominator *= -1 20 | neg = !neg 21 | } 22 | if neg { 23 | ret = "-" 24 | } 25 | ret += strconv.Itoa(numerator / denominator) 26 | remainder := numerator % denominator 27 | if remainder == 0 { 28 | return ret 29 | } 30 | ret += "." 31 | floatBytes := []byte{} 32 | indexMap := map[int]int{} 33 | for remainder != 0 { 34 | if idx, ok := indexMap[remainder]; ok { 35 | return ret + string(floatBytes[:idx]) + "(" + string(floatBytes[idx:]) + ")" 36 | } 37 | indexMap[remainder] = len(floatBytes) 38 | remainder *= 10 39 | v := m[remainder/denominator] 40 | remainder %= denominator 41 | floatBytes = append(floatBytes, v) 42 | } 43 | return ret + string(floatBytes) 44 | } 45 | -------------------------------------------------------------------------------- /gas_station/gas_station.go: -------------------------------------------------------------------------------- 1 | package gas_station 2 | 3 | func canCompleteCircuit(gas []int, cost []int) int { 4 | var total, sum, diff, start int 5 | for i := range gas { 6 | diff = gas[i] - cost[i] 7 | total += diff 8 | if sum < 0 { 9 | sum = diff 10 | start = i 11 | } else { 12 | sum += diff 13 | } 14 | } 15 | if total < 0 { 16 | return -1 17 | } else { 18 | return start 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /generate_parentheses/generate_parentheses.go: -------------------------------------------------------------------------------- 1 | package generate_parentheses 2 | 3 | func generateParenthesis(n int) []string { 4 | if n == 0 { 5 | return []string{} 6 | } 7 | var ret []string 8 | tmps := generateParenthesisI(n-1, n, 1) 9 | for index := range tmps { 10 | ret = append(ret, "("+tmps[index]) 11 | } 12 | return ret 13 | } 14 | 15 | func generateParenthesisI(left, right, sum int) []string { 16 | if left == 0 { 17 | bytes := make([]byte, right) 18 | for index := range bytes { 19 | bytes[index] = ')' 20 | } 21 | return []string{string(bytes)} 22 | } 23 | var ret []string 24 | if sum == 0 { 25 | tmps := generateParenthesisI(left-1, right, 1) 26 | for index := range tmps { 27 | ret = append(ret, "("+tmps[index]) 28 | } 29 | } else { 30 | tmps := generateParenthesisI(left-1, right, sum+1) 31 | for index := range tmps { 32 | ret = append(ret, "("+tmps[index]) 33 | } 34 | tmps = generateParenthesisI(left, right-1, sum-1) 35 | for index := range tmps { 36 | ret = append(ret, ")"+tmps[index]) 37 | } 38 | } 39 | return ret 40 | } 41 | -------------------------------------------------------------------------------- /gray_code/gray_code.go: -------------------------------------------------------------------------------- 1 | package gray_code 2 | 3 | func grayCode(n int) []int { 4 | if n == 0 { 5 | return []int{0} 6 | } 7 | if n == 1 { 8 | return []int{0, 1} 9 | } 10 | tmps := grayCode(n - 1) 11 | rets := make([]int, 2*len(tmps)) 12 | ones := 1 13 | for n > 1 { 14 | ones *= 2 15 | n-- 16 | } 17 | for i, tmp := range tmps { 18 | rets[i] = tmp 19 | rets[2*len(tmps)-i-1] = tmp + ones 20 | } 21 | return rets 22 | } 23 | -------------------------------------------------------------------------------- /group_anagrams/group_anagrams.go: -------------------------------------------------------------------------------- 1 | package group_anagrams 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | type bytes []byte 8 | 9 | func (this bytes) Len() int { 10 | return len(this) 11 | } 12 | 13 | func (this bytes) Less(i, j int) bool { 14 | return this[i] < this[j] 15 | } 16 | 17 | func (this bytes) Swap(i, j int) { 18 | this[i], this[j] = this[j], this[i] 19 | } 20 | 21 | func groupAnagrams(strs []string) [][]string { 22 | var ret [][]string 23 | indexMap := map[string]int{} 24 | for i := range strs { 25 | key := bytes(strs[i]) 26 | sort.Sort(key) 27 | keyString := string(key) 28 | if _, ok := indexMap[keyString]; !ok { 29 | indexMap[keyString] = len(ret) 30 | ret = append(ret, []string{strs[i]}) 31 | } else { 32 | ret[indexMap[keyString]] = append(ret[indexMap[keyString]], strs[i]) 33 | } 34 | } 35 | return ret 36 | } 37 | -------------------------------------------------------------------------------- /guess_number_higher_or_lower/guess_number_higher_or_lower.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of guess API. 2 | // @param num, your guess 3 | // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | int guess(int num); 5 | 6 | class Solution { 7 | public: 8 | int guessNumber(int n) { 9 | int left = 1, right = n; 10 | int mid; 11 | while (left <= right) { 12 | mid = left + (right-left)/2; 13 | cout << mid << endl; 14 | if (guess(mid) == 0) break; 15 | else if (guess(mid) > 0) left = mid+1; 16 | else right = mid-1; 17 | } 18 | return mid; 19 | } 20 | }; -------------------------------------------------------------------------------- /guess_number_higher_or_lower_II/guess_number_higher_or_lower_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getMoneyAmount(int n) { 4 | vector> dp(n+1, vector(n+1, 0)); 5 | for (int gap = 1; gap < n; ++gap) { 6 | for (int low = 1; low <= n-gap; ++low) { 7 | int high = low + gap; 8 | dp[low][high] = INT_MAX; 9 | for (int i = low; i < high; ++i) { 10 | dp[low][high] = min(dp[low][high], i + max(dp[low][i-1], dp[i+1][high])); 11 | } 12 | } 13 | } 14 | return dp[1][n]; 15 | } 16 | }; -------------------------------------------------------------------------------- /happy_number/happy_number.go: -------------------------------------------------------------------------------- 1 | package happy_number 2 | 3 | func isHappy(n int) bool { 4 | happened := map[int]bool{} 5 | for n != 1 { 6 | n = squares(n) 7 | if happened[n] { 8 | return false 9 | } 10 | happened[n] = true 11 | } 12 | return true 13 | } 14 | 15 | func squares(n int) (ret int) { 16 | for n > 0 { 17 | num := n % 10 18 | ret += num * num 19 | n /= 10 20 | } 21 | return 22 | } 23 | -------------------------------------------------------------------------------- /house_robber/house_robber.go: -------------------------------------------------------------------------------- 1 | package house_robber 2 | 3 | func rob(nums []int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | if len(nums) == 1 { 8 | return nums[0] 9 | } 10 | array := make([]int, len(nums)) 11 | array[0] = nums[0] 12 | if array[0] > nums[1] { 13 | array[1] = array[0] 14 | } else { 15 | array[1] = nums[1] 16 | } 17 | for i := 2; i < len(nums); i++ { 18 | if array[i-1] > array[i-2]+nums[i] { 19 | array[i] = array[i-1] 20 | } else { 21 | array[i] = array[i-2] + nums[i] 22 | } 23 | } 24 | return array[len(array)-1] 25 | } 26 | -------------------------------------------------------------------------------- /house_robber_II/house_robber_II.go: -------------------------------------------------------------------------------- 1 | package house_robber_II 2 | 3 | func rob(nums []int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | if len(nums) == 1 { 8 | return nums[0] 9 | } 10 | if len(nums) == 2 { 11 | return max(nums[0], nums[1]) 12 | } 13 | x := helper(nums, 0, len(nums)-2) 14 | y := helper(nums, 1, len(nums)-1) 15 | return max(x, y) 16 | } 17 | 18 | func helper(nums []int, i, j int) int { 19 | var n1, n2, current int 20 | for ; i <= j; i++ { 21 | current = max(n1, n2+nums[i]) 22 | n2 = n1 23 | n1 = current 24 | } 25 | return n1 26 | } 27 | 28 | func max(i, j int) int { 29 | if i > j { 30 | return i 31 | } 32 | return j 33 | } 34 | -------------------------------------------------------------------------------- /house_robber_III/house_robber_III.cpp: -------------------------------------------------------------------------------- 1 | struct TreeNode { 2 | int val; 3 | TreeNode *left; 4 | TreeNode *right; 5 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 6 | }; 7 | 8 | class Solution { 9 | unordered_map records; 10 | public: 11 | int rob(TreeNode* root) { 12 | if (root == NULL) return 0; 13 | if (records.count(root) == 0) { 14 | int left = rob(root->left); 15 | int right = rob(root->right); 16 | int without_left = 0, without_right = 0; 17 | if (root->left) without_left = rob(root->left->left) + rob(root->left->right); 18 | if (root->right) without_right = rob(root->right->left) + rob(root->right->right); 19 | records[root] = max(root->val+without_left+without_right, left+right); 20 | } 21 | return records[root]; 22 | } 23 | }; -------------------------------------------------------------------------------- /implement_queue_using_stacks/implement_queue_using_stacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Queue { 5 | public: 6 | stack push_stack; 7 | stack pop_stack; 8 | // Push element x to the back of queue. 9 | void push(int x) { 10 | push_stack.push(x); 11 | } 12 | 13 | // Removes the element from in front of queue. 14 | void pop(void) { 15 | if (pop_stack.empty()){ 16 | while (!push_stack.empty()) { 17 | pop_stack.push(push_stack.top()); 18 | push_stack.pop(); 19 | } 20 | } 21 | pop_stack.pop(); 22 | } 23 | 24 | // Get the front element. 25 | int peek(void) { 26 | if (pop_stack.empty()){ 27 | while (!push_stack.empty()) { 28 | pop_stack.push(push_stack.top()); 29 | push_stack.pop(); 30 | } 31 | } 32 | return pop_stack.top(); 33 | } 34 | 35 | // Return whether the queue is empty. 36 | bool empty(void) { 37 | return pop_stack.empty() && push_stack.empty(); 38 | } 39 | }; -------------------------------------------------------------------------------- /implement_stack_using_queues/implement_stack_using_queues.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Stack { 4 | public: 5 | queue q; 6 | // Push element x onto stack. 7 | void push(int x) { 8 | q.push(x); 9 | } 10 | 11 | // Removes the element on top of the stack. 12 | void pop() { 13 | int num = q.size() - 1; 14 | while (num-- > 0){ 15 | q.push(q.front()); 16 | q.pop(); 17 | } 18 | q.pop(); 19 | } 20 | 21 | // Get the top element. 22 | int top() { 23 | return q.back(); 24 | } 25 | 26 | // Return whether the stack is empty. 27 | bool empty() { 28 | return q.empty(); 29 | } 30 | }; -------------------------------------------------------------------------------- /increasing_triplet_subsequence/increasing_triplet_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool increasingTriplet(vector& nums) { 4 | if (nums.size() < 3) return false; 5 | int first = nums[0], second = INT_MAX; 6 | for (int i = 1; i < nums.size(); ++i) { 7 | if (nums[i] > second) return true; 8 | else if (nums[i] < first) first= nums[i]; 9 | else if (nums[i] > first && nums[i] < second) second = nums[i]; 10 | } 11 | return false; 12 | } 13 | }; -------------------------------------------------------------------------------- /insertion_sort_list/insertion_sort_list.go: -------------------------------------------------------------------------------- 1 | package insertion_sort_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func insertionSortList(head *ListNode) *ListNode { 9 | if head == nil || head.Next == nil { 10 | return head 11 | } 12 | fake := &ListNode{Next: head} 13 | tail := head 14 | var cur *ListNode 15 | for tail.Next != nil { 16 | cur = tail.Next 17 | p := fake 18 | for ; p.Next != cur; p = p.Next { 19 | if p.Next.Val >= cur.Val { 20 | tmp := p.Next 21 | p.Next = cur 22 | tail.Next = cur.Next 23 | cur.Next = tmp 24 | break 25 | } 26 | } 27 | if p == tail { 28 | tail = cur 29 | } 30 | } 31 | return fake.Next 32 | } 33 | -------------------------------------------------------------------------------- /insertion_sort_list/insertion_sort_list_test.go: -------------------------------------------------------------------------------- 1 | package insertion_sort_list 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func (this *ListNode) insert(val int) { 8 | p := this 9 | for p.Next != nil { 10 | p = p.Next 11 | } 12 | p.Next = &ListNode{Val: val} 13 | } 14 | 15 | func (this *ListNode) print() { 16 | p := this 17 | for p != nil { 18 | println(p.Val) 19 | p = p.Next 20 | } 21 | } 22 | 23 | func TestInsertionSortList(t *testing.T) { 24 | head := &ListNode{Val: 3} 25 | head.insert(2) 26 | head.insert(1) 27 | head.insert(4) 28 | head.insert(5) 29 | head.insert(1) 30 | head = insertionSortList(head) 31 | head.print() 32 | } 33 | -------------------------------------------------------------------------------- /integer_break/integer_break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int integerBreak(int n) { 4 | if (n == 2) return 1; 5 | if (n == 3) return 2; 6 | int result = 1; 7 | while (n > 4) { 8 | result *= 3; 9 | n -= 3; 10 | } 11 | result *= n; 12 | return result; 13 | } 14 | }; -------------------------------------------------------------------------------- /integer_to_roman/integer_to_roman.go: -------------------------------------------------------------------------------- 1 | package integer_to_roman 2 | 3 | func intToRoman(num int) string { 4 | romanMap := [][]string{ 5 | []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, 6 | []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, 7 | []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, 8 | []string{"", "M", "MM", "MMM"}, 9 | } 10 | digits, tmp := 0, num 11 | var ret string 12 | for tmp > 0 { 13 | remain := tmp % 10 14 | ret = romanMap[digits][remain] + ret 15 | tmp = tmp / 10 16 | digits++ 17 | } 18 | return ret 19 | } 20 | -------------------------------------------------------------------------------- /integer_to_roman/integer_to_roman_test.go: -------------------------------------------------------------------------------- 1 | package integer_to_roman 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIntToRoman(t *testing.T) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /intersection_of_two_arrays/intersection_of_two_arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersection(vector& nums1, vector& nums2) { 4 | unordered_set s, visited; 5 | for (auto& num: nums1) { 6 | s.insert(num); 7 | } 8 | vector res; 9 | for (auto& num: nums2) { 10 | if (s.count(num) && visited.count(num) == 0) res.push_back(num); 11 | visited.insert(num); 12 | } 13 | return res; 14 | } 15 | }; -------------------------------------------------------------------------------- /intersection_of_two_arrays_II/intersection_of_two_arrays_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& nums1, vector& nums2) { 4 | unordered_map m; 5 | for (auto& num: nums1) { 6 | ++m[num]; 7 | } 8 | vector res; 9 | for (auto& num: nums2) { 10 | if (m[num] > 0) { 11 | --m[num]; 12 | res.push_back(num); 13 | } 14 | } 15 | return res; 16 | } 17 | }; -------------------------------------------------------------------------------- /intersection_of_two_linked_lists/intersection_of_two_linked_lists.cpp: -------------------------------------------------------------------------------- 1 | struct ListNode { 2 | int val; 3 | ListNode *next; 4 | ListNode(int x) : val(x), next(NULL) {} 5 | }; 6 | 7 | class Solution { 8 | public: 9 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 10 | int count1 = 0; 11 | int count2 = 0; 12 | ListNode* p1 = headA; 13 | ListNode* p2 = headB; 14 | while (p1 != NULL) { 15 | ++count1; 16 | p1 = p1->next; 17 | } 18 | while (p2 != NULL) { 19 | ++count2; 20 | p2 = p2->next; 21 | } 22 | int diff; 23 | if (count1 > count2) { 24 | diff = count1 - count2; 25 | p1 = headA; 26 | p2 = headB; 27 | }else { 28 | diff = count2 - count1; 29 | p1 = headB; 30 | p2 = headA; 31 | } 32 | for (; diff > 0; --diff) p1 = p1->next; 33 | while (p1 != p2){ 34 | p1 = p1->next; 35 | p2 = p2->next; 36 | } 37 | return p1; 38 | } 39 | }; -------------------------------------------------------------------------------- /invert_binary_tree/invert_binary_tree.go: -------------------------------------------------------------------------------- 1 | package invert_binary_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func invertTree(root *TreeNode) *TreeNode { 10 | if root == nil { 11 | return nil 12 | } 13 | root.Left, root.Right = root.Right, root.Left 14 | invertTree(root.Right) 15 | invertTree(root.Left) 16 | return root 17 | } 18 | -------------------------------------------------------------------------------- /is_subsequence/is_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | if (s.size() == 0) return true; 5 | int ps = 0, pt = 0; 6 | for (; pt < t.size() && ps < t.size(); ++pt) { 7 | if (s[ps] == t[pt]) ++ps; 8 | } 9 | return ps == s.size(); 10 | } 11 | }; -------------------------------------------------------------------------------- /isomorphic_strings/isomorphic_strings.go: -------------------------------------------------------------------------------- 1 | package isomorphic_strings 2 | 3 | func isIsomorphic(s string, t string) bool { 4 | if len(s) != len(t) { 5 | return false 6 | } 7 | m := map[byte]byte{} 8 | n := map[byte]byte{} 9 | for i := range s { 10 | if _, ok := m[t[i]]; !ok { 11 | m[t[i]] = s[i] 12 | } 13 | if _, ok := n[s[i]]; !ok { 14 | n[s[i]] = t[i] 15 | } 16 | if s[i] != m[t[i]] { 17 | return false 18 | } 19 | if t[i] != n[s[i]] { 20 | return false 21 | } 22 | } 23 | return true 24 | } 25 | -------------------------------------------------------------------------------- /jump_game/jump_game.go: -------------------------------------------------------------------------------- 1 | package jump_game 2 | 3 | func canJump(nums []int) bool { 4 | if len(nums) == 0 { 5 | return false 6 | } 7 | step := nums[0] 8 | for i := 1; i < len(nums); i++ { 9 | if step > 0 { 10 | step-- 11 | step = max(step, nums[i]) 12 | } else { 13 | return false 14 | } 15 | } 16 | return true 17 | } 18 | 19 | func max(i, j int) int { 20 | if i >= j { 21 | return i 22 | } 23 | return j 24 | } 25 | -------------------------------------------------------------------------------- /kth_largest_element_in_an_array/kth_largest_element_in_an_array.go: -------------------------------------------------------------------------------- 1 | package kth_largest_element_in_an_array 2 | 3 | func findKthLargest(nums []int, k int) int { 4 | return partition(nums, 0, len(nums)-1, k) 5 | } 6 | 7 | func partition(nums []int, i, j, k int) (ret int) { 8 | p := i 9 | for m := i; m < j; m++ { 10 | if nums[m] > nums[j] { 11 | nums[p], nums[m] = nums[m], nums[p] 12 | p++ 13 | } 14 | } 15 | nums[p], nums[j] = nums[j], nums[p] 16 | if p+1 == k { 17 | return nums[p] 18 | } 19 | if k < p+1 { 20 | return partition(nums, i, p-1, k) 21 | } 22 | return partition(nums, p+1, j, k) 23 | } 24 | -------------------------------------------------------------------------------- /kth_smallest_element_in_a_BST/kth_smallest_element_in_a_BST.go: -------------------------------------------------------------------------------- 1 | package kth_smallest_element_in_a_BST 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func kthSmallest(root *TreeNode, k int) int { 10 | if root == nil { 11 | return 0 12 | } 13 | left := helper(root.Left) 14 | if left == k-1 { 15 | return root.Val 16 | } 17 | if left > k-1 { 18 | return kthSmallest(root.Left, k) 19 | } 20 | return kthSmallest(root.Right, k-1-left) 21 | } 22 | 23 | func helper(root *TreeNode) int { 24 | if root == nil { 25 | return 0 26 | } 27 | return 1 + helper(root.Left) + helper(root.Right) 28 | } 29 | -------------------------------------------------------------------------------- /kth_smallest_element_in_a_sorted_matrix/kth_smallest_element_in_a_sorted_matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthSmallest(vector>& matrix, int k) { 4 | int left = matrix[0][0], right = matrix.back().back(); 5 | while (left < right) { 6 | int mid = left + (right - left)/2; 7 | int cnt = 0; 8 | for (auto& vec: matrix) { 9 | cnt += upper_bound(vec.begin(), vec.end(), mid) - vec.begin(); 10 | } 11 | if (cnt < k) left = mid + 1; 12 | else right = mid; 13 | } 14 | return left; 15 | } 16 | }; -------------------------------------------------------------------------------- /largest_divisible_subset/largest_divisible_subset.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector largestDivisibleSubset(vector& nums) { 4 | if (nums.size() == 0) return {}; 5 | sort(nums.begin(), nums.end()); 6 | vector dp(nums.size(), 1), pre(nums.size()); 7 | for (int i = 0; i < pre.size(); ++i) { 8 | pre[i] = i; 9 | } 10 | int max_v = 1, k = 0; 11 | for (int i = 1; i < dp.size(); ++i) { 12 | for (int j = i-1; j >= 0; --j) { 13 | if (nums[i] % nums[j] != 0) continue; 14 | if (dp[i] < dp[j]+1) { 15 | pre[i] = j; 16 | dp[i] = dp[j]+1; 17 | } 18 | if (dp[i] > max_v) { 19 | max_v = dp[i]; 20 | k = i; 21 | } 22 | } 23 | } 24 | vector result; 25 | while (k != pre[k]) { 26 | result.push_back(nums[k]); 27 | k = pre[k]; 28 | } 29 | result.push_back(nums[k]); 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /largest_number/largest_number.go: -------------------------------------------------------------------------------- 1 | package largest_number 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func largestNumber(nums []int) string { 8 | stringList := make([]string, len(nums)) 9 | for i := range nums { 10 | stringList[i] = strconv.Itoa(nums[i]) 11 | } 12 | quickSort(stringList, 0, len(stringList)-1) 13 | var ret string 14 | for i := range stringList { 15 | ret += stringList[i] 16 | } 17 | if len(ret) != 0 && ret[0] == '0' { 18 | return "0" 19 | } 20 | return ret 21 | } 22 | 23 | func quickSort(stringList []string, i, j int) { 24 | if i >= j { 25 | return 26 | } 27 | mid := partition(stringList, i, j) 28 | quickSort(stringList, i, mid-1) 29 | quickSort(stringList, mid+1, j) 30 | return 31 | } 32 | 33 | func partition(stringList []string, i, j int) int { 34 | k := i 35 | for ; i < j; i++ { 36 | if less(stringList[i], stringList[j]) { 37 | continue 38 | } 39 | stringList[k], stringList[i] = stringList[i], stringList[k] 40 | k++ 41 | } 42 | stringList[k], stringList[j] = stringList[j], stringList[k] 43 | return k 44 | } 45 | 46 | func less(s1, s2 string) bool { 47 | return s1+s2 <= s2+s1 48 | } 49 | -------------------------------------------------------------------------------- /largest_rectangle_in_histogram/largest_rectangle_in_histogram.go: -------------------------------------------------------------------------------- 1 | package largest_rectangle_in_histogram 2 | 3 | func largestRectangleArea(heights []int) int { 4 | if len(heights) == 0 { 5 | return 0 6 | } 7 | heights = append(heights, 0) 8 | maxArea := 0 9 | stack := []int{0} 10 | for i := 1; i < len(heights); i++ { 11 | if heights[i] < heights[stack[len(stack)-1]] { 12 | j := len(stack) - 1 13 | for ; j >= 0; j-- { 14 | if heights[stack[j]] < heights[i] { 15 | break 16 | } 17 | var width int 18 | if j == 0 { 19 | width = i 20 | } else { 21 | width = i - stack[j-1] - 1 22 | } 23 | area := width * heights[stack[j]] 24 | if area > maxArea { 25 | maxArea = area 26 | } 27 | } 28 | stack = stack[:j+1] 29 | } 30 | stack = append(stack, i) 31 | } 32 | return maxArea 33 | } 34 | -------------------------------------------------------------------------------- /largest_rectangle_in_histogram/largest_rectangle_in_histogram_test.go: -------------------------------------------------------------------------------- 1 | package largest_rectangle_in_histogram 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLargestRectangleArea(t *testing.T) { 8 | println(largestRectangleArea([]int{4, 2, 0, 3, 2, 5})) 9 | } 10 | -------------------------------------------------------------------------------- /length_of_last_word/length_of_last_word.go: -------------------------------------------------------------------------------- 1 | package length_of_last_word 2 | 3 | func lengthOfLastWord(s string) int { 4 | bytes := []byte(s) 5 | lastIndex := len(bytes) - 1 6 | for i := len(bytes) - 1; i >= 0; i-- { 7 | if bytes[i] != ' ' { 8 | lastIndex = i 9 | break 10 | } 11 | } 12 | bytes = bytes[:lastIndex+1] 13 | for i := len(bytes) - 1; i >= 0; i-- { 14 | if bytes[i] == ' ' { 15 | return len(bytes) - 1 - i 16 | } 17 | } 18 | return len(bytes) 19 | } 20 | -------------------------------------------------------------------------------- /length_of_last_word/length_of_last_word_test.go: -------------------------------------------------------------------------------- 1 | package length_of_last_word 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLengthOfLastWord(t *testing.T) { 8 | println(lengthOfLastWord(" abc")) 9 | } 10 | -------------------------------------------------------------------------------- /letter_combinations_of_a_phone_number/letter_combinations_of_a_phone_number.go: -------------------------------------------------------------------------------- 1 | package letter_combinations_of_a_phone_number 2 | 3 | func letterCombinations(digits string) []string { 4 | m := map[string][]string{ 5 | "2": []string{"a", "b", "c"}, 6 | "3": []string{"d", "e", "f"}, 7 | "4": []string{"g", "h", "i"}, 8 | "5": []string{"j", "k", "l"}, 9 | "6": []string{"m", "n", "o"}, 10 | "7": []string{"p", "q", "r", "s"}, 11 | "8": []string{"t", "u", "v"}, 12 | "9": []string{"w", "x", "y", "z"}, 13 | "0": []string{" "}, 14 | } 15 | slices := [][]string{} 16 | for index := range digits { 17 | digit := string(digits[index]) 18 | if _, ok := m[digit]; ok { 19 | slices = append(slices, m[digit]) 20 | } 21 | } 22 | return generateCombinations(slices) 23 | } 24 | 25 | func generateCombinations(slices [][]string) (ret []string) { 26 | if len(slices) == 0 { 27 | return 28 | } 29 | if len(slices) == 1 { 30 | return slices[0] 31 | } 32 | for _, letter := range slices[0] { 33 | tmpRets := generateCombinations(slices[1:]) 34 | for _, tmp := range tmpRets { 35 | ret = append(ret, letter+tmp) 36 | } 37 | } 38 | return 39 | } 40 | -------------------------------------------------------------------------------- /lexicographical_numbers/lexicographical_numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector lexicalOrder(int n) { 4 | vector result; 5 | for (int i = 1; i <= n && i <= 9; ++i) { 6 | result.push_back(i); 7 | helper(i, n, result); 8 | } 9 | return result; 10 | } 11 | 12 | void helper(int num, int n, vector& result) { 13 | for (int i = 0; i <= 9; ++i) { 14 | int tmp = num*10 + i; 15 | if (tmp > n) break; 16 | result.push_back(tmp); 17 | helper(tmp, n, result); 18 | } 19 | return; 20 | } 21 | }; -------------------------------------------------------------------------------- /linked_list_cycle/linked_list_cycle.cpp: -------------------------------------------------------------------------------- 1 | struct ListNode { 2 | int val; 3 | ListNode *next; 4 | ListNode(int x) : val(x), next(NULL) {} 5 | }; 6 | class Solution { 7 | public: 8 | bool hasCycle(ListNode *head) { 9 | ListNode* fast = head; 10 | ListNode* slow = head; 11 | bool first_step = true; 12 | while (first_step || fast!=slow){ 13 | first_step = false; 14 | for (int i = 0; i < 2 && fast!=NULL; ++i) fast = fast->next; 15 | if (fast==NULL) return false; 16 | slow = slow->next; 17 | } 18 | return true; 19 | } 20 | }; -------------------------------------------------------------------------------- /linked_list_cycle_II/linked_list_cycle_II.cpp: -------------------------------------------------------------------------------- 1 | struct ListNode { 2 | int val; 3 | ListNode *next; 4 | ListNode(int x) : val(x), next(NULL) {} 5 | }; 6 | class Solution { 7 | public: 8 | ListNode* detectCycle(ListNode *head) { 9 | ListNode* fast = head; 10 | ListNode* slow = head; 11 | bool first_step = true; 12 | while (first_step || fast!=slow){ 13 | first_step = false; 14 | for (int i = 0; i < 2 && fast!=NULL; ++i) fast = fast->next; 15 | if (fast==NULL) return NULL; 16 | slow = slow->next; 17 | } 18 | int steps = 1; 19 | while (fast->next != slow){ 20 | fast = fast->next; 21 | ++steps; 22 | } 23 | fast = slow = head; 24 | for (int i = 0; i < steps; ++i) fast = fast->next; 25 | while (fast!=slow){ 26 | fast = fast->next; 27 | slow = slow->next; 28 | } 29 | return slow; 30 | } 31 | }; -------------------------------------------------------------------------------- /longest_absolute_file_path/longest_absolute_file_path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthLongestPath(string input) { 4 | unordered_map depth; 5 | int level = 0, res = 0; 6 | for (int i = 0; i < input.size(); ++i) { 7 | int start = i; 8 | while (i < input.size() && input[i] != '\n' && input[i] != '\t') ++i; 9 | if (i == input.size() || input[i] == '\n') { 10 | string name = input.substr(start, i-start); 11 | if (name.find('.') != string::npos) { 12 | res = max(res, depth[level] + (int)name.size()); 13 | }else { 14 | ++level; 15 | depth[level] = depth[level-1] + (int)name.size() + 1; 16 | } 17 | level = 0; 18 | }else { 19 | ++level; 20 | } 21 | } 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /longest_common_prefix/longest_common_prefix.go: -------------------------------------------------------------------------------- 1 | package longest_common_prefix 2 | 3 | func longestCommonPrefix(strs []string) string { 4 | if len(strs) == 0 { 5 | return "" 6 | } else if len(strs) == 1 { 7 | return strs[0] 8 | } 9 | runesList := make([][]rune, len(strs)) 10 | for index := range strs { 11 | runesList[index] = []rune(strs[index]) 12 | } 13 | var ret []rune 14 | var currentRune rune 15 | length := 0 16 | L: 17 | for { 18 | length++ 19 | for index := range runesList { 20 | if len(runesList[index]) < length { 21 | break L 22 | } 23 | if index == 0 { 24 | currentRune = runesList[0][length-1] 25 | } else { 26 | if runesList[index][length-1] != currentRune { 27 | break L 28 | } 29 | } 30 | } 31 | ret = append(ret, currentRune) 32 | } 33 | return string(ret) 34 | } 35 | -------------------------------------------------------------------------------- /longest_common_prefix/longest_common_prefix_test.go: -------------------------------------------------------------------------------- 1 | package longest_common_prefix 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLongestCommonPrefix(t *testing.T) { 8 | tests := [][]string{ 9 | []string{"", ""}, 10 | []string{"abc", "abd", "abcde"}, 11 | []string{"", "abc"}, 12 | } 13 | results := []string{ 14 | "", 15 | "ab", 16 | "", 17 | } 18 | caseNums := 3 19 | for i := 0; i < caseNums; i++ { 20 | if ret := longestCommonPrefix(tests[i]); ret != results[i] { 21 | t.Fatalf("case %d failed\nactual: %+v, expect: %+v\n", i, ret, results[i]) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /longest_consecutive_sequence/longest_consecutive_sequence.go: -------------------------------------------------------------------------------- 1 | package longest_consecutive_sequence 2 | 3 | func longestConsecutive(nums []int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | visited := map[int]struct{}{} 8 | existed := map[int]struct{}{} 9 | for i := range nums { 10 | existed[nums[i]] = struct{}{} 11 | } 12 | max := 0 13 | for i := range nums { 14 | count := 0 15 | left := nums[i] 16 | for { 17 | if _, ok := visited[left]; ok { 18 | break 19 | } else if _, ok := existed[left]; ok { 20 | visited[left] = struct{}{} 21 | count++ 22 | left-- 23 | } else { 24 | break 25 | } 26 | } 27 | right := nums[i] + 1 28 | for { 29 | if _, ok := visited[right]; ok { 30 | break 31 | } else if _, ok := existed[right]; ok { 32 | visited[right] = struct{}{} 33 | count++ 34 | right++ 35 | } else { 36 | break 37 | } 38 | } 39 | if count > max { 40 | max = count 41 | } 42 | } 43 | return max 44 | } 45 | -------------------------------------------------------------------------------- /longest_palindromic_substring/longest_palindromic_substring.go: -------------------------------------------------------------------------------- 1 | package longest_palindromic_substring 2 | 3 | func longestPalindrome(s string) string { 4 | runes := []rune(s) 5 | length := len(runes) 6 | if length <= 1 { 7 | return s 8 | } 9 | maxRune := runes[0:1] 10 | for i := 0; i < length-1; i++ { 11 | tmpRune := findPalindrome(runes, i, i) 12 | if len(tmpRune) > len(maxRune) { 13 | maxRune = tmpRune 14 | } 15 | if runes[i] == runes[i+1] { 16 | tmpRune = findPalindrome(runes, i, i+1) 17 | if len(tmpRune) > len(maxRune) { 18 | maxRune = tmpRune 19 | } 20 | } 21 | } 22 | return string(maxRune) 23 | } 24 | 25 | func findPalindrome(subRune []rune, i, j int) []rune { 26 | m, n := i-1, j+1 27 | for ; m >= 0 && n <= len(subRune)-1 && subRune[m] == subRune[n]; m, n = m-1, n+1 { 28 | } 29 | return subRune[m+1 : n] 30 | } 31 | -------------------------------------------------------------------------------- /longest_palindromic_substring/longest_palindromic_substring_test.go: -------------------------------------------------------------------------------- 1 | package longest_palindromic_substring 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLongestPalindrome(t *testing.T) { 8 | tests := []string{ 9 | "a", 10 | "aaaaa", 11 | "abababab", 12 | "abcfcdfgfdc", 13 | } 14 | results := []string{ 15 | "a", 16 | "aaaaa", 17 | "abababa", 18 | "cdfgfdc", 19 | } 20 | caseNums := 4 21 | for i := 0; i < caseNums; i++ { 22 | if ret := longestPalindrome(tests[i]); ret != results[i] { 23 | t.Fatalf("case %d failed\nactual: %s, expect: %s\n", i, ret, results[i]) 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /longest_substring_with_at_least_k_repeating_characters/longest_substring_with_at_least_k_repeating_characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubstring(string s, int k) { 4 | int ret = 0; 5 | int i = 0; 6 | while (i+k < s.size()) { 7 | int mask = 0, i_max = i; 8 | vector cnt(26, 0); 9 | for (int j = i; j < s.size(); ++j) { 10 | int idx = s[j] - 'a'; 11 | ++cnt[idx]; 12 | if (cnt[idx] < k) mask |= (1 << idx); 13 | else mask &= ~(1 << idx); 14 | if (mask == 0) { 15 | ret = max(ret, j-i+1); 16 | i_max = j; 17 | } 18 | } 19 | i = i_max + 1; 20 | } 21 | return ret; 22 | } 23 | }; -------------------------------------------------------------------------------- /longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go: -------------------------------------------------------------------------------- 1 | package longest_substring_without_repeating_characters 2 | 3 | func lengthOfLongestSubstring(s string) int { 4 | runes := []rune(s) 5 | runeMap := make(map[rune]int) 6 | longest := 0 7 | preLength := 0 8 | for i, rn := range runes { 9 | var length int 10 | if val, ok := runeMap[rn]; !ok || val < i-preLength { 11 | length = preLength + 1 12 | } else { 13 | length = i - val 14 | } 15 | if length > longest { 16 | longest = length 17 | } 18 | preLength = length 19 | runeMap[rn] = i 20 | } 21 | return longest 22 | } 23 | -------------------------------------------------------------------------------- /longest_substring_without_repeating_characters/longest_substring_without_repeating_characters_test.go: -------------------------------------------------------------------------------- 1 | package longest_substring_without_repeating_characters 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLengthOfLongestSubstring(t *testing.T) { 8 | tests := []string{ 9 | "abcabcbb", 10 | "aaaaaaaa", 11 | "abcde", 12 | "", 13 | "pwwkew", 14 | } 15 | results := []int{ 16 | 3, 17 | 1, 18 | 5, 19 | 0, 20 | 3, 21 | } 22 | caseNum := 5 23 | for i := 0; i < caseNum; i++ { 24 | if ret := lengthOfLongestSubstring(tests[i]); ret != results[i] { 25 | t.Fatalf("case %d failed\nactual: %d, expect: %d\n", i, ret, results[i]) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /longest_valid_parentheses/longest_valid_parentheses.go: -------------------------------------------------------------------------------- 1 | package longest_valid_parentheses 2 | 3 | func longestValidParentheses(s string) int { 4 | bytes := []byte(s) 5 | if len(bytes) < 2 { 6 | return 0 7 | } 8 | lengthList := make([]int, len(bytes)) 9 | var max int 10 | for i := 1; i < len(bytes); i++ { 11 | if bytes[i] == ')' { 12 | j := i - lengthList[i-1] - 1 13 | if j >= 0 && bytes[j] == '(' { 14 | lengthList[i] = lengthList[i-1] + 2 15 | if j-1 >= 0 { 16 | lengthList[i] += lengthList[j-1] 17 | } 18 | } 19 | } 20 | if lengthList[i] > max { 21 | max = lengthList[i] 22 | } 23 | } 24 | return max 25 | } 26 | -------------------------------------------------------------------------------- /longest_valid_parentheses/longest_valid_parentheses_test.go: -------------------------------------------------------------------------------- 1 | package longest_valid_parentheses 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLongestValidParentheses(t *testing.T) { 8 | } 9 | -------------------------------------------------------------------------------- /lowest_common_ancestor_of_a_binary_search_tree/lowest_common_ancestor_of_a_binary_search_tree.cpp: -------------------------------------------------------------------------------- 1 | struct TreeNode { 2 | int val; 3 | TreeNode *left; 4 | TreeNode *right; 5 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 6 | }; 7 | 8 | class Solution { 9 | public: 10 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 11 | if (root == NULL || p->val >= root->val && q->val <= root->val || p->val <= root->val && q->val >= root->val) 12 | return root; 13 | if (p->val <= root->val) 14 | return lowestCommonAncestor(root->left, p, q); 15 | return lowestCommonAncestor(root->right, p, q); 16 | } 17 | }; -------------------------------------------------------------------------------- /lowest_common_ancestor_of_a_binary_tree/lowest_common_ancestor_of_a_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 14 | vector path_p = {root}; 15 | this->searchNode(root, p, path_p); 16 | vector path_q = {root}; 17 | this->searchNode(root, q, path_q); 18 | int idx = path_p.size()= 0; --idx) { 20 | if (path_p[idx] == path_q[idx]) return path_p[idx]; 21 | } 22 | return NULL; 23 | } 24 | 25 | bool searchNode(TreeNode* root, TreeNode* target, vector& path) { 26 | if (root == target) { 27 | return true; 28 | } 29 | if (root->left == NULL && root->right == NULL) { 30 | return false; 31 | } 32 | if (root->left != NULL){ 33 | path.push_back(root->left); 34 | if (searchNode(root->left, target, path)){ 35 | return true; 36 | } 37 | path.pop_back(); 38 | } 39 | if (root->right != NULL){ 40 | path.push_back(root->right); 41 | if (searchNode(root->right, target, path)){ 42 | return true; 43 | } 44 | path.pop_back(); 45 | } 46 | return false; 47 | } 48 | }; -------------------------------------------------------------------------------- /majority_element/majority_element.go: -------------------------------------------------------------------------------- 1 | package majority_element 2 | 3 | func majorityElement(nums []int) int { 4 | var elem, count int 5 | for i := range nums { 6 | if count == 0 { 7 | count++ 8 | elem = nums[i] 9 | } else { 10 | if nums[i] != elem { 11 | count-- 12 | } else { 13 | count++ 14 | } 15 | } 16 | } 17 | return elem 18 | } 19 | -------------------------------------------------------------------------------- /majority_element_II/majority_element_II.go: -------------------------------------------------------------------------------- 1 | package majority_element_II 2 | 3 | func majorityElement(nums []int) []int { 4 | var m, n, cm, cn int 5 | for i := range nums { 6 | if nums[i] == m { 7 | cm++ 8 | } else if nums[i] == n { 9 | cn++ 10 | } else if cm == 0 { 11 | m = nums[i] 12 | cm++ 13 | } else if cn == 0 { 14 | n = nums[i] 15 | cn++ 16 | } else { 17 | cm-- 18 | cn-- 19 | } 20 | } 21 | cm, cn = 0, 0 22 | for i := range nums { 23 | if nums[i] == m { 24 | cm++ 25 | } else if nums[i] == n { 26 | cn++ 27 | } 28 | } 29 | var ret []int 30 | if cm > len(nums)/3 { 31 | ret = append(ret, m) 32 | } 33 | if cn > len(nums)/3 { 34 | ret = append(ret, n) 35 | } 36 | return ret 37 | } 38 | -------------------------------------------------------------------------------- /max_points_on_a_line/max_points_on_a_line.go: -------------------------------------------------------------------------------- 1 | package max_points_on_a_line 2 | 3 | type Point struct { 4 | X int 5 | Y int 6 | } 7 | 8 | func maxPoints(points []Point) int { 9 | if len(points) < 3 { 10 | return len(points) 11 | } 12 | var max int 13 | for i := range points { 14 | verticalNum := 0 15 | equalNum := 0 16 | m := map[float64]int{} 17 | for j := range points { 18 | if i == j { 19 | continue 20 | } 21 | if points[i].X == points[j].X && points[i].Y == points[j].Y { 22 | equalNum++ 23 | } else if points[i].X == points[j].X { 24 | verticalNum++ 25 | } else { 26 | ratio := float64(points[i].Y-points[j].Y) / float64(points[i].X-points[j].X) 27 | m[ratio]++ 28 | } 29 | } 30 | if verticalNum+equalNum > max { 31 | max = verticalNum + equalNum 32 | } 33 | for k := range m { 34 | if m[k]+equalNum > max { 35 | max = m[k] + equalNum 36 | } 37 | } 38 | } 39 | return max + 1 40 | } 41 | -------------------------------------------------------------------------------- /maximal_rectangle/maximal_rectangle.go: -------------------------------------------------------------------------------- 1 | package maximal_rectangle 2 | 3 | func maximalRectangle(matrix [][]byte) int { 4 | if len(matrix) == 0 || len(matrix[0]) == 0 { 5 | return 0 6 | } 7 | max := 0 8 | for i := 0; i < len(matrix); i++ { 9 | heights := make([]int, len(matrix[0])) 10 | for j := 0; j < len(matrix[0]); j++ { 11 | if matrix[i][j] == '0' { 12 | heights[j] = 0 13 | } else { 14 | for k := i; k < len(matrix); k++ { 15 | if matrix[k][j] == '0' { 16 | break 17 | } 18 | heights[j]++ 19 | } 20 | } 21 | } 22 | area := maxArea(heights) 23 | if area > max { 24 | max = area 25 | } 26 | } 27 | return max 28 | } 29 | 30 | func maxArea(heights []int) int { 31 | if len(heights) == 0 { 32 | return 0 33 | } 34 | max := 0 35 | stack := []int{0} 36 | heights = append(heights, 0) 37 | for i := 1; i < len(heights); i++ { 38 | if heights[i] < heights[stack[len(stack)-1]] { 39 | j := len(stack) - 1 40 | for ; j >= 0; j-- { 41 | if heights[stack[j]] < heights[i] { 42 | break 43 | } 44 | width := i 45 | if j != 0 { 46 | width = i - stack[j-1] - 1 47 | } 48 | area := width * heights[stack[j]] 49 | if area > max { 50 | max = area 51 | } 52 | } 53 | stack = stack[:j+1] 54 | } 55 | stack = append(stack, i) 56 | } 57 | return max 58 | } 59 | -------------------------------------------------------------------------------- /maximal_square/maximal_square.go: -------------------------------------------------------------------------------- 1 | package maximal_square 2 | 3 | func maximalSquare(matrix [][]byte) int { 4 | if len(matrix) == 0 || len(matrix[0]) == 0 { 5 | return 0 6 | } 7 | m := map[byte]int{ 8 | '0': 0, 9 | '1': 1, 10 | } 11 | p := make([][]int, len(matrix)) 12 | for i := range p { 13 | p[i] = make([]int, len(matrix[i])) 14 | } 15 | max := 0 16 | for i := range matrix { 17 | for j := range matrix[i] { 18 | if i == 0 || j == 0 { 19 | p[i][j] = m[matrix[i][j]] 20 | } else if matrix[i][j] == '1' { 21 | p[i][j] = min(min(p[i-1][j], p[i][j-1]), p[i-1][j-1]) + 1 22 | } 23 | if p[i][j] > max { 24 | max = p[i][j] 25 | } 26 | } 27 | } 28 | return max * max 29 | } 30 | 31 | func min(i, j int) int { 32 | if i < j { 33 | return i 34 | } 35 | return j 36 | } 37 | -------------------------------------------------------------------------------- /maximum_depth_of_binary_tree/maximum_depth_of_binary_tree.go: -------------------------------------------------------------------------------- 1 | package maximum_depth_of_binary_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func maxDepth(root *TreeNode) int { 10 | if root == nil { 11 | return 0 12 | } 13 | if root.Left == nil && root.Right == nil { 14 | return 1 15 | } 16 | left := maxDepth(root.Left) 17 | right := maxDepth(root.Right) 18 | if left > right { 19 | return left + 1 20 | } 21 | return right + 1 22 | } 23 | -------------------------------------------------------------------------------- /maximum_gap/maximum_gap.go: -------------------------------------------------------------------------------- 1 | package maximum_gap 2 | 3 | func maximumGap(nums []int) int { 4 | if len(nums) < 2 { 5 | return 0 6 | } 7 | max, min := nums[0], nums[0] 8 | for i := 1; i < len(nums); i++ { 9 | if nums[i] > max { 10 | max = nums[i] 11 | } 12 | if nums[i] < min { 13 | min = nums[i] 14 | } 15 | } 16 | bucketSize := (max-min)/len(nums) + 1 17 | bucket := make([][]int, len(nums)) 18 | for i := range nums { 19 | idx := (nums[i] - min) / bucketSize 20 | if len(bucket[idx]) == 0 { 21 | bucket[idx] = []int{nums[i], nums[i]} 22 | } else { 23 | if nums[i] < bucket[idx][0] { 24 | bucket[idx][0] = nums[i] 25 | } 26 | if nums[i] > bucket[idx][1] { 27 | bucket[idx][1] = nums[i] 28 | } 29 | } 30 | } 31 | ret := bucket[0][1] - bucket[0][0] 32 | pre := 0 33 | for i := 1; i < len(nums); i++ { 34 | if len(bucket[i]) == 0 { 35 | continue 36 | } 37 | if bucket[i][0]-bucket[pre][1] > ret { 38 | ret = bucket[i][0] - bucket[pre][1] 39 | } 40 | pre = i 41 | } 42 | return ret 43 | } 44 | -------------------------------------------------------------------------------- /maximum_product_of_word_lengths/maximum_product_of_word_lengths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& words) { 4 | vector helper(words.size(), 0); 5 | for (int i = 0; i < words.size(); ++i) { 6 | for (auto& ch: words[i]) { 7 | helper[i] |= 1 << (ch-'a'); 8 | } 9 | } 10 | int ret = 0; 11 | for (int i = 0; i < helper.size(); ++i) { 12 | for (int j = i+1; j < helper.size(); ++j) { 13 | if (helper[i] & helper[j]) continue; 14 | if (words[i].size() * words[j].size() > ret) ret = words[i].size() * words[j].size(); 15 | } 16 | } 17 | return ret; 18 | } 19 | }; -------------------------------------------------------------------------------- /maximum_product_subarray/maximum_product_subarray.go: -------------------------------------------------------------------------------- 1 | package maximum_product_subarray 2 | 3 | func maxProduct(nums []int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | if len(nums) == 1 { 8 | return nums[0] 9 | } 10 | ret, preMax, preMin := nums[0], nums[0], nums[0] 11 | var temp int 12 | for i := 1; i < len(nums); i++ { 13 | temp = preMax 14 | preMax = max(max(nums[i], nums[i]*preMax), nums[i]*preMin) 15 | preMin = min(min(nums[i], nums[i]*preMin), nums[i]*temp) 16 | ret = max(ret, preMax) 17 | } 18 | return ret 19 | } 20 | 21 | func max(i, j int) int { 22 | if i > j { 23 | return i 24 | } 25 | return j 26 | } 27 | 28 | func min(i, j int) int { 29 | if i < j { 30 | return i 31 | } 32 | return j 33 | } 34 | -------------------------------------------------------------------------------- /maximum_subarray/maximum_subarray.go: -------------------------------------------------------------------------------- 1 | package maximum_subarray 2 | 3 | func maxSubArray(nums []int) int { 4 | if len(nums) == 1 { 5 | return nums[0] 6 | } 7 | preSum, max := nums[0], nums[0] 8 | for i := 1; i < len(nums); i++ { 9 | currentSum := 0 10 | if preSum < 0 { 11 | currentSum = nums[i] 12 | } else { 13 | currentSum = nums[i] + preSum 14 | } 15 | if currentSum > max { 16 | max = currentSum 17 | } 18 | preSum = currentSum 19 | } 20 | return max 21 | } 22 | -------------------------------------------------------------------------------- /median_of_two_sorted_arrays/median_of_two_sorted_arrays.go: -------------------------------------------------------------------------------- 1 | package median_of_two_sorted_arrays 2 | 3 | func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { 4 | l1, l2 := len(nums1), len(nums2) 5 | total := l1 + l2 6 | if total%2 == 1 { 7 | return float64(findKthNum(nums1, nums2, total/2+1)) 8 | } else { 9 | return 0.5 * float64(findKthNum(nums1, nums2, total/2)+findKthNum(nums1, nums2, total/2+1)) 10 | } 11 | } 12 | 13 | func findKthNum(nums1 []int, nums2 []int, k int) (val int) { 14 | l1, l2 := len(nums1), len(nums2) 15 | if l1 > l2 { 16 | return findKthNum(nums2, nums1, k) 17 | } 18 | if l1 == 0 { 19 | return nums2[k-1] 20 | } 21 | if k == 1 { 22 | if nums1[0] < nums2[0] { 23 | return nums1[0] 24 | } else { 25 | return nums2[0] 26 | } 27 | } 28 | var pa, pb int 29 | if l1 < k/2 { 30 | pa = l1 31 | } else { 32 | pa = k / 2 33 | } 34 | pb = k - pa 35 | if nums1[pa-1] < nums2[pb-1] { 36 | return findKthNum(nums1[pa:], nums2, k-pa) 37 | } else if nums1[pa-1] > nums2[pb-1] { 38 | return findKthNum(nums1, nums2[pb:], k-pb) 39 | } else { 40 | return nums1[pa-1] 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /median_of_two_sorted_arrays/median_of_two_sorted_arrays_test.go: -------------------------------------------------------------------------------- 1 | package median_of_two_sorted_arrays 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestFindMedianSortedArrays(t *testing.T) { 8 | nums1 := [][]int{ 9 | []int{1, 3}, 10 | []int{1, 2, 3}, 11 | []int{4}, 12 | } 13 | nums2 := [][]int{ 14 | []int{2}, 15 | []int{4, 5, 6}, 16 | []int{1, 2, 3, 7, 8, 9, 10, 11}, 17 | } 18 | results := []float64{ 19 | 2, 20 | 3.5, 21 | 7, 22 | } 23 | caseNums := 3 24 | for i := 0; i < caseNums; i++ { 25 | if ret := findMedianSortedArrays(nums1[i], nums2[i]); ret != results[i] { 26 | t.Fatalf("case %d failed.\nexpect: %f, actual: %f\n", i, results[i], ret) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /merge_k_sorted_lists/merge_k_sorted_lists.go: -------------------------------------------------------------------------------- 1 | package merge_k_sorted_lists 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func mergeKLists(lists []*ListNode) *ListNode { 9 | if len(lists) == 0 { 10 | return nil 11 | } else if len(lists) == 1 { 12 | return lists[0] 13 | } 14 | return mergeTwoLists(mergeKLists(lists[:len(lists)/2]), mergeKLists(lists[len(lists)/2:])) 15 | 16 | } 17 | 18 | func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { 19 | if l1 == nil { 20 | return l2 21 | } else if l2 == nil { 22 | return l1 23 | } 24 | var head *ListNode 25 | if l1.Val < l2.Val { 26 | head = l1 27 | head.Next = mergeTwoLists(l1.Next, l2) 28 | } else { 29 | head = l2 30 | head.Next = mergeTwoLists(l2.Next, l1) 31 | } 32 | return head 33 | } 34 | -------------------------------------------------------------------------------- /merge_k_sorted_lists/merge_k_sorted_lists_test.go: -------------------------------------------------------------------------------- 1 | package merge_k_sorted_lists 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMergeKLists(t *testing.T) {} 8 | -------------------------------------------------------------------------------- /merge_sorted_array/merge_sorted_array.go: -------------------------------------------------------------------------------- 1 | package merge_sorted_array 2 | 3 | func merge(nums1 []int, m int, nums2 []int, n int) { 4 | for i := m + n - 1; m > 0 && n > 0 && i >= 0; i-- { 5 | if nums1[m-1] > nums2[n-1] { 6 | nums1[i] = nums1[m-1] 7 | m-- 8 | } else { 9 | nums1[i] = nums2[n-1] 10 | n-- 11 | } 12 | } 13 | if m == 0 { 14 | for ; n > 0; n-- { 15 | nums1[n-1] = nums2[n-1] 16 | } 17 | } 18 | return 19 | } 20 | -------------------------------------------------------------------------------- /merge_two_sorted_lists/merge_two_sorted_lists.go: -------------------------------------------------------------------------------- 1 | package merge_two_sorted_lists 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { 9 | if l1 == nil { 10 | return l2 11 | } else if l2 == nil { 12 | return l1 13 | } 14 | var head *ListNode 15 | if l1.Val < l2.Val { 16 | head = l1 17 | head.Next = mergeTwoLists(l1.Next, l2) 18 | } else { 19 | head = l2 20 | head.Next = mergeTwoLists(l2.Next, l1) 21 | } 22 | return head 23 | } 24 | -------------------------------------------------------------------------------- /min_stack/min_stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class MinStack { 5 | public: 6 | 7 | MinStack() { 8 | 9 | } 10 | 11 | void push(int x) { 12 | normal_stack.push(x); 13 | if (min_stack.empty() || x <= min_stack.top()) min_stack.push(x); 14 | return; 15 | } 16 | 17 | void pop() { 18 | int t = normal_stack.top(); 19 | normal_stack.pop(); 20 | if (t == min_stack.top()) min_stack.pop(); 21 | return; 22 | } 23 | 24 | int top() { 25 | return normal_stack.top(); 26 | } 27 | 28 | int getMin() { 29 | return min_stack.top(); 30 | } 31 | private: 32 | stack normal_stack; 33 | stack min_stack; 34 | }; -------------------------------------------------------------------------------- /minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go: -------------------------------------------------------------------------------- 1 | package minimum_depth_of_binary_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func minDepth(root *TreeNode) int { 10 | if root == nil { 11 | return 0 12 | } 13 | if root.Left == nil && root.Right == nil { 14 | return 1 15 | } 16 | left, right := -1, -1 17 | if root.Left != nil { 18 | left = minDepth(root.Left) 19 | } 20 | if root.Right != nil { 21 | right = minDepth(root.Right) 22 | } 23 | depth := 1 24 | if left == -1 { 25 | depth += right 26 | } else if right == -1 { 27 | depth += left 28 | } else if left < right { 29 | depth += left 30 | } else { 31 | depth += right 32 | } 33 | return depth 34 | } 35 | -------------------------------------------------------------------------------- /minimum_height_trees/minimum_height_trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findMinHeightTrees(int n, vector>& edges) { 4 | if (n <= 1) return {0}; 5 | vector> graph(n); 6 | for (auto& edge: edges) { 7 | graph[edge.first].insert(edge.second); 8 | graph[edge.second].insert(edge.first); 9 | } 10 | vector current; 11 | for (int i = 0; i < graph.size(); ++i) { 12 | if (graph[i].size() == 1) current.push_back(i); 13 | } 14 | while (true) { 15 | vector next; 16 | for (auto& node: current) { 17 | for (auto& neighbor: graph[node]) { 18 | graph[neighbor].erase(node); 19 | if (graph[neighbor].size() == 1) next.push_back(neighbor); 20 | } 21 | } 22 | if (next.size() == 0) break; 23 | current.swap(next); 24 | } 25 | return current; 26 | } 27 | }; -------------------------------------------------------------------------------- /minimum_path_sum/minimum_path_sum.go: -------------------------------------------------------------------------------- 1 | package minimum_path_sum 2 | 3 | func minPathSum(grid [][]int) int { 4 | if len(grid) == 0 || len(grid[0]) == 0 { 5 | return 0 6 | } 7 | m, n := len(grid), len(grid[0]) 8 | matrix := make([][]int, m) 9 | for i := range matrix { 10 | matrix[i] = make([]int, n) 11 | } 12 | for i := 0; i < m; i++ { 13 | for j := 0; j < n; j++ { 14 | if i == 0 && j == 0 { 15 | matrix[i][j] = grid[0][0] 16 | } else if i == 0 { 17 | matrix[i][j] = grid[i][j] + matrix[i][j-1] 18 | } else if j == 0 { 19 | matrix[i][j] = grid[i][j] + matrix[i-1][j] 20 | } else { 21 | matrix[i][j] = matrix[i][j-1] 22 | if matrix[i][j] > matrix[i-1][j] { 23 | matrix[i][j] = matrix[i-1][j] 24 | } 25 | matrix[i][j] += grid[i][j] 26 | } 27 | } 28 | } 29 | return matrix[m-1][n-1] 30 | } 31 | -------------------------------------------------------------------------------- /minimum_size_subarray_sum/minimum_size_subarray_sum.go: -------------------------------------------------------------------------------- 1 | package minimum_size_subarray_sum 2 | 3 | func minSubArrayLen(s int, nums []int) int { 4 | var left, right, res int 5 | min := len(nums) + 1 6 | for right < len(nums) { 7 | for ; res < s && right < len(nums); right++ { 8 | res += nums[right] 9 | } 10 | for ; res >= s; left++ { 11 | res -= nums[left] 12 | if right-left < min { 13 | min = right - left 14 | } 15 | } 16 | } 17 | if min == len(nums)+1 { 18 | return 0 19 | } 20 | return min 21 | } 22 | -------------------------------------------------------------------------------- /minimum_window_substring/minimum_window_substring.go: -------------------------------------------------------------------------------- 1 | package minimum_window_substring 2 | 3 | func minWindow(s string, t string) string { 4 | sBytes, tBytes := []byte(s), []byte(t) 5 | if len(sBytes) == 0 || len(tBytes) == 0 || len(sBytes) < len(tBytes) { 6 | return "" 7 | } 8 | sMap := map[byte]int{} 9 | tMap := map[byte]int{} 10 | for _, b := range tBytes { 11 | tMap[b]++ 12 | } 13 | begin, tmpBegin := 0, 0 14 | minSize := -1 15 | letters := 0 16 | for i := 0; i < len(sBytes); i++ { 17 | b := sBytes[i] 18 | sMap[b]++ 19 | if _, ok := tMap[b]; ok && sMap[b] < tMap[b] { 20 | letters++ 21 | } 22 | if letters == len(tBytes) { 23 | for tmpBegin < i { 24 | if _, ok := tMap[sBytes[tmpBegin]]; ok { 25 | if sMap[sBytes[tmpBegin]] == tMap[sBytes[tmpBegin]] { 26 | break 27 | } 28 | sMap[sBytes[tmpBegin]]-- 29 | } 30 | tmpBegin++ 31 | } 32 | if minSize == -1 || i-tmpBegin < minSize { 33 | minSize = i - tmpBegin 34 | begin = tmpBegin 35 | } 36 | } 37 | letters-- 38 | tmpBegin++ 39 | sMap[sBytes[tmpBegin]]-- 40 | } 41 | if minSize == -1 { 42 | return "" 43 | } 44 | return s[begin : begin+minSize+1] 45 | } 46 | -------------------------------------------------------------------------------- /missing_number/missing_number.go: -------------------------------------------------------------------------------- 1 | package missing_number 2 | 3 | func missingNumber(nums []int) int { 4 | ret := 0 5 | for i := range nums { 6 | ret ^= nums[i] ^ (i + 1) 7 | } 8 | return ret 9 | } 10 | 11 | func missingNumberI(nums []int) int { 12 | ret := 0 13 | for i := range nums { 14 | ret += i + 1 - nums[i] 15 | } 16 | return ret 17 | } 18 | -------------------------------------------------------------------------------- /move_zeroes/move_zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int j = 0; 5 | int tmp; 6 | for (int i = 0; i < nums.size(); ++i){ 7 | if (nums[i] != 0){ 8 | tmp = nums[i]; 9 | nums[i] = nums[j]; 10 | nums[j] = tmp; 11 | j++; 12 | } 13 | } 14 | return; 15 | } 16 | }; -------------------------------------------------------------------------------- /multiply_strings/multiply_strings_test.go: -------------------------------------------------------------------------------- 1 | package multiply_strings 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMultiply(t *testing.T) { 8 | println(multiply("5555", "6666")) 9 | } 10 | -------------------------------------------------------------------------------- /n_queens_II/n_queens_II.go: -------------------------------------------------------------------------------- 1 | package n_queens_II 2 | 3 | func totalNQueens(n int) int { 4 | ret, depth, maxDepth := 0, -1, n-1 5 | nextIndex := make([]int, n) 6 | stack := []int{} 7 | for { 8 | L: 9 | for depth < maxDepth { 10 | for { 11 | childDepth := depth + 1 12 | if nextIndex[childDepth] == n { 13 | nextIndex[childDepth] = 0 14 | break L 15 | } 16 | index := nextIndex[childDepth] 17 | nextIndex[childDepth]++ 18 | if isValid(stack, childDepth, index) { 19 | stack = append(stack, index) 20 | break 21 | } 22 | } 23 | depth++ 24 | } 25 | if depth == maxDepth { 26 | ret++ 27 | } 28 | if depth == -1 { 29 | break 30 | } 31 | depth-- 32 | stack = stack[:len(stack)-1] 33 | } 34 | return ret 35 | } 36 | 37 | func isValid(stack []int, index, val int) bool { 38 | for i, v := range stack { 39 | if v == val || i-index == v-val || i-index == val-v { 40 | return false 41 | } 42 | } 43 | return true 44 | } 45 | -------------------------------------------------------------------------------- /next_permutation/next_permutation.go: -------------------------------------------------------------------------------- 1 | package next_permutation 2 | 3 | func nextPermutation(nums []int) { 4 | if len(nums) < 2 { 5 | return 6 | } 7 | swapIndex := -1 8 | for i := len(nums) - 1; i > 0; i-- { 9 | if nums[i-1] < nums[i] { 10 | swapIndex = i - 1 11 | break 12 | } 13 | } 14 | if swapIndex == -1 { 15 | reverseNums(nums) 16 | return 17 | } 18 | for i := len(nums) - 1; i > swapIndex; i-- { 19 | if nums[i] > nums[swapIndex] { 20 | nums[i], nums[swapIndex] = nums[swapIndex], nums[i] 21 | reverseNums(nums[swapIndex+1:]) 22 | break 23 | } 24 | } 25 | return 26 | } 27 | 28 | func reverseNums(nums []int) { 29 | for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 { 30 | nums[i], nums[j] = nums[j], nums[i] 31 | } 32 | return 33 | } 34 | -------------------------------------------------------------------------------- /nim_game/nim_game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canWinNim(int n) { 4 | return !(n%4 == 0); 5 | } 6 | }; -------------------------------------------------------------------------------- /nth_digit/nth_digit.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNthDigit(int n) { 4 | long len = 1; 5 | long count = 9; 6 | long start = 1; 7 | while (n > len*count) { 8 | n -= len*count; 9 | start += count; 10 | ++len; 11 | count *= 10; 12 | } 13 | return to_string(start + (n-1)/len)[(n-1)%len] - '0'; 14 | } 15 | }; -------------------------------------------------------------------------------- /number_of_1bits/number_of_1bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int x = 1; 5 | int count = 0; 6 | for (int i = 0; i < 32; ++i){ 7 | if (n & x) count++; 8 | x <<= 1; 9 | } 10 | return count; 11 | } 12 | }; -------------------------------------------------------------------------------- /palindrome_lined_list/palindrome_lined_list.go: -------------------------------------------------------------------------------- 1 | package palindrome_lined_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func isPalindrome(head *ListNode) bool { 9 | slow, fast := head, head 10 | for fast != nil && fast.Next != nil { 11 | slow = slow.Next 12 | fast = fast.Next.Next 13 | } 14 | head2 := reverse(slow) 15 | for ; head != nil && head2 != nil; head, head2 = head.Next, head2.Next { 16 | if head.Val != head2.Val { 17 | return false 18 | } 19 | } 20 | return true 21 | } 22 | 23 | func reverse(head *ListNode) (newHead *ListNode) { 24 | var pre *ListNode 25 | cur := head 26 | for cur != nil { 27 | tmp := cur.Next 28 | cur.Next = pre 29 | pre = cur 30 | if tmp == nil { 31 | break 32 | } 33 | cur = tmp 34 | } 35 | return cur 36 | } 37 | -------------------------------------------------------------------------------- /palindrome_number/palindrome_number.go: -------------------------------------------------------------------------------- 1 | package palindrome_number 2 | 3 | func isPalindrome(x int) bool { 4 | if x < 0 { 5 | return false 6 | } 7 | bits := 1 8 | tmp := x 9 | for { 10 | if tmp < 10 { 11 | break 12 | } 13 | tmp = tmp / 10 14 | bits++ 15 | } 16 | i, j := 1, bits 17 | for i < j { 18 | left := (x / divisor(i)) % 10 19 | right := (x / divisor(j)) % 10 20 | if left != right { 21 | return false 22 | } 23 | i, j = i+1, j-1 24 | } 25 | return true 26 | } 27 | 28 | func divisor(bits int) int { 29 | ret := 1 30 | for i := 0; i < bits-1; i++ { 31 | ret = ret * 10 32 | } 33 | return ret 34 | } 35 | -------------------------------------------------------------------------------- /palindrome_number/palindrome_number_test.go: -------------------------------------------------------------------------------- 1 | package palindrome_number 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsPalindrome(t *testing.T) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /palindrome_pairs/palindrome_pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> palindromePairs(vector& words) { 4 | vector> results; 5 | unordered_map mapping; 6 | set index_set; 7 | for (int i = 0; i < words.size(); ++i) { 8 | mapping[words[i]] = i; 9 | index_set.insert(words[i].size()); 10 | } 11 | for (int i = 0; i < words.size(); ++i) { 12 | string word = words[i]; 13 | int len = word.size(); 14 | reverse(word.begin(), word.end()); 15 | if (mapping.count(word) != 0 && mapping[word] != i) { 16 | results.push_back(vector{i, mapping[word]}); 17 | } 18 | for (auto j = index_set.begin(); j != index_set.find(word.size()); ++j) { 19 | int d = *j; 20 | if (is_palindrome(word, 0, len - d - 1) && mapping.count(word.substr(len - d))) { 21 | results.push_back({i, mapping[word.substr(len - d)]}); 22 | } 23 | if (is_palindrome(word, d, len - 1) && mapping.count(word.substr(0, d))) { 24 | results.push_back({mapping[word.substr(0, d)], i}); 25 | } 26 | } 27 | } 28 | return results; 29 | } 30 | 31 | bool is_palindrome(string& s, int i, int j) { 32 | while (i < j) { 33 | if (s[i++] != s[j--]) return false; 34 | } 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /palindrome_partitioning/palindrome_partitioning.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | enum 7 | { 8 | INIT = 0, 9 | YES = 1, 10 | NO = 2, 11 | }; 12 | vector > matrix; 13 | public: 14 | vector> partition(string s) { 15 | matrix = vector >(s.size(), vector(s.size(), INIT)); 16 | vector> res; 17 | vector path; 18 | DFS(s, 0, res, path); 19 | return res; 20 | } 21 | 22 | void DFS(string s, int start, vector>& res, vector& path){ 23 | if (start==s.size()){ 24 | res.push_back(path); 25 | return; 26 | } 27 | for (int i = start; i < s.size(); ++i){ 28 | if (matrix[start][i]==INIT){ 29 | if (is_partition(s, start, i)) 30 | matrix[start][i] = YES; 31 | else 32 | matrix[start][i] = NO; 33 | } 34 | if (matrix[start][i]==YES){ 35 | path.push_back(s.substr(start, i-start+1)); 36 | DFS(s, i+1, res, path); 37 | path.pop_back(); 38 | } 39 | } 40 | } 41 | 42 | bool is_partition(string s, int i, int j){ 43 | while (i= 0; j-- { 24 | if matrix[j][i] { 25 | if j == 0 { 26 | min = 0 27 | } else { 28 | record := records[j-1] + 1 29 | if record < min { 30 | min = record 31 | } 32 | } 33 | } 34 | } 35 | records[i] = min 36 | } 37 | return records[len(bytes)-1] 38 | } 39 | 40 | func isPartition(bytes []byte, i, j int) bool { 41 | for ; i < j; i, j = i+1, j-1 { 42 | if bytes[i] != bytes[j] { 43 | return false 44 | } 45 | } 46 | return true 47 | } 48 | -------------------------------------------------------------------------------- /partition_list/partition_list.go: -------------------------------------------------------------------------------- 1 | package partition_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func partition(head *ListNode, x int) *ListNode { 9 | if head == nil { 10 | return nil 11 | } 12 | lower, bigger := &ListNode{}, &ListNode{} 13 | ptr1, ptr2 := lower, bigger 14 | for head != nil { 15 | if head.Val < x { 16 | ptr1.Next = head 17 | ptr1 = ptr1.Next 18 | } else { 19 | ptr2.Next = head 20 | ptr2 = ptr2.Next 21 | } 22 | head = head.Next 23 | } 24 | ptr2.Next = nil 25 | ptr1.Next = bigger.Next 26 | return lower.Next 27 | } 28 | -------------------------------------------------------------------------------- /pascals_triangle/pascals_triangle.go: -------------------------------------------------------------------------------- 1 | package pascals_triangle 2 | 3 | func generate(numRows int) [][]int { 4 | rets := make([][]int, numRows) 5 | if numRows == 0 { 6 | return rets 7 | } 8 | rets[0] = []int{1} 9 | for i := 1; i < numRows; i++ { 10 | rets[i] = make([]int, i+1) 11 | rets[i][0] = 1 12 | rets[i][i] = 1 13 | for j := 1; j < i; j++ { 14 | rets[i][j] = rets[i-1][j-1] + rets[i-1][j] 15 | } 16 | } 17 | return rets 18 | } 19 | -------------------------------------------------------------------------------- /pascals_triangle_II/pascals_triangle_II.go: -------------------------------------------------------------------------------- 1 | package pascals_triangle_II 2 | 3 | func getRow(rowIndex int) []int { 4 | rets := make([]int, rowIndex+1) 5 | rets[0] = 1 6 | for i := 1; i <= rowIndex; i++ { 7 | rets[i] = 1 8 | for j := i - 1; j > 0; j-- { 9 | rets[j] += rets[j-1] 10 | } 11 | } 12 | return rets 13 | } 14 | -------------------------------------------------------------------------------- /path_sum/path_sum.go: -------------------------------------------------------------------------------- 1 | package path_sum 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func hasPathSum(root *TreeNode, sum int) bool { 10 | if root == nil { 11 | return false 12 | } 13 | if root.Left == nil && root.Right == nil && sum == root.Val { 14 | return true 15 | } 16 | ret := hasPathSum(root.Left, sum-root.Val) 17 | if !ret { 18 | return hasPathSum(root.Right, sum-root.Val) 19 | } 20 | return true 21 | } 22 | -------------------------------------------------------------------------------- /path_sum_II/path_sum_II.go: -------------------------------------------------------------------------------- 1 | package path_sum_II 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func pathSum(root *TreeNode, sum int) [][]int { 10 | return helper(root, sum, []int{}) 11 | } 12 | 13 | func helper(root *TreeNode, sum int, solution []int) (rets [][]int) { 14 | if root == nil { 15 | return 16 | } 17 | if root.Left == nil && root.Right == nil { 18 | if root.Val != sum { 19 | return 20 | } 21 | tmp := make([]int, len(solution)+1) 22 | copy(tmp, solution) 23 | tmp[len(solution)] = sum 24 | rets = append(rets, tmp) 25 | } 26 | solution = append(solution, root.Val) 27 | leftRets := helper(root.Left, sum-root.Val, solution) 28 | rightRets := helper(root.Right, sum-root.Val, solution) 29 | if len(leftRets) != 0 { 30 | rets = append(rets, leftRets...) 31 | } 32 | if len(rightRets) != 0 { 33 | rets = append(rets, rightRets...) 34 | } 35 | return rets 36 | } 37 | -------------------------------------------------------------------------------- /peeking_iterator/peeking_iterator.cpp: -------------------------------------------------------------------------------- 1 | // Below is the interface for Iterator, which is already defined for you. 2 | // **DO NOT** modify the interface for Iterator. 3 | class Iterator { 4 | struct Data; 5 | Data* data; 6 | public: 7 | Iterator(const vector& nums); 8 | Iterator(const Iterator& iter); 9 | virtual ~Iterator(); 10 | // Returns the next element in the iteration. 11 | int next(); 12 | // Returns true if the iteration has more elements. 13 | bool hasNext() const; 14 | }; 15 | 16 | 17 | class PeekingIterator : public Iterator { 18 | int cache; 19 | bool is_peeked; 20 | public: 21 | PeekingIterator(const vector& nums) : Iterator(nums), is_peeked(false) { 22 | 23 | } 24 | 25 | // Returns the next element in the iteration without advancing the iterator. 26 | int peek() { 27 | if (!is_peeked) { 28 | cache = Iterator::next(); 29 | is_peeked = true; 30 | } 31 | return cache; 32 | } 33 | 34 | // hasNext() and next() should behave the same as in the Iterator interface. 35 | // Override them if needed. 36 | int next() { 37 | if (is_peeked) { 38 | is_peeked = false; 39 | return cache; 40 | } 41 | return Iterator::next(); 42 | } 43 | 44 | bool hasNext() const { 45 | if (is_peeked) { 46 | return true; 47 | } 48 | return Iterator::hasNext(); 49 | } 50 | }; -------------------------------------------------------------------------------- /perfect_squares/perfect_squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | if ( n<=0 ) return 0; 5 | static vector dp(1, 0); 6 | if (dp.size() >n) return dp[n]; 7 | for (int i = dp.size(); i <= n; ++i) { 8 | int m = n; 9 | for (int j = 1; i-j*j>=0; ++j) { 10 | m = min(m, dp[i-j*j]+1); 11 | } 12 | dp.push_back(m); 13 | } 14 | return dp[n]; 15 | } 16 | int min(int i, int j) { 17 | if (i < j) return i; 18 | return j; 19 | } 20 | }; -------------------------------------------------------------------------------- /permutation_sequence/permutation_sequence.go: -------------------------------------------------------------------------------- 1 | package permutation_sequence 2 | 3 | func getPermutation(n int, k int) string { 4 | if n == 0 { 5 | return "" 6 | } 7 | data := make([]int, n) 8 | data[0] = 1 9 | iToS := []byte("123456789") 10 | for i := 1; i < n; i++ { 11 | data[i] = data[i-1] * i 12 | } 13 | ret := "" 14 | k-- 15 | for i := n - 1; i >= 0; i-- { 16 | ret += string(iToS[k/data[i]]) 17 | iToS = append(iToS[:k/data[i]], iToS[k/data[i]+1:]...) 18 | k = k % data[i] 19 | } 20 | return ret 21 | } 22 | -------------------------------------------------------------------------------- /permutation_sequence/permutation_sequence_test.go: -------------------------------------------------------------------------------- 1 | package permutation_sequence 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGetPermutation(t *testing.T) { 8 | println(getPermutation(3, 5)) 9 | } 10 | -------------------------------------------------------------------------------- /permutations/permutations_test.go: -------------------------------------------------------------------------------- 1 | package permutations 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestPermute(t *testing.T) { 9 | fmt.Printf("%v\n", permute([]int{1, 2, 3})) 10 | } 11 | -------------------------------------------------------------------------------- /permutations_II/permutations_II.go: -------------------------------------------------------------------------------- 1 | package permutations_II 2 | 3 | func permuteUnique(nums []int) [][]int { 4 | return traverse(nums, map[int]bool{}, []int{}) 5 | } 6 | 7 | func traverse(nums []int, m map[int]bool, solution []int) (rets [][]int) { 8 | if len(nums) == 0 { 9 | return [][]int{} 10 | } 11 | if len(nums) == 1 { 12 | return [][]int{[]int{nums[0]}} 13 | } 14 | if len(solution) == len(nums) { 15 | replia := make([]int, len(solution)) 16 | copy(replia, solution) 17 | rets = append(rets, replia) 18 | return 19 | } 20 | repliaMap := map[int]bool{} 21 | for i, num := range nums { 22 | if m[i] || repliaMap[num] { 23 | continue 24 | } 25 | repliaMap[num] = true 26 | m[i] = true 27 | solution = append(solution, num) 28 | rets = append(rets, traverse(nums, m, solution)...) 29 | delete(m, i) 30 | solution = solution[:len(solution)-1] 31 | } 32 | return rets 33 | } 34 | -------------------------------------------------------------------------------- /plus_one/plus_one.go: -------------------------------------------------------------------------------- 1 | package plus_one 2 | 3 | func plusOne(digits []int) []int { 4 | carry := 1 5 | for i := len(digits)-1; i >= 0; i-- { 6 | sum := carry + digits[i] 7 | if sum < 10 { 8 | digits[i] = sum 9 | return digits 10 | } 11 | digits[i] = sum % 10 12 | carry = 1 13 | } 14 | if carry == 1 { 15 | return append([]int{carry}, digits...) 16 | } 17 | return digits 18 | } 19 | -------------------------------------------------------------------------------- /populating_next_right_pointers_in_each_node/populating_next_right_pointers_in_each_node.cpp: -------------------------------------------------------------------------------- 1 | struct TreeLinkNode { 2 | int val; 3 | TreeLinkNode *left, *right, *next; 4 | TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 5 | }; 6 | 7 | void connect(TreeLinkNode *root){ 8 | if (!root){ 9 | return; 10 | } 11 | TreeLinkNode* currentNode; 12 | while (root->left != NULL){ 13 | currentNode = root; 14 | while (currentNode != NULL){ 15 | currentNode->left->next = currentNode->right; 16 | if (currentNode->next != NULL){ 17 | currentNode->right->next = currentNode->next->left; 18 | } 19 | currentNode = currentNode->next; 20 | } 21 | root = root->left; 22 | } 23 | return; 24 | } -------------------------------------------------------------------------------- /populating_next_right_pointers_in_each_node_II/populating_next_right_pointers_in_each_node_II.cpp: -------------------------------------------------------------------------------- 1 | struct TreeLinkNode { 2 | int val; 3 | TreeLinkNode *left, *right, *next; 4 | TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 5 | }; 6 | 7 | void connect(TreeLinkNode *root) { 8 | TreeLinkNode *head, *tail, *last; 9 | #undef PUSH 10 | #define PUSH(node)\ 11 | if (head == NULL) { head = tail = node;}\ 12 | else { tail->next = node; tail = node;} 13 | 14 | head = tail = NULL; 15 | last = root; 16 | PUSH(root); 17 | while (head != NULL){ 18 | TreeLinkNode *p = head; 19 | head = head->next; 20 | if (p->left) PUSH(p->left); 21 | if (p->right) PUSH(p->right); 22 | if (p == last){ 23 | last = tail; 24 | p->next = NULL; 25 | } 26 | } 27 | return; 28 | } -------------------------------------------------------------------------------- /pow_x_n/pow_x_n.go: -------------------------------------------------------------------------------- 1 | package pow_x_n 2 | 3 | func myPow(x float64, n int) float64 { 4 | ret := 1.0 5 | sign := true 6 | if n < 0 { 7 | n = -n 8 | sign = false 9 | } 10 | for n != 0 { 11 | if n%2 == 1 { 12 | ret *= x 13 | } 14 | n >>= 1 15 | x *= x 16 | } 17 | 18 | if !sign { 19 | return 1 / ret 20 | } 21 | return ret 22 | } 23 | -------------------------------------------------------------------------------- /power_of_four/power_of_four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int num) { 4 | static int mask = 0b01010101010101010101010101010101; 5 | 6 | //edge case 7 | if (num<=0) return false; 8 | 9 | // there are multiple bits are 1 10 | if ((num & num-1) != 0) return false; 11 | 12 | // check which one bit is zero, if the place is 1 or 3 or 5 or 7 or 9..., 13 | // then it is the power of 4 14 | if ((num & mask) != 0) return true; 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /power_of_three/power_of_three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | return (n > 0 && 1162261467 % n == 0); 5 | } 6 | }; -------------------------------------------------------------------------------- /power_of_two/power_of_two.go: -------------------------------------------------------------------------------- 1 | package power_of_two 2 | 3 | func isPowerOfTwo(n int) bool { 4 | if n < 1 { 5 | return false 6 | } 7 | for n > 1 { 8 | if n&1 != 0 { 9 | return false 10 | } 11 | n >>= 1 12 | } 13 | return true 14 | } 15 | -------------------------------------------------------------------------------- /product_of_array_except_self/product_of_array_except_self.go: -------------------------------------------------------------------------------- 1 | package product_of_array_except_self 2 | 3 | func productExceptSelf(nums []int) []int { 4 | ret := make([]int, len(nums)) 5 | left := 1 6 | right := 1 7 | for i := 0; i < len(nums); i++ { 8 | if i <= (len(nums)-1)/2 { 9 | ret[i] = 1 10 | ret[len(nums)-i-1] = 1 11 | } 12 | ret[len(nums)-i-1] *= right 13 | ret[i] *= left 14 | left *= nums[i] 15 | right *= nums[len(nums)-i-1] 16 | } 17 | return ret 18 | } 19 | -------------------------------------------------------------------------------- /range_sum_query_2d_immutable/range_sum_query_2d_immutable.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class NumMatrix { 5 | vector> records; 6 | public: 7 | NumMatrix(vector> &matrix) { 8 | int row = matrix.size(); 9 | int col = row == 0 ? 0 : matrix[0].size(); 10 | records = vector>(row+1, vector(col+1, 0)); 11 | for (int i = 0; i < row; ++i) { 12 | for (int j = 0; j < col; ++j) { 13 | records[i+1][j+1] = records[i][j+1] + records[i+1][j] - records[i][j] + matrix[i][j]; 14 | } 15 | } 16 | } 17 | 18 | int sumRegion(int row1, int col1, int row2, int col2) { 19 | return records[row2+1][col2+1] - records[row2+1][col1] - records[row1][col2+1] + records[row1][col1]; 20 | } 21 | }; -------------------------------------------------------------------------------- /range_sum_query_immutable/range_sum_query_immutable.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class NumArray { 5 | vector fn; 6 | public: 7 | NumArray(vector &nums): fn(vector(nums.size()+1)) { 8 | fn[0] = 0; 9 | for (int i = 0; i < nums.size(); ++i) { 10 | fn[i+1] = fn[i] + nums[i]; 11 | } 12 | } 13 | 14 | int sumRange(int i, int j) { 15 | return fn[j] - fn[i-1]; 16 | } 17 | }; -------------------------------------------------------------------------------- /range_sum_query_mutable/range_sum_query_mutable.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | vector records; 3 | vector ori; 4 | public: 5 | NumArray(vector &nums): records(vector(nums.size()+1, 0)), ori(nums) { 6 | for (int i = 0; i < nums.size(); ++i) { 7 | add(i+1, nums[i]); 8 | } 9 | } 10 | 11 | void update(int i, int val) { 12 | int diff = val - ori[i]; 13 | ori[i] = val; 14 | add(i+1, diff); 15 | } 16 | 17 | int sumRange(int i, int j) { 18 | return sum(j+1) - sum(i); 19 | } 20 | 21 | void add(int x, int diff) { 22 | while (x < records.size()) { 23 | records[x] += diff; 24 | x += lowbit(x); 25 | } 26 | } 27 | 28 | int sum(int x) { 29 | int ret = 0; 30 | while (x > 0) { 31 | ret += records[x]; 32 | x -= lowbit(x); 33 | } 34 | return ret; 35 | } 36 | 37 | int lowbit(int n) { 38 | return n&-n; 39 | } 40 | }; -------------------------------------------------------------------------------- /ransom_note/ransom_note.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string ransomNote, string magazine) { 4 | vector count(26, 0); 5 | for (auto& ch: magazine) { 6 | ++count[ch-'a']; 7 | } 8 | for (auto& ch: ransomNote) { 9 | if (count[ch-'a'] <= 0) return false; 10 | --count[ch-'a']; 11 | } 12 | return true; 13 | } 14 | }; -------------------------------------------------------------------------------- /reconstruct_ltinerary/reconstruct_ltinerary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findItinerary(vector> tickets) { 4 | unordered_map> graph; 5 | for (auto& kv: tickets) { 6 | graph[kv.first].insert(kv.second); 7 | } 8 | vector solution; 9 | DFS(graph, solution, "JFK"); 10 | return vector(solution.rbegin(), solution.rend()); 11 | } 12 | void DFS(unordered_map>& graph, vector& solution, string start) { 13 | while (!graph[start].empty()) { 14 | string city = *graph[start].begin(); 15 | graph[start].erase(city); 16 | (DFS(graph, solution, city)); 17 | } 18 | solution.push_back(start); 19 | return; 20 | } 21 | }; -------------------------------------------------------------------------------- /rectangle_area/rectangle_area.go: -------------------------------------------------------------------------------- 1 | package rectangle_area 2 | 3 | func computeArea(A int, B int, C int, D int, E int, F int, G int, H int) int { 4 | if C <= E || G <= A || D <= F || H <= B { 5 | return (C-A)*(D-B) + (G-E)*(H-F) 6 | } 7 | left := max(A, E) 8 | bottom := max(B, F) 9 | right := min(C, G) 10 | top := min(D, H) 11 | return (C-A)*(D-B) + (G-E)*(H-F) - (right-left)*(top-bottom) 12 | } 13 | 14 | func min(i, j int) int { 15 | if i < j { 16 | return i 17 | } 18 | return j 19 | } 20 | 21 | func max(i, j int) int { 22 | if i > j { 23 | return i 24 | } 25 | return j 26 | } 27 | -------------------------------------------------------------------------------- /regular_expression_matching/regular_expression_matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | return isMatch(s, p, s.size(), p.size()); 5 | } 6 | bool isMatch(string& s, string& p, int i, int j) { 7 | if (i == 0 && j == 0) return true; 8 | if (i != 0 && j == 0) return false; 9 | if (i == 0 && j != 0) { 10 | if (p[j-1] == '*') { 11 | return isMatch(s, p, i, j-2); 12 | } 13 | return false; 14 | } 15 | if (s[i-1] == p[j-1] || p[j-1] == '.') { 16 | return isMatch(s, p, i-1, j-1); 17 | } else if (p[j-1] == '*') { 18 | if (isMatch(s, p, i, j-2)) return true; 19 | if (s[i-1] == p[j-2] || p[j-2] == '.') { 20 | return isMatch(s, p, i-1, j); 21 | } 22 | return false; 23 | } 24 | return false; 25 | } 26 | }; -------------------------------------------------------------------------------- /remove_duplicate_letters/remove_duplicate_letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicateLetters(string s) { 4 | if (s.size() == 0) return ""; 5 | unordered_map count; 6 | for (int i = 0; i < s.size(); ++i) { 7 | ++count[s[i]]; 8 | } 9 | unordered_set existed = {s[0]}; 10 | vector vec = {s[0]}; 11 | --count[s[0]]; 12 | for (int i = 1; i < s.size(); ++i) { 13 | --count[s[i]]; 14 | if (existed.count(s[i]) == 0) { 15 | while (!vec.empty()) { 16 | char back = vec.back(); 17 | if (back <= s[i] || count[back] == 0) break; 18 | vec.pop_back(); 19 | existed.erase(back); 20 | } 21 | vec.push_back(s[i]); 22 | existed.insert(s[i]); 23 | } 24 | } 25 | string ret; 26 | for (auto ch: vec) { 27 | ret += ch; 28 | } 29 | return ret; 30 | } 31 | }; -------------------------------------------------------------------------------- /remove_duplicates_from_sorted_array/remove_duplicates_from_sorted_array.go: -------------------------------------------------------------------------------- 1 | package remove_duplicates_from_sorted_array 2 | 3 | func removeDuplicates(nums []int) int { 4 | if len(nums) < 2 { 5 | return len(nums) 6 | } 7 | start, preVal := 1, nums[0] 8 | for i := 1; i < len(nums); i++ { 9 | if nums[i] != preVal { 10 | start, preVal, nums[start] = start+1, nums[i], nums[i] 11 | } 12 | } 13 | return start 14 | } 15 | -------------------------------------------------------------------------------- /remove_duplicates_from_sorted_array_II/remove_duplicates_from_sorted_array_II.go: -------------------------------------------------------------------------------- 1 | package remove_duplicates_from_sorted_array_II 2 | 3 | func removeDuplicates(nums []int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | begin := 0 8 | for i := 1; i < len(nums); i++ { 9 | if nums[i] != nums[begin] || begin == 0 || nums[i] != nums[begin-1] { 10 | begin++ 11 | nums[begin], nums[i] = nums[i], nums[begin] 12 | } 13 | } 14 | return begin + 1 15 | } 16 | -------------------------------------------------------------------------------- /remove_duplicates_from_sorted_list/remove_duplicates_from_sorted_list.go: -------------------------------------------------------------------------------- 1 | package remove_duplicates_from_sorted_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func deleteDuplicates(head *ListNode) *ListNode { 9 | if head == nil { 10 | return nil 11 | } 12 | pre, current := head, head 13 | for current != nil { 14 | for current.Next != nil && current.Val == current.Next.Val { 15 | current = current.Next 16 | } 17 | pre.Next = current.Next 18 | pre, current = current.Next, current.Next 19 | } 20 | return head 21 | } 22 | -------------------------------------------------------------------------------- /remove_duplicates_from_sorted_list_II/remove_duplicates_from_sorted_list_II.go: -------------------------------------------------------------------------------- 1 | package remove_duplicates_from_sorted_list_II 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func deleteDuplicates(head *ListNode) *ListNode { 9 | if head == nil { 10 | return nil 11 | } 12 | helper := &ListNode{Next: head} 13 | pre, current := helper, helper.Next 14 | for current != nil { 15 | for current.Next != nil && current.Next.Val == current.Val { 16 | current = current.Next 17 | } 18 | if pre.Next == current { 19 | pre = pre.Next 20 | } else { 21 | pre.Next = current.Next 22 | } 23 | current = current.Next 24 | } 25 | return helper.Next 26 | } 27 | -------------------------------------------------------------------------------- /remove_element/remove_element.go: -------------------------------------------------------------------------------- 1 | package remove_element 2 | 3 | func removeElement(nums []int, val int) int { 4 | l := 0 5 | for _, v := range nums { 6 | if v != val { 7 | nums[l] = v 8 | l++ 9 | } 10 | } 11 | 12 | return l 13 | } 14 | -------------------------------------------------------------------------------- /remove_linked_list_elements/remove_linked_list_elements.go: -------------------------------------------------------------------------------- 1 | package remove_linked_list_elements 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func removeElements(head *ListNode, val int) *ListNode { 9 | fake := &ListNode{Next: head} 10 | p := fake 11 | for p != nil && p.Next != nil { 12 | if p.Next.Val == val { 13 | p.Next = p.Next.Next 14 | } else { 15 | p = p.Next 16 | } 17 | } 18 | return fake.Next 19 | } 20 | -------------------------------------------------------------------------------- /remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go: -------------------------------------------------------------------------------- 1 | package remove_nth_node_from_end_of_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func removeNthFromEnd(head *ListNode, n int) *ListNode { 9 | if head == nil { 10 | return nil 11 | } 12 | list := []*ListNode{} 13 | var ptr *ListNode 14 | for ptr = head; ptr.Next != nil; ptr = ptr.Next { 15 | list = append(list, ptr) 16 | } 17 | list = append(list, ptr) 18 | index := len(list) - n 19 | if index == 0 { 20 | return head.Next 21 | } 22 | list[index-1].Next = list[index].Next 23 | return head 24 | } 25 | -------------------------------------------------------------------------------- /reorder_list/reorder_list.go: -------------------------------------------------------------------------------- 1 | package reorder_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func reorderList(head *ListNode) { 9 | slow, fast := head, head 10 | var tail *ListNode 11 | for fast != nil && fast.Next != nil { 12 | tail = slow 13 | slow = slow.Next 14 | fast = fast.Next.Next 15 | } 16 | if tail != nil { 17 | tail.Next = nil 18 | } 19 | var secondHead *ListNode 20 | fast = slow 21 | for fast != nil { 22 | slow = fast 23 | fast = fast.Next 24 | slow.Next = secondHead 25 | secondHead = slow 26 | } 27 | firstHead := head 28 | var p1, p2 *ListNode 29 | for firstHead != nil && secondHead != nil { 30 | p1 = firstHead.Next 31 | p2 = secondHead.Next 32 | firstHead.Next = secondHead 33 | secondHead.Next = p1 34 | if p1 == nil { 35 | secondHead.Next = p2 36 | break 37 | } 38 | firstHead = p1 39 | secondHead = p2 40 | } 41 | return 42 | } 43 | -------------------------------------------------------------------------------- /repeated_dna_sequences/repeated_dna_sequences.go: -------------------------------------------------------------------------------- 1 | package repeated_dna_sequences 2 | 3 | func findRepeatedDnaSequences(s string) []string { 4 | m := map[string]int{} 5 | rets := []string{} 6 | for i := 0; i <= len(s)-10; i++ { 7 | sub := string(s[i : i+10]) 8 | m[sub]++ 9 | if m[sub] == 2 { 10 | rets = append(rets, sub) 11 | } 12 | } 13 | return rets 14 | } 15 | -------------------------------------------------------------------------------- /restore_IP_addresses/restore_IP_addresses_test.go: -------------------------------------------------------------------------------- 1 | package restore_IP_addresses 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestRestoreIpAddresses(t *testing.T) { 9 | fmt.Println(restoreIpAddresses("25525511135")) 10 | } 11 | -------------------------------------------------------------------------------- /reverse_bits/reverse_bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | uint32_t ret = 0; 5 | for (int i = 0; i < 32; ++i){ 6 | ret = ret*2 + (n&0x1); 7 | n /= 2; 8 | } 9 | return ret; 10 | } 11 | }; -------------------------------------------------------------------------------- /reverse_integer/reverse_integer.go: -------------------------------------------------------------------------------- 1 | package reverse_integer 2 | 3 | // fucking leetcode's int32 overflow test cases 4 | const ( 5 | MAX int32 = 1<<31 - 1 6 | MIN = -MAX - 1 7 | ) 8 | 9 | func reverse(x int) int { 10 | var sign int32 = 1 11 | tmp := x 12 | if x < 0 { 13 | sign = -1 14 | tmp = -1 * x 15 | } 16 | list := []int32{} 17 | for tmp > 9 { 18 | list = append(list, int32(tmp%10)) 19 | tmp = tmp / 10 20 | } 21 | list = append(list, int32(tmp)) 22 | var ret int32 23 | for i := 0; i < len(list); i++ { 24 | if sign == 1 { 25 | if ret > (MAX-list[i])/10 { 26 | return 0 27 | } 28 | } else { 29 | if -ret < (MIN+list[i])/10 { 30 | return 0 31 | } 32 | } 33 | ret = 10*ret + list[i] 34 | } 35 | return int(ret * sign) 36 | } 37 | -------------------------------------------------------------------------------- /reverse_integer/reverse_integer_test.go: -------------------------------------------------------------------------------- 1 | package reverse_integer 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestReverse(t *testing.T) { 8 | tests := []int{ 9 | 123, 10 | -123, 11 | 0, 12 | -1, 13 | 1534236469, 14 | } 15 | results := []int{ 16 | 321, 17 | -321, 18 | 0, 19 | -1, 20 | 0, 21 | } 22 | caseNum := 5 23 | for i := 0; i < caseNum; i++ { 24 | if ret := reverse(tests[i]); ret != results[i] { 25 | t.Fatalf("case %d failed\nactual: %d, expect: %d\n", i, ret, results[i]) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /reverse_linked_list/reverse_linked_list.go: -------------------------------------------------------------------------------- 1 | package reverse_linked_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func reverseList(head *ListNode) *ListNode { 9 | var tail, next *ListNode 10 | for head != nil && head.Next != nil { 11 | next = head.Next 12 | head.Next = tail 13 | tail = head 14 | head = next 15 | } 16 | if head != nil { 17 | head.Next = tail 18 | } 19 | return head 20 | } 21 | -------------------------------------------------------------------------------- /reverse_linked_list_II/reverse_linked_list_II.go: -------------------------------------------------------------------------------- 1 | package reverse_linked_list_II 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func reverseBetween(head *ListNode, m int, n int) *ListNode { 9 | if head == nil || m == n { 10 | return head 11 | } 12 | fake := &ListNode{Next: head} 13 | tmp := fake 14 | for i := 0; i < m-1; i++ { 15 | tmp = tmp.Next 16 | } 17 | current, post := tmp.Next, tmp.Next.Next 18 | tail := current 19 | count := n - m 20 | var ptr *ListNode 21 | for ; count > 0; count-- { 22 | ptr = post.Next 23 | post.Next = current 24 | current = post 25 | post = ptr 26 | } 27 | tail.Next = post 28 | tmp.Next = current 29 | return fake.Next 30 | } 31 | -------------------------------------------------------------------------------- /reverse_nodes_in_k_group/reverse_nodes_in_k_group.go: -------------------------------------------------------------------------------- 1 | package reverse_nodes_in_k_group 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func reverseKGroup(head *ListNode, k int) *ListNode { 9 | if k <= 0 { 10 | return head 11 | } 12 | fake := &ListNode{Next: head} 13 | p := fake 14 | for p != nil { 15 | p.Next = reverseKNodes(p.Next, k) 16 | for i := 0; p != nil && i < k; i++ { 17 | p = p.Next 18 | } 19 | } 20 | return fake.Next 21 | } 22 | 23 | func reverseKNodes(head *ListNode, k int) *ListNode { 24 | end := head 25 | for k > 0 && end != nil { 26 | end = end.Next 27 | k-- 28 | } 29 | if k > 0 { 30 | return head 31 | } 32 | ret, pNode := end, head 33 | var qNode *ListNode 34 | for pNode != end { 35 | qNode = pNode.Next 36 | pNode.Next = ret 37 | ret = pNode 38 | pNode = qNode 39 | } 40 | return ret 41 | } 42 | -------------------------------------------------------------------------------- /reverse_nodes_in_k_group/reverse_nodes_in_k_group_test.go: -------------------------------------------------------------------------------- 1 | package reverse_nodes_in_k_group 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestReverseKGroup(t *testing.T) { 8 | head := &ListNode{ 9 | Val: 1, 10 | Next: &ListNode{ 11 | Val: 2, 12 | Next: &ListNode{ 13 | Val: 3, 14 | }, 15 | }, 16 | } 17 | reverseKGroup(head, 2) 18 | } 19 | -------------------------------------------------------------------------------- /reverse_string/reverse_string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseString(string s) { 4 | string ret(s.size(), '\0'); 5 | for (int i = 0, j = s.size()-1; i <= j; ++i, --j) { 6 | ret[i] = s[j]; 7 | ret[j] = s[i]; 8 | } 9 | return ret; 10 | } 11 | }; -------------------------------------------------------------------------------- /reverse_vowels_of_a_string/reverse_vowels_of_a_string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseVowels(string s) { 4 | unordered_set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 5 | string ret(s.size(), '\0'); 6 | for (int i = 0, j = s.size()-1; i <= j; ++i, --j) { 7 | while (i < s.size()-1 && vowels.count(s[i]) == 0) { 8 | ret[i] = s[i]; 9 | ++i; 10 | } 11 | while (j >= 0 && vowels.count(s[j]) == 0) { 12 | ret[j] = s[j]; 13 | --j; 14 | } 15 | if (i > j) break; 16 | ret[i] = s[j]; 17 | ret[j] = s[i]; 18 | } 19 | return ret; 20 | } 21 | }; -------------------------------------------------------------------------------- /reverse_words_in_a_string/reverse_words_in_a_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | void reverseWords(string &s) { 9 | vector words; 10 | bool found = false; 11 | int start = -1; 12 | const char space = ' '; 13 | for (int i = 0; i < s.size(); ++i){ 14 | if (found && s[i]==space){ 15 | words.push_back(s.substr(start, i-start)); 16 | found = false; 17 | }else if (!found && s[i]!=space){ 18 | start = i; 19 | found = true; 20 | } 21 | } 22 | if (found) words.push_back(s.substr(start)); 23 | s.clear(); 24 | if (words.empty()) return; 25 | for (int i = words.size()-1; i > 0; --i){ 26 | s += words[i]; 27 | s.push_back(space); 28 | } 29 | s += words[0]; 30 | return; 31 | } 32 | }; -------------------------------------------------------------------------------- /roman_to_integer/roman_to_integer.go: -------------------------------------------------------------------------------- 1 | package roman_to_integer 2 | 3 | func romanToInt(s string) int { 4 | m := map[rune]int{ 5 | rune('I'): 1, 6 | rune('V'): 5, 7 | rune('X'): 10, 8 | rune('L'): 50, 9 | rune('C'): 100, 10 | rune('D'): 500, 11 | rune('M'): 1000, 12 | } 13 | runes := []rune(s) 14 | if len(runes) == 1 { 15 | return m[runes[0]] 16 | } 17 | ret := m[runes[0]] 18 | for i := 1; i < len(runes); i++ { 19 | if m[runes[i-1]] < m[runes[i]] { 20 | ret += m[runes[i]] - 2*m[runes[i-1]] 21 | } else { 22 | ret += m[runes[i]] 23 | } 24 | } 25 | return ret 26 | } 27 | -------------------------------------------------------------------------------- /roman_to_integer/roman_to_integer_test.go: -------------------------------------------------------------------------------- 1 | package roman_to_integer 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestRomanToInt(t *testing.T) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /rotate_array/rotate_array.go: -------------------------------------------------------------------------------- 1 | package rotate_array 2 | 3 | func rotate(nums []int, k int) { 4 | k %= len(nums) 5 | reverse(nums, 0, len(nums)-1) 6 | reverse(nums, 0, k-1) 7 | reverse(nums, k, len(nums)-1) 8 | return 9 | } 10 | 11 | func reverse(nums []int, i, j int) { 12 | for ; i < j; i, j = i+1, j-1 { 13 | nums[i], nums[j] = nums[j], nums[i] 14 | } 15 | return 16 | } 17 | -------------------------------------------------------------------------------- /rotate_function/rotate_function.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxRotateFunction(vector& A) { 4 | if (A.size() == 0) return 0; 5 | int sum = 0; 6 | int pre = 0; 7 | for (int i = 0; i < A.size(); ++i) { 8 | sum += A[i]; 9 | pre += i * A[i]; 10 | } 11 | int ret = pre; 12 | int len = A.size(); 13 | for (int i = 0; i < len-1; ++i) { 14 | pre = pre - sum + len*A[i]; 15 | ret = max(ret, pre); 16 | } 17 | return ret; 18 | } 19 | }; -------------------------------------------------------------------------------- /rotate_image/rotate_image.go: -------------------------------------------------------------------------------- 1 | package rotate_image 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func rotate(matrix [][]int) { 8 | n := len(matrix) - 1 9 | for i := 0; i < n/2+1; i++ { 10 | for j := 0; j < len(matrix)/2; j++ { 11 | matrix[j][n-i], matrix[n-i][n-j], matrix[n-j][i], matrix[i][j] = matrix[i][j], matrix[j][n-i], matrix[n-i][n-j], matrix[n-j][i] 12 | } 13 | } 14 | return 15 | } 16 | -------------------------------------------------------------------------------- /rotate_list/rotate_list.go: -------------------------------------------------------------------------------- 1 | package rotate_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func rotateRight(head *ListNode, k int) *ListNode { 9 | if head == nil { 10 | return nil 11 | } 12 | cnt := 0 13 | for tmp := head; tmp != nil; tmp = tmp.Next { 14 | cnt++ 15 | } 16 | k %= cnt 17 | if k == 0 { 18 | return head 19 | } 20 | pre, post := head, head 21 | for i := 0; i < k && post != nil; i++ { 22 | post = post.Next 23 | } 24 | if post == nil { 25 | return head 26 | } 27 | for post.Next != nil { 28 | pre, post = pre.Next, post.Next 29 | } 30 | newHead := pre.Next 31 | post.Next = head 32 | pre.Next = nil 33 | return newHead 34 | } 35 | -------------------------------------------------------------------------------- /russian_doll_envelopes/russian_doll_envelopes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxEnvelopes(vector>& envelopes) { 4 | vector dp; 5 | sort(envelopes.begin(), envelopes.end(), [](const pair& a, const pair& b) { 6 | if (a.first == b.first) return a.second > b.second; 7 | return a.first < b.first; 8 | }); 9 | for (int i = 0; i < envelopes.size(); ++i) { 10 | int left = 0, right = dp.size(); 11 | while (left < right) { 12 | int mid = left + (right-left)/2; 13 | if (dp[mid] < envelopes[i].second) { 14 | left = mid+1; 15 | }else { 16 | right = mid; 17 | } 18 | } 19 | if (right >= dp.size()) dp.push_back(envelopes[i].second); 20 | else dp[right] = envelopes[i].second; 21 | } 22 | return dp.size(); 23 | } 24 | }; -------------------------------------------------------------------------------- /same_tree/same_tree.go: -------------------------------------------------------------------------------- 1 | package same_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func isSameTree(p *TreeNode, q *TreeNode) bool { 10 | if p == nil && q != nil || p != nil && q == nil { 11 | return false 12 | } 13 | if p == nil && q == nil { 14 | return true 15 | } 16 | if p.Val != q.Val { 17 | return false 18 | } 19 | ret := isSameTree(p.Left, q.Left) 20 | if !ret { 21 | return false 22 | } 23 | return isSameTree(p.Right, q.Right) 24 | } 25 | -------------------------------------------------------------------------------- /search_a_2D_matrix/search_a_2D_matrix.go: -------------------------------------------------------------------------------- 1 | package search_a_2D_matrix 2 | 3 | func searchMatrix(matrix [][]int, target int) bool { 4 | if len(matrix) == 0 || len(matrix[0]) == 0 { 5 | return false 6 | } 7 | row := -1 8 | for i := 0; i < len(matrix); i++ { 9 | if matrix[i][0] <= target && (i < len(matrix)-1 && matrix[i+1][0] > target || i == len(matrix)-1) { 10 | row = i 11 | break 12 | } 13 | } 14 | if row == -1 { 15 | return false 16 | } 17 | return binarySearch(matrix[row], 0, len(matrix[row])-1, target) 18 | } 19 | 20 | func binarySearch(array []int, i, j, target int) bool { 21 | if i > j { 22 | return false 23 | } 24 | mid := i + (j-i)/2 25 | if array[mid] == target { 26 | return true 27 | } 28 | success := binarySearch(array, i, mid-1, target) 29 | if success { 30 | return true 31 | } 32 | return binarySearch(array, mid+1, j, target) 33 | } 34 | -------------------------------------------------------------------------------- /search_a_2D_matrix_II/search_a_2D_matrix_II.go: -------------------------------------------------------------------------------- 1 | package search_a_2D_matrix_II 2 | 3 | func searchMatrix(matrix [][]int, target int) bool { 4 | if len(matrix) == 0 || len(matrix[0]) == 0 { 5 | return false 6 | } 7 | row, col := 0, len(matrix[0])-1 8 | for row <= len(matrix)-1 && col >= 0 { 9 | if matrix[row][col] == target { 10 | return true 11 | } 12 | for row <= len(matrix)-1 && col >= 0 && matrix[row][col] < target { 13 | row++ 14 | } 15 | for row <= len(matrix)-1 && col >= 0 && matrix[row][col] > target { 16 | col-- 17 | } 18 | } 19 | return false 20 | } 21 | -------------------------------------------------------------------------------- /search_for_a_range/search_for_a_range_test.go: -------------------------------------------------------------------------------- 1 | package search_for_a_range 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestSearchRange(t *testing.T) { 8 | ret := searchRange([]int{1, 2, 3, 3, 3, 3, 4, 5, 9}, 3) 9 | println("ret", ret[0], ret[1]) 10 | } 11 | -------------------------------------------------------------------------------- /search_in_rotated_sorted_array/search_in_rotated_sorted_array_test.go: -------------------------------------------------------------------------------- 1 | package search_in_rotated_sorted_array 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestSearch(t *testing.T) { 8 | println(search([]int{4, 5, 6, 7, 0, 1, 2}, 4)) 9 | } 10 | -------------------------------------------------------------------------------- /search_insert_position/search_insert_position.go: -------------------------------------------------------------------------------- 1 | package search_insert_position 2 | 3 | func searchInsert(nums []int, target int) int { 4 | return searchInsertI(nums, 0, len(nums)-1, target) 5 | } 6 | 7 | func searchInsertI(nums []int, left, right, target int) int { 8 | length := len(nums) 9 | if length == 0 { 10 | return 0 11 | } 12 | if left > right { 13 | return -1 14 | } 15 | if nums[left] > target { 16 | return left 17 | } 18 | if nums[right] < target { 19 | return right + 1 20 | } 21 | mid := left + (right-left)/2 22 | if nums[mid] == target { 23 | return mid 24 | } else if nums[mid] < target { 25 | return searchInsertI(nums, mid+1, right, target) 26 | } 27 | return searchInsertI(nums, left, mid-1, target) 28 | } 29 | -------------------------------------------------------------------------------- /self_crossing/self_crossing.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSelfCrossing(vector& x) { 4 | int m = x.size(); 5 | for(int i=0; i=3 && x[i]>=x[i-2] && x[i-3]>=x[i-1]) 7 | return true; 8 | if(i>=4 && x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) 9 | return true; 10 | if(i>=5 && x[i-3]>x[i-1] && x[i-2]>x[i-4] && x[i]+x[i-4]>=x[i-2] && x[i-1]+x[i-5]>=x[i-3]) 11 | return true; 12 | } 13 | return false; 14 | } 15 | }; -------------------------------------------------------------------------------- /serialize_and_deserialize_binary_tree/serialize_and_deserialize_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Codec { 12 | public: 13 | string serialize(TreeNode* root) { 14 | if (root == NULL) { 15 | return "null"; 16 | } 17 | string ret = to_string(root->val); 18 | ret += "," + serialize(root->left); 19 | ret += "," + serialize(root->right); 20 | return ret; 21 | } 22 | 23 | TreeNode* deserialize(string data) { 24 | int idx = 0; 25 | return helper(data, idx); 26 | } 27 | 28 | TreeNode* helper(string& data, int& idx) { 29 | int start = idx; 30 | for (; idx < data.size(); ++idx) { 31 | if (data[idx] == ',') { 32 | break; 33 | } 34 | } 35 | string sub = data.substr(start, idx-start); 36 | ++idx; 37 | if (sub == "null") return NULL; 38 | TreeNode* node = new TreeNode(stoi(sub)); 39 | if (idx == data.size()) return node; 40 | node->left = helper(data, idx); 41 | node->right = helper(data, idx); 42 | return node; 43 | } 44 | }; -------------------------------------------------------------------------------- /set_matrix_zeroes/set_matrix_zeroes.go: -------------------------------------------------------------------------------- 1 | package set_matrix_zeroes 2 | 3 | func setZeroes(matrix [][]int) { 4 | if len(matrix) == 0 || len(matrix[0]) == 0 { 5 | return 6 | } 7 | var clearRow, clearCol bool 8 | for i := 0; i < len(matrix); i++ { 9 | for j := 0; j < len(matrix[0]); j++ { 10 | if matrix[i][j] == 0 { 11 | if i == 0 { 12 | clearRow = true 13 | } 14 | if j == 0 { 15 | clearCol = true 16 | } 17 | if i != 0 && j != 0 { 18 | matrix[0][j] = 0 19 | matrix[i][0] = 0 20 | } 21 | } 22 | } 23 | } 24 | for i := 1; i < len(matrix); i++ { 25 | if matrix[i][0] == 0 { 26 | for j := 1; j < len(matrix[0]); j++ { 27 | matrix[i][j] = 0 28 | } 29 | } 30 | } 31 | for j := 1; j < len(matrix[0]); j++ { 32 | if matrix[0][j] == 0 { 33 | for i := 1; i < len(matrix); i++ { 34 | matrix[i][j] = 0 35 | } 36 | } 37 | } 38 | if clearRow { 39 | for j := 0; j < len(matrix[0]); j++ { 40 | matrix[0][j] = 0 41 | } 42 | } 43 | if clearCol { 44 | for i := 0; i < len(matrix); i++ { 45 | matrix[i][0] = 0 46 | } 47 | } 48 | return 49 | } 50 | -------------------------------------------------------------------------------- /shortest_palindrome/shortest_palindrome.go: -------------------------------------------------------------------------------- 1 | package shortest_palindrome 2 | 3 | func shortestPalindrome(s string) string { 4 | matrix := make([][]bool, len(s)) 5 | for i := range matrix { 6 | matrix[i] = make([]bool, len(s)) 7 | } 8 | for i := len(matrix) - 1; i >= 0; i-- { 9 | for j := i; j < len(matrix[i]); j++ { 10 | if j == i || s[i] == s[j] && (i+1 == j || matrix[i+1][j-1]) { 11 | matrix[i][j] = true 12 | } 13 | } 14 | } 15 | 16 | p := len(s) - 1 17 | for ; p >= 0; p-- { 18 | if matrix[0][p] { 19 | break 20 | } 21 | } 22 | return reverse(s[p+1:]) + s 23 | } 24 | 25 | func reverse(s string) string { 26 | bytes := make([]byte, len(s)) 27 | for i := range s { 28 | bytes[len(s)-i-1] = s[i] 29 | } 30 | return string(bytes) 31 | } 32 | -------------------------------------------------------------------------------- /shuffle_an_array/shuffle_an_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Solution(vector nums): nums(nums), current(nums) { 4 | srand(time(NULL)); 5 | } 6 | 7 | /** Resets the array to its original configuration and return it. */ 8 | vector reset() { 9 | return current = nums; 10 | } 11 | 12 | /** Returns a random shuffling of the array. */ 13 | vector shuffle() { 14 | int i = current.size(); 15 | while (--i > 0) { 16 | int j = rand() % (i+1); 17 | swap(current[i], current[j]); 18 | } 19 | return current; 20 | } 21 | private: 22 | vector nums, current; 23 | }; 24 | 25 | /** 26 | * Your Solution object will be instantiated and called as such: 27 | * Solution obj = new Solution(nums); 28 | * vector param_1 = obj.reset(); 29 | * vector param_2 = obj.shuffle(); 30 | */ -------------------------------------------------------------------------------- /single_number/single_number.go: -------------------------------------------------------------------------------- 1 | package single_number 2 | 3 | func singleNumber(nums []int) int { 4 | ret := 0 5 | for i := range nums { 6 | ret ^= nums[i] 7 | } 8 | return ret 9 | } 10 | -------------------------------------------------------------------------------- /single_number_II/single_number_II.go: -------------------------------------------------------------------------------- 1 | package single_number_II 2 | 3 | func singleNumber(nums []int) int { 4 | var one, two, three int 5 | for i := range nums { 6 | three = two & nums[i] 7 | two = ^three & (two | one&nums[i]) 8 | one = ^three & (one ^ nums[i]) 9 | } 10 | return one 11 | } 12 | -------------------------------------------------------------------------------- /single_number_III/single_number_III.go: -------------------------------------------------------------------------------- 1 | package single_number_III 2 | 3 | func singleNumber(nums []int) []int { 4 | var allox int 5 | for i := range nums { 6 | allox ^= nums[i] 7 | } 8 | mask := 1 9 | for ; mask&allox == 0; mask <<= 1 { 10 | } 11 | var ret1, ret2 int 12 | for i := range nums { 13 | if nums[i]&mask != 0 { 14 | ret1 ^= nums[i] 15 | } else { 16 | ret2 ^= nums[i] 17 | } 18 | } 19 | return []int{ret1, ret2} 20 | } 21 | -------------------------------------------------------------------------------- /sliding_window_maximum/sliding_window_maximum.go: -------------------------------------------------------------------------------- 1 | package sliding_window_maximum 2 | 3 | func maxSlidingWindow(nums []int, k int) []int { 4 | ret := []int{} 5 | idxArray := []int{} 6 | for i := range nums { 7 | for len(idxArray) != 0 && idxArray[0] <= i-k { 8 | idxArray = idxArray[1:] 9 | } 10 | j := len(idxArray) - 1 11 | for ; j >= 0 && nums[idxArray[j]] <= nums[i]; j-- { 12 | } 13 | idxArray = append(idxArray[:j+1], i) 14 | if i >= k-1 { 15 | ret = append(ret, nums[idxArray[0]]) 16 | } 17 | } 18 | return ret 19 | } 20 | -------------------------------------------------------------------------------- /sort_colors/sort_colors.go: -------------------------------------------------------------------------------- 1 | package sort_colors 2 | 3 | func sortColors(nums []int) { 4 | r, b := 0, len(nums)-1 5 | for i := 0; i <= b; i++ { 6 | if nums[i] == 0 { 7 | nums[i], nums[r] = nums[r], nums[i] 8 | r++ 9 | } else if nums[i] == 2 { 10 | nums[i], nums[b] = nums[b], nums[i] 11 | b-- 12 | i-- 13 | } 14 | } 15 | return 16 | } 17 | -------------------------------------------------------------------------------- /sort_list/sort_list.go: -------------------------------------------------------------------------------- 1 | package sort_list 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func sortList(head *ListNode) *ListNode { 9 | if head == nil || head.Next == nil { 10 | return head 11 | } 12 | secHead := split(head) 13 | return merge(sortList(head), sortList(secHead)) 14 | } 15 | 16 | func split(head *ListNode) *ListNode { 17 | if head == nil || head.Next == nil { 18 | return nil 19 | } 20 | slow, fast := head, head 21 | var tail *ListNode 22 | for fast != nil && fast.Next != nil { 23 | tail = slow 24 | slow = slow.Next 25 | fast = fast.Next.Next 26 | } 27 | tail.Next = nil 28 | return slow 29 | } 30 | 31 | func merge(left, right *ListNode) (head *ListNode) { 32 | if left == nil { 33 | return right 34 | } else if right == nil { 35 | return left 36 | } 37 | var p, cur *ListNode 38 | for left != nil && right != nil { 39 | if left.Val < right.Val { 40 | cur = left 41 | left = left.Next 42 | } else { 43 | cur = right 44 | right = right.Next 45 | } 46 | if head == nil { 47 | head = cur 48 | } else { 49 | p.Next = cur 50 | } 51 | p = cur 52 | } 53 | if left != nil { 54 | p.Next = left 55 | } else { 56 | p.Next = right 57 | } 58 | return head 59 | } 60 | -------------------------------------------------------------------------------- /spiral_matrix/spiral_matrix.go: -------------------------------------------------------------------------------- 1 | package spiral_matrix 2 | 3 | const ( 4 | up string = "up" 5 | down = "down" 6 | left = "left" 7 | right = "right" 8 | ) 9 | 10 | func spiralOrder(matrix [][]int) []int { 11 | ret := []int{} 12 | if len(matrix) == 0 { 13 | return ret 14 | } 15 | rows, cols := len(matrix), len(matrix[0]) 16 | status := right 17 | i, j := 0, -1 18 | for rows != 0 && cols != 0 { 19 | switch status { 20 | case right: 21 | cnt := cols 22 | for { 23 | if cnt == 0 { 24 | break 25 | } 26 | j, cnt = j+1, cnt-1 27 | ret = append(ret, matrix[i][j]) 28 | } 29 | rows-- 30 | status = down 31 | case down: 32 | cnt := rows 33 | for { 34 | if cnt == 0 { 35 | break 36 | } 37 | i, cnt = i+1, cnt-1 38 | ret = append(ret, matrix[i][j]) 39 | } 40 | cols-- 41 | status = left 42 | case left: 43 | cnt := cols 44 | for { 45 | if cnt == 0 { 46 | break 47 | } 48 | j, cnt = j-1, cnt-1 49 | ret = append(ret, matrix[i][j]) 50 | } 51 | rows-- 52 | status = up 53 | case up: 54 | cnt := rows 55 | for { 56 | if cnt == 0 { 57 | break 58 | } 59 | i, cnt = i-1, cnt-1 60 | ret = append(ret, matrix[i][j]) 61 | } 62 | cols-- 63 | status = right 64 | } 65 | } 66 | return ret 67 | } 68 | -------------------------------------------------------------------------------- /spiral_matrix/spiral_matrix_test.go: -------------------------------------------------------------------------------- 1 | package spiral_matrix 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestSpiralOrder(t *testing.T) { 9 | fmt.Printf("%v\n", spiralOrder([][]int{[]int{1, 2, 3}, []int{4, 5, 6}, []int{7, 8, 9}})) 10 | } 11 | -------------------------------------------------------------------------------- /spiral_matrix_II/spiral_matrix_II.go: -------------------------------------------------------------------------------- 1 | package spiral_matrix_II 2 | 3 | const ( 4 | up string = "up" 5 | down = "down" 6 | left = "left" 7 | right = "right" 8 | ) 9 | 10 | func generateMatrix(n int) [][]int { 11 | matrix := make([][]int, n) 12 | for i := range matrix { 13 | matrix[i] = make([]int, n) 14 | } 15 | 16 | if n == 0 { 17 | return matrix 18 | } 19 | rows, cols := n, n 20 | status := right 21 | i, j := 0, -1 22 | current := 1 23 | for rows != 0 && cols != 0 { 24 | switch status { 25 | case right: 26 | cnt := cols 27 | for { 28 | if cnt == 0 { 29 | break 30 | } 31 | j, cnt = j+1, cnt-1 32 | matrix[i][j] = current 33 | current++ 34 | } 35 | rows-- 36 | status = down 37 | case down: 38 | cnt := rows 39 | for { 40 | if cnt == 0 { 41 | break 42 | } 43 | i, cnt = i+1, cnt-1 44 | matrix[i][j] = current 45 | current++ 46 | } 47 | cols-- 48 | status = left 49 | case left: 50 | cnt := cols 51 | for { 52 | if cnt == 0 { 53 | break 54 | } 55 | j, cnt = j-1, cnt-1 56 | matrix[i][j] = current 57 | current++ 58 | } 59 | rows-- 60 | status = up 61 | case up: 62 | cnt := rows 63 | for { 64 | if cnt == 0 { 65 | break 66 | } 67 | i, cnt = i-1, cnt-1 68 | matrix[i][j] = current 69 | current++ 70 | } 71 | cols-- 72 | status = right 73 | } 74 | } 75 | return matrix 76 | } 77 | -------------------------------------------------------------------------------- /string_to_integer/string_to_integer.go: -------------------------------------------------------------------------------- 1 | package string_to_integer 2 | 3 | // just consider 32-bit, fucking leetcode.com's test cases 4 | const ( 5 | MAX int32 = 1<<31 - 1 6 | MIN int32 = -1*MAX - 1 7 | ) 8 | 9 | func myAtoi(str string) int { 10 | if len(str) == 0 { 11 | return 0 12 | } 13 | runes := []rune(str) 14 | var ret int32 15 | var neg bool 16 | i := 0 17 | for ; runes[i] == rune(' '); i++ { 18 | } 19 | if runes[i] == rune('-') || runes[i] == rune('+') { 20 | neg = runes[i] == rune('-') 21 | i++ 22 | } 23 | 24 | for ; i < len(runes); i++ { 25 | if val, ok := toInt(runes[i]); !ok { 26 | break 27 | } else { 28 | if neg { 29 | if -ret < (MIN+val)/10 { 30 | return int(MIN) 31 | } 32 | } else { 33 | if ret > (MAX-val)/10 { 34 | return int(MAX) 35 | } 36 | } 37 | ret = 10*ret + val 38 | } 39 | } 40 | if neg { 41 | return int(-ret) 42 | } 43 | return int(ret) 44 | } 45 | 46 | func toInt(r rune) (int32, bool) { 47 | ret := int32(r - rune('0')) 48 | if ret >= 0 && ret <= 9 { 49 | return ret, true 50 | } 51 | return 0, false 52 | } 53 | -------------------------------------------------------------------------------- /string_to_integer/string_to_integer_test.go: -------------------------------------------------------------------------------- 1 | package string_to_integer 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMyAtoi(t *testing) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /subsets/subsets.go: -------------------------------------------------------------------------------- 1 | package subsets 2 | 3 | func subsets(nums []int) [][]int { 4 | rets := [][]int{} 5 | if len(nums) == 0 { 6 | return rets 7 | } 8 | currentIndex := make([]int, len(nums)) 9 | for i := range currentIndex { 10 | currentIndex[i] = -1 11 | } 12 | solution := []int{} 13 | depth, maxDepth := -1, len(nums)-1 14 | for { 15 | finish := false 16 | L: 17 | for depth < maxDepth { 18 | for { 19 | childDepth := depth + 1 20 | preIndex := currentIndex[childDepth] 21 | if preIndex == len(nums)-1 { 22 | finish = true 23 | currentIndex[childDepth] = -1 24 | break L 25 | } 26 | currentIndex[childDepth]++ 27 | if depth == -1 || nums[currentIndex[depth]] < nums[currentIndex[childDepth]] { 28 | solution = append(solution, nums[currentIndex[childDepth]]) 29 | break 30 | } 31 | } 32 | depth++ 33 | } 34 | if finish || depth == maxDepth { 35 | cp := make([]int, len(solution)) 36 | copy(cp, solution) 37 | rets = append(rets, cp) 38 | finish = false 39 | } 40 | if depth == -1 { 41 | break 42 | } 43 | depth-- 44 | solution = solution[:len(solution)-1] 45 | } 46 | return rets 47 | } 48 | -------------------------------------------------------------------------------- /subsets_II/subsets_II.go: -------------------------------------------------------------------------------- 1 | package subsets_II 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func subsetsWithDup(nums []int) [][]int { 8 | sort.Ints(nums) 9 | solution := []int{} 10 | ret := [][]int{[]int{}} 11 | ret = append(ret, subsetsI(nums, solution, -1)...) 12 | return ret 13 | } 14 | 15 | func subsetsI(nums []int, solution []int, idx int) [][]int { 16 | ret := [][]int{} 17 | for i := idx + 1; i < len(nums); i++ { 18 | if i > idx+1 && nums[i] == nums[i-1] { 19 | continue 20 | } 21 | solution = append(solution, nums[i]) 22 | cp1 := make([]int, len(solution)) 23 | copy(cp1, solution) 24 | ret = append(ret, cp1) 25 | tmps := subsetsI(nums, solution, i) 26 | ret = append(ret, tmps...) 27 | solution = solution[:len(solution)-1] 28 | } 29 | return ret 30 | } 31 | -------------------------------------------------------------------------------- /sum_of_two_integers/sum_of_two_integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getSum(int a, int b) { 4 | int carry = 0; 5 | while (b != 0) { 6 | carry = a & b; 7 | a ^= b; 8 | b = carry << 1; 9 | } 10 | return a; 11 | } 12 | }; -------------------------------------------------------------------------------- /sum_root_to_leaf_numbers/sum_root_to_leaf_numbers.go: -------------------------------------------------------------------------------- 1 | package sum_root_to_leaf_numbers 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | type solution struct { 10 | sum int 11 | } 12 | 13 | func sumNumbers(root *TreeNode) int { 14 | s := &solution{} 15 | s.helper(root, 0) 16 | return s.sum 17 | } 18 | 19 | func (this *solution) helper(root *TreeNode, current int) { 20 | if root == nil { 21 | return 22 | } 23 | v := current*10 + root.Val 24 | if root.Left == nil && root.Right == nil { 25 | this.sum += v 26 | } 27 | this.helper(root.Left, v) 28 | this.helper(root.Right, v) 29 | return 30 | } 31 | -------------------------------------------------------------------------------- /summary_ranges/summary_ranges.go: -------------------------------------------------------------------------------- 1 | package summary_ranges 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func summaryRanges(nums []int) []string { 8 | var ret []string 9 | if len(nums) == 0 { 10 | return ret 11 | } 12 | if len(nums) == 1 { 13 | return []string{strconv.Itoa(nums[0])} 14 | } 15 | var i int 16 | var j int = 1 17 | for ; j < len(nums); j++ { 18 | if nums[j] == nums[j-1]+1 { 19 | continue 20 | } 21 | if nums[j] != nums[j-1]+1 { 22 | if j-1 == i { 23 | ret = append(ret, strconv.Itoa(nums[i])) 24 | } else { 25 | ret = append(ret, strconv.Itoa(nums[i])+"->"+strconv.Itoa(nums[j-1])) 26 | } 27 | i = j 28 | } 29 | } 30 | if j-1 == i { 31 | ret = append(ret, strconv.Itoa(nums[i])) 32 | } else { 33 | ret = append(ret, strconv.Itoa(nums[i])+"->"+strconv.Itoa(nums[j-1])) 34 | } 35 | return ret 36 | } 37 | -------------------------------------------------------------------------------- /super_ugly_number/super_ugly_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthSuperUglyNumber(int n, vector& primes) { 4 | vector dp(n, 1); 5 | vector idxs(primes.size(), 0); 6 | for (int i = 1; i < n; ++i) { 7 | dp[i] = INT_MAX; 8 | for (int idx = 0; idx < idxs.size(); ++idx) { 9 | dp[i] = min(dp[i], primes[idx]*dp[idxs[idx]]); 10 | } 11 | for (int idx = 0; idx < idxs.size(); ++idx) { 12 | if (dp[i] == primes[idx] * dp[idxs[idx]]) ++idxs[idx]; 13 | } 14 | } 15 | return dp.back(); 16 | } 17 | }; -------------------------------------------------------------------------------- /surrounded_regions/surrounded_regions.go: -------------------------------------------------------------------------------- 1 | package surrounded_regions 2 | 3 | type solution struct { 4 | visited [][]bool 5 | board [][]byte 6 | } 7 | 8 | func solve(board [][]byte) { 9 | if len(board) < 2 { 10 | return 11 | } 12 | s := &solution{ 13 | visited: make([][]bool, len(board)), 14 | board: board, 15 | } 16 | for i := range board { 17 | s.visited[i] = make([]bool, len(board[i])) 18 | } 19 | for i := range board { 20 | if board[i][0] == 'O' { 21 | s.DFS(i, 0) 22 | } 23 | if len(board[i]) > 1 && board[i][len(board[i])-1] == 'O' { 24 | s.DFS(i, len(board[i])-1) 25 | } 26 | } 27 | for j := range board[0] { 28 | if board[0][j] == 'O' { 29 | s.DFS(0, j) 30 | } 31 | } 32 | for j := range board[len(board)-1] { 33 | if board[len(board)-1][j] == 'O' { 34 | s.DFS(len(board)-1, j) 35 | } 36 | } 37 | 38 | for i := range board { 39 | for j := range board[i] { 40 | if board[i][j] == 'O' && !s.visited[i][j] { 41 | board[i][j] = 'X' 42 | } 43 | } 44 | } 45 | return 46 | } 47 | 48 | func (this *solution) DFS(i, j int) { 49 | if i < 0 || i >= len(this.board) || j < 0 || j >= len(this.board[i]) || this.board[i][j] == 'X' || this.visited[i][j] { 50 | return 51 | } 52 | this.visited[i][j] = true 53 | this.DFS(i-1, j) 54 | this.DFS(i+1, j) 55 | this.DFS(i, j-1) 56 | this.DFS(i, j+1) 57 | return 58 | } 59 | -------------------------------------------------------------------------------- /swap_nodes_in_pairs/swap_nodes_in_pairs.go: -------------------------------------------------------------------------------- 1 | package swap_nodes_in_pairs 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | func swapPairs(head *ListNode) *ListNode { 9 | if head == nil || head.Next == nil { 10 | return head 11 | } 12 | newHead := head.Next 13 | newHead.Next, head.Next = head, swapPairs(newHead.Next) 14 | return newHead 15 | } 16 | -------------------------------------------------------------------------------- /three_sum/three_sum.go: -------------------------------------------------------------------------------- 1 | package three_sum 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func threeSum(nums []int) [][]int { 8 | var ret [][]int 9 | sort.Ints(nums) 10 | for i := 0; i < len(nums)-2; i++ { 11 | if i > 0 && nums[i-1] == nums[i] { 12 | continue 13 | } 14 | j, k := i+1, len(nums)-1 15 | for j < k { 16 | if j > i+1 && nums[j] == nums[j-1] { 17 | j++ 18 | continue 19 | } 20 | if nums[i]+nums[j]+nums[k] == 0 { 21 | ret = append(ret, []int{nums[i], nums[j], nums[k]}) 22 | j++ 23 | k-- 24 | } else if nums[i]+nums[j]+nums[k] < 0 { 25 | j++ 26 | } else { 27 | k-- 28 | } 29 | } 30 | } 31 | return ret 32 | } 33 | -------------------------------------------------------------------------------- /three_sum/three_sum_test.go: -------------------------------------------------------------------------------- 1 | package three_sum 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestThreeSum(t *testing.T) { 8 | } 9 | -------------------------------------------------------------------------------- /three_sum_closest/three_sum_closest.go: -------------------------------------------------------------------------------- 1 | package three_sum_closest 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func threeSumClosest(nums []int, target int) int { 8 | var diff int 9 | sort.Ints(nums) 10 | for i := 0; i < len(nums)-2; i++ { 11 | if i == 0 { 12 | diff = nums[0] + nums[1] + nums[len(nums)-1] - target 13 | } else if i > 0 && nums[i] == nums[i-1] { 14 | continue 15 | } 16 | j, k := i+1, len(nums)-1 17 | for j < k { 18 | if j > i+1 && nums[j] == nums[j-1] { 19 | j++ 20 | continue 21 | } 22 | tmp := nums[i] + nums[j] + nums[k] - target 23 | if tmp == 0 { 24 | return target 25 | } else { 26 | if tmp < 0 { 27 | j++ 28 | } else { 29 | k-- 30 | } 31 | if abs(tmp) < abs(diff) { 32 | diff = tmp 33 | } 34 | } 35 | } 36 | } 37 | return diff + target 38 | } 39 | 40 | func abs(i int) int { 41 | if i >= 0 { 42 | return i 43 | } 44 | return -i 45 | } 46 | -------------------------------------------------------------------------------- /three_sum_closest/three_sum_closest_test.go: -------------------------------------------------------------------------------- 1 | package three_sum_closest 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestThreeSumClosest(t *testing.T) { 8 | } 9 | -------------------------------------------------------------------------------- /top_k_frequent_elements/top_k_frequent_elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | unordered_map mapping; 5 | for (auto num: nums) { 6 | ++mapping[num]; 7 | } 8 | vector> freq(nums.size()+1); 9 | for (auto m: mapping) { 10 | freq[m.second].push_back(m.first); 11 | } 12 | vector result; 13 | for (int i = freq.size()-1; i >=0 && k > 0; --i) { 14 | for (auto num: freq[i]) { 15 | result.push_back(num); 16 | --k; 17 | if (k == 0) break; 18 | } 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /trapping_rain_water/trapping_rain_water.go: -------------------------------------------------------------------------------- 1 | package trapping_rain_water 2 | 3 | func trap(height []int) int { 4 | left, right, secHeight, area := 0, len(height)-1, 0, 0 5 | for left < right { 6 | if height[left] < height[right] { 7 | secHeight = max(secHeight, height[left]) 8 | area += secHeight - height[left] 9 | left++ 10 | } else { 11 | secHeight = max(secHeight, height[right]) 12 | area += secHeight - height[right] 13 | right-- 14 | } 15 | } 16 | return area 17 | } 18 | 19 | func max(i, j int) int { 20 | if i > j { 21 | return i 22 | } 23 | return j 24 | } 25 | -------------------------------------------------------------------------------- /triangle/triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minimumTotal(vector>& triangle) { 5 | int length = triangle.size(); 6 | if (length == 0) return 0; 7 | if (length == 1) return triangle[0][0]; 8 | vector dp(length); 9 | dp[0] = triangle[0][0]; 10 | int min; 11 | bool first = true; 12 | for (int i = 1; i < length; ++i){ 13 | for (int j = i; j >= 0; --j){ 14 | if (j != 0 && (dp[j-1] < dp[j] || j == i)){ 15 | dp[j] = dp[j-1]; 16 | } 17 | dp[j] += triangle[i][j]; 18 | if (i == length-1 && (first || dp[j] < min)){ 19 | first = false; 20 | min = dp[j]; 21 | } 22 | } 23 | } 24 | return min; 25 | } 26 | -------------------------------------------------------------------------------- /two_sum/two_sum.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | func twoSum(nums []int, target int) []int { 4 | m := make(map[int]int) 5 | for i := 0; i < len(nums); i++ { 6 | another := target - nums[i] 7 | if _, ok := m[another]; ok { 8 | return []int{m[another], i} 9 | } 10 | m[nums[i]] = i 11 | } 12 | return nil 13 | } 14 | -------------------------------------------------------------------------------- /two_sum/two_sum_test.go: -------------------------------------------------------------------------------- 1 | package two_sum 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestTwoSum(t *testing.T) { 8 | tests := [][]int{ 9 | []int{3, 2, 4}, 10 | []int{0, 8, 7, 3, 3, 4, 2}, 11 | []int{0, 1}, 12 | } 13 | targets := []int{ 14 | 6, 15 | 11, 16 | 1, 17 | } 18 | results := [][]int{ 19 | []int{1, 2}, 20 | []int{1, 3}, 21 | []int{0, 1}, 22 | } 23 | caseNum := 3 24 | for i := 0; i < caseNum; i++ { 25 | if ret := twoSum(tests[i], targets[i]); ret[0] != results[i][0] && ret[1] != results[i][1] { 26 | t.Fatalf("case %d fails: %v\n", i, ret) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /two_sum_II/two_sum_II.go: -------------------------------------------------------------------------------- 1 | package two_sum_II 2 | 3 | func twoSum(numbers []int, target int) []int { 4 | i, j := 0, len(numbers)-1 5 | var sum int 6 | for i < j { 7 | sum = numbers[i] + numbers[j] 8 | if sum == target { 9 | return []int{i + 1, j + 1} 10 | } 11 | if sum < target { 12 | i++ 13 | } else { 14 | j-- 15 | } 16 | } 17 | return []int{} 18 | } 19 | -------------------------------------------------------------------------------- /ugly_number/ugly_number.go: -------------------------------------------------------------------------------- 1 | package ugly_number 2 | 3 | func isUgly(num int) bool { 4 | if num == 0 { 5 | return false 6 | } 7 | for ; num%2 == 0; num /= 2 { 8 | } 9 | for ; num%3 == 0; num /= 3 { 10 | } 11 | for ; num%5 == 0; num /= 5 { 12 | } 13 | if num == 1 { 14 | return true 15 | } 16 | return false 17 | } 18 | -------------------------------------------------------------------------------- /ugly_number_II/ugly_number_II.go: -------------------------------------------------------------------------------- 1 | package ugly_number_II 2 | 3 | func nthUglyNumber(n int) int { 4 | if n == 1 { 5 | return 1 6 | } 7 | records := []int{1} 8 | i, j, k := 0, 0, 0 9 | for len(records) < n { 10 | next := min(2*records[i], min(3*records[j], 5*records[k])) 11 | if next == 2*records[i] { 12 | i++ 13 | } 14 | if next == 3*records[j] { 15 | j++ 16 | } 17 | if next == 5*records[k] { 18 | k++ 19 | } 20 | records = append(records, next) 21 | } 22 | return records[len(records)-1] 23 | } 24 | 25 | func min(i, j int) int { 26 | if i < j { 27 | return i 28 | } 29 | return j 30 | } 31 | -------------------------------------------------------------------------------- /unique_binary_search_trees/unique_binary_search_trees.go: -------------------------------------------------------------------------------- 1 | package unique_binary_search_trees 2 | 3 | func numTrees(n int) int { 4 | if n <= 1 { 5 | return n 6 | } 7 | array := make([]int, n+1) 8 | array[0], array[1] = 1, 1 9 | for i := 2; i <= n; i++ { 10 | for j := 0; j < i; j++ { 11 | array[i] += array[j] * array[i-j-1] 12 | } 13 | } 14 | return array[n] 15 | } 16 | -------------------------------------------------------------------------------- /unique_binary_search_trees_II/unique_binary_search_trees_II.go: -------------------------------------------------------------------------------- 1 | package unique_binary_search_trees_II 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func generateTrees(n int) []*TreeNode { 10 | if n == 0 { 11 | return []*TreeNode{} 12 | } 13 | return generateTreesI(1, n) 14 | } 15 | 16 | func generateTreesI(left, right int) (ret []*TreeNode) { 17 | if left > right { 18 | return []*TreeNode{nil} 19 | } 20 | if left == right { 21 | return []*TreeNode{&TreeNode{Val: left}} 22 | } 23 | for num := left; num <= right; num++ { 24 | leftTrees := generateTreesI(left, num-1) 25 | rightTrees := generateTreesI(num+1, right) 26 | for i := range leftTrees { 27 | for j := range rightTrees { 28 | root := &TreeNode{Val: num} 29 | root.Left = leftTrees[i] 30 | root.Right = rightTrees[j] 31 | ret = append(ret, root) 32 | } 33 | } 34 | } 35 | return 36 | } 37 | -------------------------------------------------------------------------------- /unique_paths/unique_paths.go: -------------------------------------------------------------------------------- 1 | package unique_paths 2 | 3 | func uniquePaths(m int, n int) int { 4 | matrix := make([][]int, m) 5 | for i := range matrix { 6 | matrix[i] = make([]int, n) 7 | } 8 | for i := 0; i < m; i++ { 9 | for j := 0; j < n; j++ { 10 | if i == 0 || j == 0 { 11 | matrix[i][j] = 1 12 | } else { 13 | matrix[i][j] = matrix[i-1][j] + matrix[i][j-1] 14 | } 15 | } 16 | } 17 | return matrix[m-1][n-1] 18 | } 19 | -------------------------------------------------------------------------------- /unique_paths_II/unique_paths_II.go: -------------------------------------------------------------------------------- 1 | package unique_paths_II 2 | 3 | func uniquePathsWithObstacles(obstacleGrid [][]int) int { 4 | if len(obstacleGrid) == 0 { 5 | return 0 6 | } 7 | m, n := len(obstacleGrid)-1, len(obstacleGrid[0])-1 8 | if obstacleGrid[m][n] == 1 { 9 | return 0 10 | } 11 | matrix := make([][]int, m+1) 12 | for i := range matrix { 13 | matrix[i] = make([]int, n+1) 14 | } 15 | for i := 0; i <= m; i++ { 16 | for j := 0; j <= n; j++ { 17 | if obstacleGrid[i][j] == 1 { 18 | continue 19 | } 20 | if i == 0 && j == 0 { 21 | matrix[i][j] = 1 - obstacleGrid[0][0] 22 | } else if i == 0 { 23 | matrix[i][j] = matrix[i][j-1] 24 | } else if j == 0 { 25 | matrix[i][j] = matrix[i-1][j] 26 | } else { 27 | matrix[i][j] = matrix[i-1][j] + matrix[i][j-1] 28 | } 29 | } 30 | } 31 | return matrix[m][n] 32 | } 33 | -------------------------------------------------------------------------------- /valid_anagram/valid_anagram.go: -------------------------------------------------------------------------------- 1 | package valid_anagram 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func isAnagram(s string, t string) bool { 8 | if len(s) != len(t) { 9 | return false 10 | } 11 | m := [26]int{} 12 | for i := range s { 13 | m[int(s[i]-'a')]++ 14 | m[int(t[i]-'a')]-- 15 | } 16 | for i := range m { 17 | if m[i] != 0 { 18 | return false 19 | } 20 | } 21 | return true 22 | } 23 | -------------------------------------------------------------------------------- /valid_number/valid_number.go: -------------------------------------------------------------------------------- 1 | package valid_number 2 | 3 | func isNumber(s string) bool { 4 | bytes := []byte(s) 5 | point, hasE := false, false 6 | i, n := 0, len(bytes) 7 | for ; i < n; i++ { 8 | if bytes[i] != ' ' { 9 | break 10 | } 11 | } 12 | if i == n { 13 | return false 14 | } 15 | if bytes[i] == '+' || bytes[i] == '-' { 16 | i++ 17 | } 18 | if i == n { 19 | return false 20 | } 21 | head := i 22 | for ; i < n; i++ { 23 | switch bytes[i] { 24 | case '.': 25 | if point || hasE || i == head && (i == n-1 || !isDigit(bytes[i+1])) { 26 | return false 27 | } 28 | point = true 29 | continue 30 | case 'e': 31 | if hasE || i == head || i == n-1 { 32 | return false 33 | } 34 | i++ 35 | if bytes[i] == '-' || bytes[i] == '+' { 36 | i++ 37 | } 38 | if i == n || !isDigit(bytes[i]) { 39 | return false 40 | } 41 | hasE = true 42 | continue 43 | } 44 | if bytes[i] == ' ' { 45 | for ; i < n; i++ { 46 | if bytes[i] != ' ' { 47 | return false 48 | } 49 | } 50 | return true 51 | } 52 | if !isDigit(bytes[i]) { 53 | return false 54 | } 55 | } 56 | return true 57 | } 58 | 59 | func isDigit(b byte) bool { 60 | if b >= '0' && b <= '9' { 61 | return true 62 | } 63 | return false 64 | } 65 | -------------------------------------------------------------------------------- /valid_number/valid_number_test.go: -------------------------------------------------------------------------------- 1 | package valid_number 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsNumber(t *testing.T) { 8 | println(isNumber("4e+")) 9 | } 10 | -------------------------------------------------------------------------------- /valid_palindrome/valid_palindrome.go: -------------------------------------------------------------------------------- 1 | package valid_palindrome 2 | 3 | func isPalindrome(s string) bool { 4 | bytes := []byte(s) 5 | i, j := 0, len(bytes)-1 6 | L: 7 | for i < j { 8 | for { 9 | if i >= j { 10 | break L 11 | } 12 | if !isAlpha(bytes[i]) { 13 | i++ 14 | } else { 15 | break 16 | } 17 | } 18 | for { 19 | if i >= j { 20 | break L 21 | } 22 | if !isAlpha(bytes[j]) { 23 | j-- 24 | } else { 25 | break 26 | } 27 | } 28 | if toLower(bytes[i]) != toLower(bytes[j]) { 29 | return false 30 | } 31 | i++ 32 | j-- 33 | } 34 | return true 35 | } 36 | 37 | func toLower(b byte) byte { 38 | if b >= 'A' && b <= 'Z' { 39 | return 'a' + b - 'A' 40 | } 41 | return b 42 | } 43 | 44 | func isAlpha(b byte) bool { 45 | if 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' || '0' <= b && b <= '9' { 46 | return true 47 | } 48 | return false 49 | } 50 | -------------------------------------------------------------------------------- /valid_parentheses/valid_parentheses.go: -------------------------------------------------------------------------------- 1 | package valid_parentheses 2 | 3 | func isValid(s string) bool { 4 | m := map[rune]rune{ 5 | '(': ')', 6 | '[': ']', 7 | '{': '}', 8 | } 9 | stack := make([]rune, len(s)) 10 | top := 0 11 | for _, c := range s { 12 | switch c { 13 | case '(', '[', '{': 14 | stack[top] = m[c] 15 | top++ 16 | case ')', ']', '}': 17 | if top > 0 && stack[top-1] == c { 18 | top-- 19 | } else { 20 | return false 21 | } 22 | } 23 | } 24 | 25 | return top == 0 26 | } 27 | -------------------------------------------------------------------------------- /valid_parentheses/valid_parentheses_test.go: -------------------------------------------------------------------------------- 1 | package valid_parentheses 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsValid(t *testing.T) { 8 | } 9 | -------------------------------------------------------------------------------- /valid_perfect_square/valid_perfect_square.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPerfectSquare(int num) { 4 | long i = 1, j = num; 5 | while (i <= j) { 6 | long mid = i + (j-i)/2; 7 | if (mid*mid == num) return true; 8 | if (mid*mid < num) { 9 | i = mid + 1; 10 | }else { 11 | j = mid - 1; 12 | } 13 | } 14 | return false; 15 | } 16 | }; -------------------------------------------------------------------------------- /valid_sudoku/valid_sudoku.go: -------------------------------------------------------------------------------- 1 | package valid_sudoku 2 | 3 | func isValidSudoku(board [][]byte) bool { 4 | rowMask, colMask, areaMask := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} 5 | for r := range board { 6 | for c := range board[r] { 7 | if board[r][c] == '.' { 8 | continue 9 | } 10 | digit := board[r][c] - '0' - 1 11 | area := 3*(r/3) + c/3 12 | if rowMask[r][digit] || colMask[c][digit] || areaMask[area][digit] { 13 | return false 14 | } 15 | rowMask[r][digit] = true 16 | colMask[c][digit] = true 17 | areaMask[area][digit] = true 18 | } 19 | } 20 | return true 21 | } 22 | -------------------------------------------------------------------------------- /valid_sudoku/valid_sudoku_test.go: -------------------------------------------------------------------------------- 1 | package valid_sudoku 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsValidSudoku(t *testing.T) { 8 | println(isValidSudoku( 9 | [][]byte{[]byte(".87654321"), 10 | []byte("2........"), 11 | []byte("3........"), 12 | []byte("4........"), 13 | []byte("5........"), 14 | []byte("6........"), 15 | []byte("7........"), 16 | []byte("8........"), 17 | []byte("9........")})) 18 | } 19 | -------------------------------------------------------------------------------- /validate_binary_search_tree/validate_binary_search_tree.go: -------------------------------------------------------------------------------- 1 | package validate_binary_search_tree 2 | 3 | type TreeNode struct { 4 | Val int 5 | Left *TreeNode 6 | Right *TreeNode 7 | } 8 | 9 | func isValidBST(root *TreeNode) bool { 10 | p := root 11 | stack := []*TreeNode{} 12 | sortedValues := []int{} 13 | for p != nil || len(stack) != 0 { 14 | for p != nil { 15 | stack = append(stack, p) 16 | p = p.Left 17 | } 18 | if len(stack) != 0 { 19 | p = stack[len(stack)-1] 20 | stack = stack[:len(stack)-1] 21 | if len(sortedValues) != 0 && p.Val <= sortedValues[len(sortedValues)-1] { 22 | return false 23 | } 24 | sortedValues = append(sortedValues, p.Val) 25 | p = p.Right 26 | } 27 | } 28 | return true 29 | } 30 | -------------------------------------------------------------------------------- /verify_preorder_serialization_of_a_binary_tree/verify_preorder_serialization_of_a_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSerialization(string preorder) { 4 | int idx = 0; 5 | return helper(preorder, idx) ? idx == preorder.size() ? true : false : false; 6 | } 7 | 8 | bool helper(string& preorder, int& idx) { 9 | if (idx == preorder.size()) return false; 10 | int start = idx; 11 | while (idx < preorder.size() && preorder[idx] != ',') ++idx; 12 | if (idx == preorder.size()) { 13 | return preorder.substr(start) == "#" ? true : false; 14 | } 15 | ++idx; 16 | if (preorder.substr(start, idx-start-1) == "#") 17 | return true; 18 | if (!helper(preorder, idx)) return false; 19 | return helper(preorder, idx); 20 | } 21 | }; -------------------------------------------------------------------------------- /wiggle_subsequence/wiggle_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int wiggleMaxLength(vector& nums) { 4 | if (nums.size() < 2) return nums.size(); 5 | int inc_length = 1, dec_length = 1; 6 | int pre_inc_v = nums[0], pre_dec_v = nums[0]; 7 | for (int i = 1; i < nums.size(); ++i) { 8 | if (nums[i] < pre_inc_v && dec_length <= inc_length) { 9 | dec_length = inc_length + 1; 10 | pre_dec_v = nums[i]; 11 | } 12 | if (nums[i] > pre_dec_v && inc_length <= dec_length) { 13 | inc_length = dec_length + 1; 14 | pre_inc_v = nums[i]; 15 | } 16 | if (nums[i] > pre_inc_v) pre_inc_v = nums[i]; 17 | if (nums[i] < pre_dec_v) pre_dec_v = nums[i]; 18 | } 19 | return max(inc_length, dec_length); 20 | } 21 | }; -------------------------------------------------------------------------------- /word_break/word_break.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool wordBreak(string s, unordered_set& wordDict) { 9 | vector history(s.size(), false); 10 | for (int i = 0; i < s.size(); ++i){ 11 | bool yes = false; 12 | for (int j = i; j >=0 && !yes; --j){ 13 | if (wordDict.find(s.substr(j, i-j+1))!=wordDict.end() && (j == 0 || history[j-1])) 14 | yes = true; 15 | } 16 | history[i] = yes; 17 | } 18 | return history[s.size()-1]; 19 | } 20 | }; -------------------------------------------------------------------------------- /word_break_II/word_break_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector wordBreak(string s, unordered_set& wordDict) { 9 | vector history(s.size()+1, true); 10 | vector results; 11 | vector path; 12 | DFS(s, 0, results, path, history, wordDict); 13 | return results; 14 | } 15 | 16 | void DFS(string s, int start, vector& results, vector& path, vector& history, unordered_set& wordDict){ 17 | if (start==s.size()){ 18 | if (path.empty()) return; 19 | string ret = path[0]; 20 | for (int i = 1; i < path.size(); ++i) 21 | ret = ret + " " + path[i]; 22 | results.push_back(ret); 23 | return; 24 | } 25 | int pre_num = results.size(); 26 | for (int end = start+1; end <= s.size(); ++end){ 27 | if (!history[end] || wordDict.find(s.substr(start, end-start))==wordDict.end()) continue; 28 | path.push_back(s.substr(start, end-start)); 29 | DFS(s, end, results, path, history, wordDict); 30 | path.pop_back(); 31 | } 32 | if (results.size()==pre_num) history[start] = false; 33 | return; 34 | } 35 | }; -------------------------------------------------------------------------------- /word_ladder/word_ladder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int ladderLength(string beginWord, string endWord, unordered_set& wordList) { 8 | if (beginWord == endWord) 9 | return 1; 10 | if (distance(beginWord, endWord)==1) 11 | return 2; 12 | map dist; 13 | dist[beginWord] = 1; 14 | queue q; 15 | q.push(beginWord); 16 | while (!q.empty()){ 17 | string word = q.front(); 18 | q.pop(); 19 | if (word == endWord) return dist[word]; 20 | if (wordList.size() < 26*word.size()){ 21 | for (auto& w: wordList){ 22 | if (dist.find(w)==dist.end() && distance(word, w)==1){ 23 | dist[w] = dist[word] + 1; 24 | q.push(w); 25 | } 26 | } 27 | }else{ 28 | for (int i = 0; i < word.size(); ++i){ 29 | string temp = word; 30 | for (int j = 'a'; j <= 'z'; ++j){ 31 | temp[i] = j; 32 | if (wordList.find(temp)!=wordList.end() && dist.find(temp)==dist.end()){ 33 | dist[temp] = dist[word] + 1; 34 | q.push(temp); 35 | } 36 | } 37 | } 38 | } 39 | } 40 | return 0; 41 | } 42 | 43 | int distance(string dist, string src){ 44 | int count = 0; 45 | for (int i = 0; i < dist.size(); ++i){ 46 | if (dist[i]!=src[i]) ++count; 47 | } 48 | return count; 49 | } -------------------------------------------------------------------------------- /word_pattern/word_pattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool wordPattern(string pattern, string str) { 9 | unordered_map pattern_to_str; 10 | unordered_map str_to_pattern; 11 | int i = 0; 12 | int start = 0; 13 | for (int j = 0; j <= str.size(); ++j){ 14 | if (i >= pattern.size()) return false; 15 | if (j == str.size() || str[j] == ' ') { 16 | string sub = str.substr(start, j-start); 17 | if (pattern_to_str.count(pattern[i]) == 0 && str_to_pattern.count(sub) == 0) { 18 | pattern_to_str[pattern[i]] = sub; 19 | str_to_pattern[sub] = pattern[i]; 20 | }else if (pattern_to_str.count(pattern[i]) != 0 && str_to_pattern.count(sub) != 0) { 21 | if (pattern_to_str[pattern[i]] != sub || str_to_pattern[sub] != pattern[i]) { 22 | return false; 23 | } 24 | }else { 25 | return false; 26 | } 27 | ++i; 28 | start = j+1; 29 | } 30 | } 31 | if (i != pattern.size()) return false; 32 | return true; 33 | } 34 | }; -------------------------------------------------------------------------------- /word_search/word_search.go: -------------------------------------------------------------------------------- 1 | package word_search 2 | 3 | func exist(board [][]byte, word string) bool { 4 | words := []byte(word) 5 | if len(words) == 0 || len(board) == 0 || len(board[0]) == 0 { 6 | return true 7 | } 8 | 9 | mask := make([][]bool, len(board)) 10 | for i := 0; i < len(board); i++ { 11 | mask[i] = make([]int, len(board[i])) 12 | } 13 | 14 | for i := 0; i < len(board); i++ { 15 | for j := 0; j < len(board[i]); j++ { 16 | 17 | } 18 | } 19 | return false 20 | } 21 | 22 | func getExist(board [][]byte, words []byte, index int, row int, col int, mask [][]int) { 23 | 24 | } 25 | -------------------------------------------------------------------------------- /word_search/word_search_test.go: -------------------------------------------------------------------------------- 1 | package word_search 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestExist(t *testing.T) { 8 | board := [][]byte{ 9 | []byte("abce"), 10 | []byte("sfcs"), 11 | []byte("adee"), 12 | } 13 | println(exist(board, "abceseeefs")) 14 | } 15 | -------------------------------------------------------------------------------- /zigzag_conversion/zigzag_conversion.go: -------------------------------------------------------------------------------- 1 | package zigzag_conversion 2 | 3 | const ( 4 | up string = "up" 5 | down = "down" 6 | ) 7 | 8 | func convert(s string, numRows int) string { 9 | if numRows == 1 { 10 | return s 11 | } 12 | runes := []rune(s) 13 | rows := make([][]rune, numRows) 14 | i := 0 15 | status := down 16 | for index := range runes { 17 | rows[i] = append(rows[i], runes[index]) 18 | if status == down { 19 | i++ 20 | if i == numRows-1 { 21 | status = up 22 | } 23 | } else { 24 | i-- 25 | if i == 0 { 26 | status = down 27 | } 28 | } 29 | } 30 | retRunes := []rune{} 31 | for index := range rows { 32 | retRunes = append(retRunes, rows[index]...) 33 | } 34 | return string(retRunes) 35 | } 36 | -------------------------------------------------------------------------------- /zigzag_conversion/zigzag_conversion_test.go: -------------------------------------------------------------------------------- 1 | package zigzag_conversion 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestConvert(t *testing.T) { 8 | tests := []string{ 9 | "A", 10 | "ABCDE", 11 | "PAYPALISHIRING", 12 | } 13 | rows := []int{ 14 | 1, 15 | 3, 16 | 3, 17 | } 18 | results := []string{ 19 | "A", 20 | "AEBDC", 21 | "PAHNAPLSIIGYIR", 22 | } 23 | caseNum := 3 24 | for i := 0; i < caseNum; i++ { 25 | if ret := convert(tests[i], rows[i]); ret != results[i] { 26 | t.Fatalf("case %d failed\nactual: %s, expect: %s\n", i, ret, results[i]) 27 | } 28 | } 29 | } 30 | --------------------------------------------------------------------------------