From 531e56230861f898bc77f7db8eee25488b2f6d3c Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 03:56:00 +0200 Subject: [PATCH 01/12] Renamed packages --- src/Algorithms/Calculator.php | 59 -------- .../Solution.php} | 40 +++--- src/Algorithms/s0001_two_sum/readme.md | 38 +++++ .../Solution.php} | 68 ++++----- .../s0002_add_two_numbers/readme.md | 35 +++++ .../Solution.php} | 38 ++--- .../readme.md | 40 ++++++ .../Solution.php} | 72 +++++----- .../readme.md | 50 +++++++ .../Solution.php} | 54 +++---- .../readme.md | 34 +++++ .../Solution.php} | 46 +++--- .../s0006_zigzag_conversion/readme.md | 39 ++++++ .../Solution.php} | 30 ++-- .../s0007_reverse_integer/readme.md | 35 +++++ .../Solution.php} | 50 +++---- .../s0008_string_to_integer_atoi/readme.md | 113 +++++++++++++++ .../Solution.php} | 30 ++-- .../s0009_palindrome_number/readme.md | 41 ++++++ .../Solution.php} | 50 +++---- .../readme.md | 56 ++++++++ .../Solution.php} | 34 ++--- .../s0011_container_with_most_water/readme.md | 41 ++++++ .../Solution.php} | 50 +++---- .../s0012_integer_to_roman/readme.md | 62 ++++++++ .../Solution.php} | 70 +++++----- .../s0013_roman_to_integer/readme.md | 64 +++++++++ .../Solution.php} | 78 +++++------ .../s0014_longest_common_prefix/readme.md | 27 ++++ .../3sum.php => s0015_3sum/Solution.php} | 78 +++++------ src/Algorithms/s0015_3sum/readme.md | 30 ++++ .../Solution.php} | 68 ++++----- src/Algorithms/s0016_3sum_closest/readme.md | 29 ++++ .../Solution.php} | 90 ++++++------ .../readme.md | 32 +++++ .../4sum.php => s0018_4sum/Solution.php} | 108 +++++++------- src/Algorithms/s0018_4sum/readme.md | 29 ++++ .../Solution.php} | 92 ++++++------ .../readme.md | 34 +++++ .../Solution.php} | 72 +++++----- .../s0020_valid_parentheses/readme.md | 45 ++++++ .../Solution.php} | 80 +++++------ .../s0021_merge_two_sorted_lists/readme.md | 31 ++++ .../Solution.php} | 54 +++---- .../s0022_generate_parentheses/readme.md | 21 +++ .../Solution.php} | 94 ++++++------- .../s0023_merge_k_sorted_lists/readme.md | 36 +++++ .../Solution.php} | 54 +++---- .../s0024_swap_nodes_in_pairs/readme.md | 30 ++++ .../Solution.php} | 98 ++++++------- .../s0025_reverse_nodes_in_k_group/readme.md | 46 ++++++ .../Solution.php} | 52 +++---- .../readme.md | 49 +++++++ .../Solution.php} | 38 ++--- src/Algorithms/s0027_remove_element/readme.md | 52 +++++++ .../Solution.php} | 48 +++---- .../readme.md | 36 +++++ .../Solution.php} | 56 ++++---- .../s0029_divide_two_integers/readme.md | 44 ++++++ .../Solution.php} | 68 ++++----- .../readme.md | 35 +++++ .../Solution.php} | 54 +++---- .../s0031_next_permutation/readme.md | 38 +++++ .../Solution.php} | 58 ++++---- .../s0032_longest_valid_parentheses/readme.md | 32 +++++ .../Solution.php} | 62 ++++---- .../readme.md | 37 +++++ .../Solution.php} | 72 +++++----- .../readme.md | 34 +++++ .../Solution.php} | 32 ++--- .../s0035_search_insert_position/readme.md | 44 ++++++ .../Solution.php} | 84 +++++------ src/Algorithms/s0036_valid_sudoku/readme.md | 58 ++++++++ .../Solution.php} | 120 ++++++++-------- src/Algorithms/s0037_sudoku_solver/readme.md | 52 +++++++ .../Solution.php} | 60 ++++---- src/Algorithms/s0038_count_and_say/readme.md | 41 ++++++ .../Solution.php} | 70 +++++----- .../s0039_combination_sum/readme.md | 52 +++++++ .../Solution.php} | 56 ++++---- .../s0040_combination_sum_ii/readme.md | 39 ++++++ .../Solution.php} | 42 +++--- .../s0041_first_missing_positive/readme.md | 30 ++++ .../Solution.php} | 0 .../s0042_trapping_rain_water/readme.md | 27 ++++ .../Solution.php} | 0 .../s0043_multiply_strings/readme.md | 25 ++++ .../Solution.php} | 0 .../s0044_wildcard_matching/readme.md | 54 +++++++ .../Solution.php} | 0 src/Algorithms/s0045_jump_game_ii/readme.md | 30 ++++ .../Solution.php} | 0 src/Algorithms/s0046_permutations/readme.md | 29 ++++ .../Solution.php} | 0 .../s0047_permutations_ii/readme.md | 22 +++ .../Solution.php} | 0 src/Algorithms/s0048_rotate_image/readme.md | 42 ++++++ .../Solution.php} | 0 src/Algorithms/s0049_group_anagrams/readme.md | 31 ++++ .../powx-n.php => s0050_powx_n/Solution.php} | 0 src/Algorithms/s0050_powx_n/readme.md | 31 ++++ .../Solution.php} | 70 +++++----- src/Algorithms/s0051_n_queens/readme.md | 29 ++++ .../Solution.php} | 66 ++++----- src/Algorithms/s0052_n_queens_ii/readme.md | 27 ++++ .../Solution.php} | 34 ++--- .../s0053_maximum_subarray/readme.md | 34 +++++ .../Solution.php} | 98 ++++++------- src/Algorithms/s0054_spiral_matrix/readme.md | 28 ++++ .../Solution.php} | 44 +++--- src/Algorithms/s0055_jump_game/readme.md | 28 ++++ .../Solution.php} | 88 ++++++------ .../s0056_merge_intervals/readme.md | 27 ++++ .../Solution.php} | 88 ++++++------ .../s0057_insert_interval/readme.md | 50 +++++++ .../Solution.php} | 40 +++--- .../s0058_length_of_last_word/readme.md | 37 +++++ .../Solution.php} | 38 ++--- .../s0059_spiral_matrix_ii/readme.md | 23 +++ .../Solution.php} | 50 +++---- .../s0060_permutation_sequence/readme.md | 39 ++++++ .../Solution.php} | 114 +++++++-------- src/Algorithms/s0061_rotate_list/readme.md | 27 ++++ .../Solution.php} | 44 +++--- src/Algorithms/s0062_unique_paths/readme.md | 47 +++++++ .../Solution.php} | 64 ++++----- .../s0063_unique_paths_ii/readme.md | 36 +++++ .../Solution.php} | 42 +++--- .../s0064_minimum_path_sum/readme.md | 30 ++++ .../Solution.php} | 116 +++++++-------- src/Algorithms/s0065_valid_number/readme.md | 54 +++++++ .../Solution.php} | 46 +++--- src/Algorithms/s0066_plus_one/readme.md | 45 ++++++ .../Solution.php} | 46 +++--- src/Algorithms/s0067_add_binary/readme.md | 23 +++ .../Solution.php} | 84 +++++------ .../s0068_text_justification/readme.md | 45 ++++++ .../sqrtx.php => s0069_sqrtx/Solution.php} | 50 +++---- src/Algorithms/s0069_sqrtx/readme.md | 27 ++++ .../Solution.php} | 44 +++--- .../s0070_climbing_stairs/readme.md | 27 ++++ .../Solution.php} | 38 ++--- src/Algorithms/s0071_simplify_path/readme.md | 52 +++++++ .../Solution.php} | 54 +++---- src/Algorithms/s0072_edit_distance/readme.md | 32 +++++ .../Solution.php} | 68 ++++----- .../s0073_set_matrix_zeroes/readme.md | 36 +++++ .../Solution.php} | 38 ++--- .../s0074_search_a_2d_matrix/readme.md | 31 ++++ .../Solution.php} | 60 ++++---- src/Algorithms/s0075_sort_colors/readme.md | 41 ++++++ .../Solution.php} | 86 ++++++------ .../s0076_minimum_window_substring/readme.md | 42 ++++++ .../Solution.php} | 48 +++---- src/Algorithms/s0077_combinations/readme.md | 24 ++++ .../Solution.php} | 50 +++---- src/Algorithms/s0078_subsets/readme.md | 25 ++++ .../Solution.php} | 62 ++++---- src/Algorithms/s0079_word_search/readme.md | 41 ++++++ .../Solution.php} | 52 +++---- .../readme.md | 49 +++++++ .../Solution.php} | 34 ++--- .../readme.md | 32 +++++ .../Solution.php} | 76 +++++----- .../readme.md | 27 ++++ .../Solution.php} | 60 ++++---- .../readme.md | 27 ++++ .../Solution.php} | 30 ++-- .../readme.md | 28 ++++ .../Solution.php} | 102 +++++++------- .../s0085_maximal_rectangle/readme.md | 46 ++++++ .../Solution.php} | 90 ++++++------ src/Algorithms/s0086_partition_list/readme.md | 27 ++++ .../Solution.php} | 72 +++++----- .../s0087_scramble_string/readme.md | 39 ++++++ .../Solution.php} | 56 ++++---- .../s0088_merge_sorted_array/readme.md | 43 ++++++ .../Solution.php} | 52 +++---- src/Algorithms/s0089_gray_code/readme.md | 31 ++++ .../Solution.php} | 62 ++++---- src/Algorithms/s0090_subsets_ii/readme.md | 24 ++++ .../Solution.php} | 60 ++++---- src/Algorithms/s0091_decode_ways/readme.md | 55 ++++++++ .../Solution.php} | 90 ++++++------ .../s0092_reverse_linked_list_ii/readme.md | 28 ++++ .../Solution.php} | 104 +++++++------- .../s0093_restore_ip_addresses/readme.md | 44 ++++++ .../Solution.php} | 54 +++---- .../readme.md | 48 +++++++ .../Solution.php} | 104 +++++++------- .../readme.md | 23 +++ .../Solution.php} | 38 ++--- .../readme.md | 23 +++ .../Solution.php} | 62 ++++---- .../s0097_interleaving_string/readme.md | 42 ++++++ .../Solution.php} | 50 +++---- .../readme.md | 34 +++++ .../Solution.php} | 68 ++++----- .../readme.md | 32 +++++ .../Solution.php} | 52 +++---- src/Algorithms/s0100_same_tree/readme.md | 36 +++++ .../Solution.php} | 64 ++++----- src/Algorithms/s0101_symmetric_tree/readme.md | 28 ++++ .../Solution.php} | 72 +++++----- .../readme.md | 30 ++++ .../Solution.php} | 80 +++++------ .../readme.md | 30 ++++ .../Solution.php} | 40 +++--- .../readme.md | 38 +++++ .../Solution.php} | 68 ++++----- .../readme.md | 29 ++++ .../Solution.php} | 68 ++++----- .../readme.md | 29 ++++ .../Solution.php} | 92 ++++++------ .../readme.md | 30 ++++ .../Solution.php} | 72 +++++----- .../readme.md | 33 +++++ .../Solution.php} | 100 ++++++------- .../readme.md | 40 ++++++ .../Solution.php} | 60 ++++---- .../s0110_balanced_binary_tree/readme.md | 36 +++++ .../Solution.php} | 52 +++---- .../readme.md | 28 ++++ .../Solution.php} | 84 +++++------ src/Algorithms/s0112_path_sum/readme.md | 35 +++++ .../Solution.php} | 96 ++++++------- src/Algorithms/s0113_path_sum_ii/readme.md | 37 +++++ .../Solution.php} | 64 ++++----- .../readme.md | 35 +++++ .../Solution.php} | 42 +++--- .../s0115_distinct_subsequences/readme.md | 30 ++++ .../Solution.php} | 86 ++++++------ .../readme.md | 37 +++++ .../Solution.php} | 132 +++++++++--------- .../readme.md | 37 +++++ .../Solution.php} | 56 ++++---- .../s0118_pascals_triangle/readme.md | 25 ++++ .../Solution.php} | 66 ++++----- .../s0119_pascals_triangle_ii/readme.md | 33 +++++ .../Solution.php} | 54 +++---- src/Algorithms/s0120_triangle/readme.md | 37 +++++ .../Solution.php} | 60 ++++---- .../readme.md | 30 ++++ .../Solution.php} | 30 ++-- .../readme.md | 38 +++++ .../Solution.php} | 0 .../readme.md | 44 ++++++ .../Solution.php} | 0 .../readme.md | 34 +++++ .../Solution.php} | 0 .../s0125_valid_palindrome/readme.md | 36 +++++ .../Solution.php} | 0 .../readme.md | 26 ++++ .../Solution.php} | 0 .../s0129_sum_root_to_leaf_numbers/readme.md | 39 ++++++ .../Solution.php} | 0 .../s0130_surrounded_regions/readme.md | 30 ++++ .../Solution.php} | 0 .../s0131_palindrome_partitioning/readme.md | 24 ++++ .../Solution.php} | 52 +++---- .../readme.md | 32 +++++ .../Solution.php} | 78 +++++------ src/Algorithms/s0133_clone_graph/readme.md | 69 +++++++++ .../Solution.php} | 44 +++--- src/Algorithms/s0134_gas_station/readme.md | 47 +++++++ .../candy.php => s0135_candy/Solution.php} | 66 ++++----- src/Algorithms/s0135_candy/readme.md | 34 +++++ .../Solution.php} | 26 ++-- src/Algorithms/s0136_single_number/readme.md | 31 ++++ .../Solution.php} | 0 .../s0137_single_number_ii/readme.md | 25 ++++ .../Solution.php} | 0 .../readme.md | 56 ++++++++ .../Solution.php} | 0 src/Algorithms/s0139_word_break/readme.md | 37 +++++ .../Solution.php} | 0 src/Algorithms/s0140_word_break_ii/readme.md | 35 +++++ .../Solution.php} | 0 src/Algorithms/s0143_reorder_list/readme.md | 34 +++++ .../Solution.php} | 0 .../readme.md | 48 +++++++ .../Solution.php} | 0 .../readme.md | 48 +++++++ .../LRUCache.php} | 0 src/Algorithms/s0146_lru_cache/readme.md | 39 ++++++ .../Solution.php} | 0 .../s0147_insertion_sort_list/readme.md | 36 +++++ .../Solution.php} | 0 src/Algorithms/s0148_sort_list/readme.md | 34 +++++ .../Solution.php} | 0 .../s0149_max_points_on_a_line/readme.md | 28 ++++ .../Solution.php} | 0 .../readme.md | 48 +++++++ .../Solution.php} | 0 .../s0151_reverse_words_in_a_string/readme.md | 53 +++++++ .../Solution.php} | 0 .../s0152_maximum_product_subarray/readme.md | 31 ++++ .../Solution.php} | 26 ++-- .../readme.md | 46 ++++++ .../Solution.php} | 50 +++---- .../readme.md | 35 +++++ .../Solution.php} | 38 ++--- .../s0162_find_peak_element/readme.md | 33 +++++ .../Solution.php} | 132 +++++++++--------- src/Algorithms/s0164_maximum_gap/readme.md | 28 ++++ .../Solution.php} | 46 +++--- .../s0165_compare_version_numbers/readme.md | 58 ++++++++ .../Solution.php} | 116 +++++++-------- .../readme.md | 46 ++++++ .../Solution.php} | 42 +++--- .../readme.md | 41 ++++++ .../Solution.php} | 30 ++-- .../s0168_excel_sheet_column_title/readme.md | 44 ++++++ .../Solution.php} | 20 +-- .../s0169_majority_element/readme.md | 27 ++++ .../Solution.php} | 36 ++--- .../s0171_excel_sheet_column_number/readme.md | 46 ++++++ .../Solution.php} | 28 ++-- .../s0172_factorial_trailing_zeroes/readme.md | 35 +++++ .../Solution.php} | 66 ++++----- src/Algorithms/s0174_dungeon_game/readme.md | 38 +++++ .../Solution.php} | 64 ++++----- src/Algorithms/s0179_largest_number/readme.md | 36 +++++ .../Solution.php} | 0 .../s0771_jewels_and_stones/readme.md | 25 ++++ .../Solution.php} | 0 .../readme.md | 55 ++++++++ .../Solution.php} | 122 ++++++++-------- .../readme.md | 40 ++++++ tests/CalculatorTest.php | 50 ------- 330 files changed, 10267 insertions(+), 4273 deletions(-) delete mode 100644 src/Algorithms/Calculator.php rename src/Algorithms/{0001.two-sum/two-sum.php => s0001_two_sum/Solution.php} (96%) create mode 100644 src/Algorithms/s0001_two_sum/readme.md rename src/Algorithms/{0002.add-two-numbers/add-two-numbers.php => s0002_add_two_numbers/Solution.php} (96%) create mode 100644 src/Algorithms/s0002_add_two_numbers/readme.md rename src/Algorithms/{0003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.php => s0003_longest_substring_without_repeating_characters/Solution.php} (96%) create mode 100644 src/Algorithms/s0003_longest_substring_without_repeating_characters/readme.md rename src/Algorithms/{0004.median-of-two-sorted-arrays/median-of-two-sorted-arrays.php => s0004_median_of_two_sorted_arrays/Solution.php} (96%) create mode 100644 src/Algorithms/s0004_median_of_two_sorted_arrays/readme.md rename src/Algorithms/{0005.longest-palindromic-substring/longest-palindromic-substring.php => s0005_longest_palindromic_substring/Solution.php} (97%) create mode 100644 src/Algorithms/s0005_longest_palindromic_substring/readme.md rename src/Algorithms/{0006.zigzag-conversion/zigzag-conversion.php => s0006_zigzag_conversion/Solution.php} (96%) create mode 100644 src/Algorithms/s0006_zigzag_conversion/readme.md rename src/Algorithms/{0007.reverse-integer/reverse-integer.php => s0007_reverse_integer/Solution.php} (96%) create mode 100644 src/Algorithms/s0007_reverse_integer/readme.md rename src/Algorithms/{0008.string-to-integer-atoi/string-to-integer-atoi.php => s0008_string_to_integer_atoi/Solution.php} (96%) create mode 100644 src/Algorithms/s0008_string_to_integer_atoi/readme.md rename src/Algorithms/{0009.palindrome-number/palindrome-number.php => s0009_palindrome_number/Solution.php} (95%) create mode 100644 src/Algorithms/s0009_palindrome_number/readme.md rename src/Algorithms/{0010.regular-expression-matching/regular-expression-matching.php => s0010_regular_expression_matching/Solution.php} (97%) create mode 100644 src/Algorithms/s0010_regular_expression_matching/readme.md rename src/Algorithms/{0011.container-with-most-water/container-with-most-water.php => s0011_container_with_most_water/Solution.php} (96%) create mode 100644 src/Algorithms/s0011_container_with_most_water/readme.md rename src/Algorithms/{0012.integer-to-roman/integer-to-roman.php => s0012_integer_to_roman/Solution.php} (96%) create mode 100644 src/Algorithms/s0012_integer_to_roman/readme.md rename src/Algorithms/{0013.roman-to-integer/roman-to-integer.php => s0013_roman_to_integer/Solution.php} (95%) create mode 100644 src/Algorithms/s0013_roman_to_integer/readme.md rename src/Algorithms/{0014.longest-common-prefix/longest-common-prefix.php => s0014_longest_common_prefix/Solution.php} (96%) create mode 100644 src/Algorithms/s0014_longest_common_prefix/readme.md rename src/Algorithms/{0015.3sum/3sum.php => s0015_3sum/Solution.php} (96%) create mode 100644 src/Algorithms/s0015_3sum/readme.md rename src/Algorithms/{0016.3sum-closest/3sum-closest.php => s0016_3sum_closest/Solution.php} (96%) create mode 100644 src/Algorithms/s0016_3sum_closest/readme.md rename src/Algorithms/{0017.letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.php => s0017_letter_combinations_of_a_phone_number/Solution.php} (96%) create mode 100644 src/Algorithms/s0017_letter_combinations_of_a_phone_number/readme.md rename src/Algorithms/{0018.4sum/4sum.php => s0018_4sum/Solution.php} (96%) create mode 100644 src/Algorithms/s0018_4sum/readme.md rename src/Algorithms/{0019.remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.php => s0019_remove_nth_node_from_end_of_list/Solution.php} (95%) create mode 100644 src/Algorithms/s0019_remove_nth_node_from_end_of_list/readme.md rename src/Algorithms/{0020.valid-parentheses/valid-parentheses.php => s0020_valid_parentheses/Solution.php} (96%) create mode 100644 src/Algorithms/s0020_valid_parentheses/readme.md rename src/Algorithms/{0021.merge-two-sorted-lists/merge-two-sorted-lists.php => s0021_merge_two_sorted_lists/Solution.php} (96%) create mode 100644 src/Algorithms/s0021_merge_two_sorted_lists/readme.md rename src/Algorithms/{0022.generate-parentheses/generate-parentheses.php => s0022_generate_parentheses/Solution.php} (96%) create mode 100644 src/Algorithms/s0022_generate_parentheses/readme.md rename src/Algorithms/{0023.merge-k-sorted-lists/merge-k-sorted-lists.php => s0023_merge_k_sorted_lists/Solution.php} (96%) create mode 100644 src/Algorithms/s0023_merge_k_sorted_lists/readme.md rename src/Algorithms/{0024.swap-nodes-in-pairs/swap-nodes-in-pairs.php => s0024_swap_nodes_in_pairs/Solution.php} (95%) create mode 100644 src/Algorithms/s0024_swap_nodes_in_pairs/readme.md rename src/Algorithms/{0025.reverse-nodes-in-k-group/reverse-nodes-in-k-group.php => s0025_reverse_nodes_in_k_group/Solution.php} (95%) create mode 100644 src/Algorithms/s0025_reverse_nodes_in_k_group/readme.md rename src/Algorithms/{0026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.php => s0026_remove_duplicates_from_sorted_array/Solution.php} (94%) create mode 100644 src/Algorithms/s0026_remove_duplicates_from_sorted_array/readme.md rename src/Algorithms/{0027.remove-element/remove-element.php => s0027_remove_element/Solution.php} (95%) create mode 100644 src/Algorithms/s0027_remove_element/readme.md rename src/Algorithms/{0028.implement-strstr/implement-strstr.php => s0028_find_the_index_of_the_first_occurrence_in_a_string/Solution.php} (96%) create mode 100644 src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md rename src/Algorithms/{0029.divide-two-integers/divide-two-integers.php => s0029_divide_two_integers/Solution.php} (96%) create mode 100644 src/Algorithms/s0029_divide_two_integers/readme.md rename src/Algorithms/{0030.substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.php => s0030_substring_with_concatenation_of_all_words/Solution.php} (97%) create mode 100644 src/Algorithms/s0030_substring_with_concatenation_of_all_words/readme.md rename src/Algorithms/{0031.next-permutation/next-permutation.php => s0031_next_permutation/Solution.php} (96%) create mode 100644 src/Algorithms/s0031_next_permutation/readme.md rename src/Algorithms/{0032.longest-valid-parentheses/longest-valid-parentheses.php => s0032_longest_valid_parentheses/Solution.php} (97%) create mode 100644 src/Algorithms/s0032_longest_valid_parentheses/readme.md rename src/Algorithms/{0033.search-in-rotated-sorted-array/search-in-rotated-sorted-array.php => s0033_search_in_rotated_sorted_array/Solution.php} (96%) create mode 100644 src/Algorithms/s0033_search_in_rotated_sorted_array/readme.md rename src/Algorithms/{0034.search-for-a-range/search-for-a-range.php => s0034_find_first_and_last_position_of_element_in_sorted_array/Solution.php} (96%) create mode 100644 src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md rename src/Algorithms/{0035.search-insert-position/search-insert-position.php => s0035_search_insert_position/Solution.php} (95%) create mode 100644 src/Algorithms/s0035_search_insert_position/readme.md rename src/Algorithms/{0036.valid-sudoku/valid-sudoku.php => s0036_valid_sudoku/Solution.php} (96%) create mode 100644 src/Algorithms/s0036_valid_sudoku/readme.md rename src/Algorithms/{0037.sudoku-solver/sudoku-solver.php => s0037_sudoku_solver/Solution.php} (97%) create mode 100644 src/Algorithms/s0037_sudoku_solver/readme.md rename src/Algorithms/{0038.count-and-say/count-and-say.php => s0038_count_and_say/Solution.php} (95%) create mode 100644 src/Algorithms/s0038_count_and_say/readme.md rename src/Algorithms/{0039.combination-sum/combination-sum.php => s0039_combination_sum/Solution.php} (96%) create mode 100644 src/Algorithms/s0039_combination_sum/readme.md rename src/Algorithms/{0040.combination-sum-ii/combination-sum-ii.php => s0040_combination_sum_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0040_combination_sum_ii/readme.md rename src/Algorithms/{0041.first-missing-positive/first-missing-positive.php => s0041_first_missing_positive/Solution.php} (96%) create mode 100644 src/Algorithms/s0041_first_missing_positive/readme.md rename src/Algorithms/{0042.trapping-rain-water/trapping-rain-water.php => s0042_trapping_rain_water/Solution.php} (100%) create mode 100644 src/Algorithms/s0042_trapping_rain_water/readme.md rename src/Algorithms/{0043.multiply-strings/multiply-strings.php => s0043_multiply_strings/Solution.php} (100%) create mode 100644 src/Algorithms/s0043_multiply_strings/readme.md rename src/Algorithms/{0044.wildcard-matching/wildcard-matching.php => s0044_wildcard_matching/Solution.php} (100%) create mode 100644 src/Algorithms/s0044_wildcard_matching/readme.md rename src/Algorithms/{0045.jump-game-ii/jump-game-ii.php => s0045_jump_game_ii/Solution.php} (100%) create mode 100644 src/Algorithms/s0045_jump_game_ii/readme.md rename src/Algorithms/{0046.permutations/permutations.php => s0046_permutations/Solution.php} (100%) create mode 100644 src/Algorithms/s0046_permutations/readme.md rename src/Algorithms/{0047.permutations-ii/permutations-ii.php => s0047_permutations_ii/Solution.php} (100%) create mode 100644 src/Algorithms/s0047_permutations_ii/readme.md rename src/Algorithms/{0048.rotate-image/rotate-image.php => s0048_rotate_image/Solution.php} (100%) create mode 100644 src/Algorithms/s0048_rotate_image/readme.md rename src/Algorithms/{0049.group-anagrams/group-anagrams.php => s0049_group_anagrams/Solution.php} (100%) create mode 100644 src/Algorithms/s0049_group_anagrams/readme.md rename src/Algorithms/{0050.powx-n/powx-n.php => s0050_powx_n/Solution.php} (100%) create mode 100644 src/Algorithms/s0050_powx_n/readme.md rename src/Algorithms/{0051.n-queens/n-queens.php => s0051_n_queens/Solution.php} (97%) create mode 100644 src/Algorithms/s0051_n_queens/readme.md rename src/Algorithms/{0052.n-queens-ii/n-queens-ii.php => s0052_n_queens_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0052_n_queens_ii/readme.md rename src/Algorithms/{0053.maximum-subarray/maximum-subarray.php => s0053_maximum_subarray/Solution.php} (95%) create mode 100644 src/Algorithms/s0053_maximum_subarray/readme.md rename src/Algorithms/{0054.spiral-matrix/spiral-matrix.php => s0054_spiral_matrix/Solution.php} (94%) create mode 100644 src/Algorithms/s0054_spiral_matrix/readme.md rename src/Algorithms/{0055.jump-game/jump-game.php => s0055_jump_game/Solution.php} (95%) create mode 100644 src/Algorithms/s0055_jump_game/readme.md rename src/Algorithms/{0056.merge-intervals/merge-intervals.php => s0056_merge_intervals/Solution.php} (96%) create mode 100644 src/Algorithms/s0056_merge_intervals/readme.md rename src/Algorithms/{0057.insert-interval/insert-interval.php => s0057_insert_interval/Solution.php} (95%) create mode 100644 src/Algorithms/s0057_insert_interval/readme.md rename src/Algorithms/{0058.length-of-last-word/length-of-last-word.php => s0058_length_of_last_word/Solution.php} (95%) create mode 100644 src/Algorithms/s0058_length_of_last_word/readme.md rename src/Algorithms/{0059.spiral-matrix-ii/spiral-matrix-ii.php => s0059_spiral_matrix_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0059_spiral_matrix_ii/readme.md rename src/Algorithms/{0060.permutation-sequence/permutation-sequence.php => s0060_permutation_sequence/Solution.php} (95%) create mode 100644 src/Algorithms/s0060_permutation_sequence/readme.md rename src/Algorithms/{0061.rotate-list/rotate-list.php => s0061_rotate_list/Solution.php} (95%) create mode 100644 src/Algorithms/s0061_rotate_list/readme.md rename src/Algorithms/{0062.unique-paths/unique-paths.php => s0062_unique_paths/Solution.php} (95%) create mode 100644 src/Algorithms/s0062_unique_paths/readme.md rename src/Algorithms/{0063.unique-paths-ii/unique-paths-ii.php => s0063_unique_paths_ii/Solution.php} (97%) create mode 100644 src/Algorithms/s0063_unique_paths_ii/readme.md rename src/Algorithms/{0064.minimum-path-sum/minimum-path-sum.php => s0064_minimum_path_sum/Solution.php} (96%) create mode 100644 src/Algorithms/s0064_minimum_path_sum/readme.md rename src/Algorithms/{0065.valid-number/valid-number.php => s0065_valid_number/Solution.php} (96%) create mode 100644 src/Algorithms/s0065_valid_number/readme.md rename src/Algorithms/{0066.plus-one/plus-one.php => s0066_plus_one/Solution.php} (96%) create mode 100644 src/Algorithms/s0066_plus_one/readme.md rename src/Algorithms/{0067.add-binary/add-binary.php => s0067_add_binary/Solution.php} (96%) create mode 100644 src/Algorithms/s0067_add_binary/readme.md rename src/Algorithms/{0068.text-justification/text-justification.php => s0068_text_justification/Solution.php} (96%) create mode 100644 src/Algorithms/s0068_text_justification/readme.md rename src/Algorithms/{0069.sqrtx/sqrtx.php => s0069_sqrtx/Solution.php} (95%) create mode 100644 src/Algorithms/s0069_sqrtx/readme.md rename src/Algorithms/{0070.climbing-stairs/climbing-stairs.php => s0070_climbing_stairs/Solution.php} (93%) create mode 100644 src/Algorithms/s0070_climbing_stairs/readme.md rename src/Algorithms/{0071.simplify-path/simplify-path.php => s0071_simplify_path/Solution.php} (96%) create mode 100644 src/Algorithms/s0071_simplify_path/readme.md rename src/Algorithms/{0072.edit-distance/edit-distance.php => s0072_edit_distance/Solution.php} (96%) create mode 100644 src/Algorithms/s0072_edit_distance/readme.md rename src/Algorithms/{0073.set-matrix-zeroes/set-matrix-zeroes.php => s0073_set_matrix_zeroes/Solution.php} (97%) create mode 100644 src/Algorithms/s0073_set_matrix_zeroes/readme.md rename src/Algorithms/{0074.search-a-2d-matrix/search-a-2d-matrix.php => s0074_search_a_2d_matrix/Solution.php} (97%) create mode 100644 src/Algorithms/s0074_search_a_2d_matrix/readme.md rename src/Algorithms/{0075.sort-colors/sort-colors.php => s0075_sort_colors/Solution.php} (95%) create mode 100644 src/Algorithms/s0075_sort_colors/readme.md rename src/Algorithms/{0076.minimum-window-substring/minimum-window-substring.php => s0076_minimum_window_substring/Solution.php} (96%) create mode 100644 src/Algorithms/s0076_minimum_window_substring/readme.md rename src/Algorithms/{0077.combinations/combinations.php => s0077_combinations/Solution.php} (96%) create mode 100644 src/Algorithms/s0077_combinations/readme.md rename src/Algorithms/{0078.subsets/subsets.php => s0078_subsets/Solution.php} (96%) create mode 100644 src/Algorithms/s0078_subsets/readme.md rename src/Algorithms/{0079.word-search/word-search.php => s0079_word_search/Solution.php} (97%) create mode 100644 src/Algorithms/s0079_word_search/readme.md rename src/Algorithms/{0080.remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.php => s0080_remove_duplicates_from_sorted_array_ii/Solution.php} (95%) create mode 100644 src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/readme.md rename src/Algorithms/{0081.search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.php => s0081_search_in_rotated_sorted_array_ii/Solution.php} (95%) create mode 100644 src/Algorithms/s0081_search_in_rotated_sorted_array_ii/readme.md rename src/Algorithms/{0082.remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.php => s0082_remove_duplicates_from_sorted_list_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/readme.md rename src/Algorithms/{0083.remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.php => s0083_remove_duplicates_from_sorted_list/Solution.php} (95%) create mode 100644 src/Algorithms/s0083_remove_duplicates_from_sorted_list/readme.md rename src/Algorithms/{0084.largest-rectangle-in-histogram/largest-rectangle-in-histogram.php => s0084_largest_rectangle_in_histogram/Solution.php} (97%) create mode 100644 src/Algorithms/s0084_largest_rectangle_in_histogram/readme.md rename src/Algorithms/{0085.maximal-rectangle/maximal-rectangle.php => s0085_maximal_rectangle/Solution.php} (96%) create mode 100644 src/Algorithms/s0085_maximal_rectangle/readme.md rename src/Algorithms/{0086.partition-list/partition-list.php => s0086_partition_list/Solution.php} (96%) create mode 100644 src/Algorithms/s0086_partition_list/readme.md rename src/Algorithms/{0087.scramble-string/scramble-string.php => s0087_scramble_string/Solution.php} (97%) create mode 100644 src/Algorithms/s0087_scramble_string/readme.md rename src/Algorithms/{0088.merge-sorted-array/merge-sorted-array.php => s0088_merge_sorted_array/Solution.php} (96%) create mode 100644 src/Algorithms/s0088_merge_sorted_array/readme.md rename src/Algorithms/{0089.gray-code/gray-code.php => s0089_gray_code/Solution.php} (95%) create mode 100644 src/Algorithms/s0089_gray_code/readme.md rename src/Algorithms/{0090.subsets-ii/subsets-ii.php => s0090_subsets_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0090_subsets_ii/readme.md rename src/Algorithms/{0091.decode-ways/decode-ways.php => s0091_decode_ways/Solution.php} (94%) create mode 100644 src/Algorithms/s0091_decode_ways/readme.md rename src/Algorithms/{0092.reverse-linked-list-ii/reverse-linked-list-ii.php => s0092_reverse_linked_list_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0092_reverse_linked_list_ii/readme.md rename src/Algorithms/{0093.restore-ip-addresses/restore-ip-addresses.php => s0093_restore_ip_addresses/Solution.php} (96%) create mode 100644 src/Algorithms/s0093_restore_ip_addresses/readme.md rename src/Algorithms/{0094.binary-tree-inorder-traversal/binary-tree-inorder-traversal.php => s0094_binary_tree_inorder_traversal/Solution.php} (95%) create mode 100644 src/Algorithms/s0094_binary_tree_inorder_traversal/readme.md rename src/Algorithms/{0095.unique-binary-search-trees-ii/unique-binary-search-trees-ii.php => s0095_unique_binary_search_trees_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0095_unique_binary_search_trees_ii/readme.md rename src/Algorithms/{0096.unique-binary-search-trees/unique-binary-search-trees.php => s0096_unique_binary_search_trees/Solution.php} (95%) create mode 100644 src/Algorithms/s0096_unique_binary_search_trees/readme.md rename src/Algorithms/{0097.interleaving-string/interleaving-string.php => s0097_interleaving_string/Solution.php} (96%) create mode 100644 src/Algorithms/s0097_interleaving_string/readme.md rename src/Algorithms/{0098.validate-binary-search-tree/validate-binary-search-tree.php => s0098_validate_binary_search_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0098_validate_binary_search_tree/readme.md rename src/Algorithms/{0099.recover-binary-search-tree/recover-binary-search-tree.php => s0099_recover_binary_search_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0099_recover_binary_search_tree/readme.md rename src/Algorithms/{0100.same-tree/same-tree.php => s0100_same_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0100_same_tree/readme.md rename src/Algorithms/{0101.symmetric-tree/symmetric-tree.php => s0101_symmetric_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0101_symmetric_tree/readme.md rename src/Algorithms/{0102.binary-tree-level-order-traversal/binary-tree-level-order-traversal.php => s0102_binary_tree_level_order_traversal/Solution.php} (96%) create mode 100644 src/Algorithms/s0102_binary_tree_level_order_traversal/readme.md rename src/Algorithms/{0103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.php => s0103_binary_tree_zigzag_level_order_traversal/Solution.php} (96%) create mode 100644 src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/readme.md rename src/Algorithms/{0104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.php => s0104_maximum_depth_of_binary_tree/Solution.php} (95%) create mode 100644 src/Algorithms/s0104_maximum_depth_of_binary_tree/readme.md rename src/Algorithms/{0105.construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.php => s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php} (96%) create mode 100644 src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md rename src/Algorithms/{0106.construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.php => s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php} (97%) create mode 100644 src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md rename src/Algorithms/{0107.binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.php => s0107_binary_tree_level_order_traversal_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0107_binary_tree_level_order_traversal_ii/readme.md rename src/Algorithms/{0108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.php => s0108_convert_sorted_array_to_binary_search_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/readme.md rename src/Algorithms/{0109.convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.php => s0109_convert_sorted_list_to_binary_search_tree/Solution.php} (95%) create mode 100644 src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/readme.md rename src/Algorithms/{0110.balanced-binary-tree/balanced-binary-tree.php => s0110_balanced_binary_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0110_balanced_binary_tree/readme.md rename src/Algorithms/{0111.minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.php => s0111_minimum_depth_of_binary_tree/Solution.php} (96%) create mode 100644 src/Algorithms/s0111_minimum_depth_of_binary_tree/readme.md rename src/Algorithms/{0112.path-sum/path-sum.php => s0112_path_sum/Solution.php} (95%) create mode 100644 src/Algorithms/s0112_path_sum/readme.md rename src/Algorithms/{0113.path-sum-ii/path-sum-ii.php => s0113_path_sum_ii/Solution.php} (95%) create mode 100644 src/Algorithms/s0113_path_sum_ii/readme.md rename src/Algorithms/{0114.flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.php => s0114_flatten_binary_tree_to_linked_list/Solution.php} (95%) create mode 100644 src/Algorithms/s0114_flatten_binary_tree_to_linked_list/readme.md rename src/Algorithms/{0115.distinct-subsequences/distinct-subsequences.php => s0115_distinct_subsequences/Solution.php} (95%) create mode 100644 src/Algorithms/s0115_distinct_subsequences/readme.md rename src/Algorithms/{0116.populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.php => s0116_populating_next_right_pointers_in_each_node/Solution.php} (95%) create mode 100644 src/Algorithms/s0116_populating_next_right_pointers_in_each_node/readme.md rename src/Algorithms/{0117.populating-next-right-pointers-in-each-node-ii/populating-next-right-pointers-in-each-node-ii.php => s0117_populating_next_right_pointers_in_each_node_ii/Solution.php} (95%) create mode 100644 src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/readme.md rename src/Algorithms/{0118.pascals-triangle/pascals-triangle.php => s0118_pascals_triangle/Solution.php} (95%) create mode 100644 src/Algorithms/s0118_pascals_triangle/readme.md rename src/Algorithms/{0119.pascals-triangle-ii/pascals-triangle-ii.php => s0119_pascals_triangle_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0119_pascals_triangle_ii/readme.md rename src/Algorithms/{0120.triangle/triangle.php => s0120_triangle/Solution.php} (97%) create mode 100644 src/Algorithms/s0120_triangle/readme.md rename src/Algorithms/{0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.php => s0121_best_time_to_buy_and_sell_stock/Solution.php} (96%) create mode 100644 src/Algorithms/s0121_best_time_to_buy_and_sell_stock/readme.md rename src/Algorithms/{0122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.php => s0122_best_time_to_buy_and_sell_stock_ii/Solution.php} (95%) create mode 100644 src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/readme.md rename src/Algorithms/{0123.best-time-to-buy-and-sell-stock-iii/best-time-to-buy-and-sell-stock-iii.php => s0123_best_time_to_buy_and_sell_stock_iii/Solution.php} (100%) create mode 100644 src/Algorithms/s0123_best_time_to_buy_and_sell_stock_iii/readme.md rename src/Algorithms/{0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.php => s0124_binary_tree_maximum_path_sum/Solution.php} (100%) create mode 100644 src/Algorithms/s0124_binary_tree_maximum_path_sum/readme.md rename src/Algorithms/{0125.valid-palindrome/valid-palindrome.php => s0125_valid_palindrome/Solution.php} (100%) create mode 100644 src/Algorithms/s0125_valid_palindrome/readme.md rename src/Algorithms/{0128.longest-consecutive-sequence/longest-consecutive-sequence.php => s0128_longest_consecutive_sequence/Solution.php} (100%) create mode 100644 src/Algorithms/s0128_longest_consecutive_sequence/readme.md rename src/Algorithms/{0129.sum-root-to-leaf-numbers/sum-root-to-leaf-numbers.php => s0129_sum_root_to_leaf_numbers/Solution.php} (100%) create mode 100644 src/Algorithms/s0129_sum_root_to_leaf_numbers/readme.md rename src/Algorithms/{0130.surrounded-regions/surrounded-regions.php => s0130_surrounded_regions/Solution.php} (100%) create mode 100644 src/Algorithms/s0130_surrounded_regions/readme.md rename src/Algorithms/{0131.palindrome-partitioning/palindrome-partitioning.php => s0131_palindrome_partitioning/Solution.php} (100%) create mode 100644 src/Algorithms/s0131_palindrome_partitioning/readme.md rename src/Algorithms/{0132.palindrome-partitioning-ii/palindrome-partitioning-ii.php => s0132_palindrome_partitioning_ii/Solution.php} (96%) create mode 100644 src/Algorithms/s0132_palindrome_partitioning_ii/readme.md rename src/Algorithms/{0133.clone-graph/clone-graph.php => s0133_clone_graph/Solution.php} (95%) create mode 100644 src/Algorithms/s0133_clone_graph/readme.md rename src/Algorithms/{0134.gas-station/gas-station.php => s0134_gas_station/Solution.php} (95%) create mode 100644 src/Algorithms/s0134_gas_station/readme.md rename src/Algorithms/{0135.candy/candy.php => s0135_candy/Solution.php} (94%) create mode 100644 src/Algorithms/s0135_candy/readme.md rename src/Algorithms/{0136.single-number/single-number.php => s0136_single_number/Solution.php} (95%) create mode 100644 src/Algorithms/s0136_single_number/readme.md rename src/Algorithms/{0137.single-number-ii/single-number-ii.php => s0137_single_number_ii/Solution.php} (100%) create mode 100644 src/Algorithms/s0137_single_number_ii/readme.md rename src/Algorithms/{0138.copy-list-with-random-pointer/copy-list-with-random-pointer.php => s0138_copy_list_with_random_pointer/Solution.php} (100%) create mode 100644 src/Algorithms/s0138_copy_list_with_random_pointer/readme.md rename src/Algorithms/{0139.word-break/word-break.php => s0139_word_break/Solution.php} (100%) create mode 100644 src/Algorithms/s0139_word_break/readme.md rename src/Algorithms/{0140.word-break-ii/word-break-ii.php => s0140_word_break_ii/Solution.php} (100%) create mode 100644 src/Algorithms/s0140_word_break_ii/readme.md rename src/Algorithms/{0143.reorder-list/reorder-list.php => s0143_reorder_list/Solution.php} (100%) create mode 100644 src/Algorithms/s0143_reorder_list/readme.md rename src/Algorithms/{0144.binary-tree-preorder-traversal/binary-tree-preorder-traversal.php => s0144_binary_tree_preorder_traversal/Solution.php} (100%) create mode 100644 src/Algorithms/s0144_binary_tree_preorder_traversal/readme.md rename src/Algorithms/{0145.binary-tree-postorder-traversal/binary-tree-postorder-traversal.php => s0145_binary_tree_postorder_traversal/Solution.php} (100%) create mode 100644 src/Algorithms/s0145_binary_tree_postorder_traversal/readme.md rename src/Algorithms/{0146.lru-cache/lru-cache.php => s0146_lru_cache/LRUCache.php} (100%) create mode 100644 src/Algorithms/s0146_lru_cache/readme.md rename src/Algorithms/{0147.insertion-sort-list/insertion-sort-list.php => s0147_insertion_sort_list/Solution.php} (100%) create mode 100644 src/Algorithms/s0147_insertion_sort_list/readme.md rename src/Algorithms/{0148.sort-list/sort-list.php => s0148_sort_list/Solution.php} (100%) create mode 100644 src/Algorithms/s0148_sort_list/readme.md rename src/Algorithms/{0149.max-points-on-a-line/max-points-on-a-line.php => s0149_max_points_on_a_line/Solution.php} (100%) create mode 100644 src/Algorithms/s0149_max_points_on_a_line/readme.md rename src/Algorithms/{0150.evaluate-reverse-polish-notation/evaluate-reverse-polish-notation.php => s0150_evaluate_reverse_polish_notation/Solution.php} (100%) create mode 100644 src/Algorithms/s0150_evaluate_reverse_polish_notation/readme.md rename src/Algorithms/{0151.reverse-words-in-a-string/reverse-words-in-a-string.php => s0151_reverse_words_in_a_string/Solution.php} (100%) create mode 100644 src/Algorithms/s0151_reverse_words_in_a_string/readme.md rename src/Algorithms/{0152.maximum-product-subarray/maximum-product-subarray.php => s0152_maximum_product_subarray/Solution.php} (100%) create mode 100644 src/Algorithms/s0152_maximum_product_subarray/readme.md rename src/Algorithms/{0153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.php => s0153_find_minimum_in_rotated_sorted_array/Solution.php} (95%) create mode 100644 src/Algorithms/s0153_find_minimum_in_rotated_sorted_array/readme.md rename src/Algorithms/{0154.find-minimum-in-rotated-sorted-array-ii/find-minimum-in-rotated-sorted-array-ii.php => s0154_find_minimum_in_rotated_sorted_array_ii/Solution.php} (97%) create mode 100644 src/Algorithms/s0154_find_minimum_in_rotated_sorted_array_ii/readme.md rename src/Algorithms/{0162.find-peak-element/find-peak-element.php => s0162_find_peak_element/Solution.php} (96%) create mode 100644 src/Algorithms/s0162_find_peak_element/readme.md rename src/Algorithms/{0164.maximum-gap/maximum-gap.php => s0164_maximum_gap/Solution.php} (96%) create mode 100644 src/Algorithms/s0164_maximum_gap/readme.md rename src/Algorithms/{0165.compare-version-numbers/compare-version-numbers.php => s0165_compare_version_numbers/Solution.php} (96%) create mode 100644 src/Algorithms/s0165_compare_version_numbers/readme.md rename src/Algorithms/{0166.fraction-to-recurring-decimal/fraction-to-recurring-decimal.php => s0166_fraction_to_recurring_decimal/Solution.php} (96%) create mode 100644 src/Algorithms/s0166_fraction_to_recurring_decimal/readme.md rename src/Algorithms/{0167.two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.php => s0167_two_sum_ii_input_array_is_sorted/Solution.php} (96%) create mode 100644 src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/readme.md rename src/Algorithms/{0168.excel-sheet-column-title/excel-sheet-column-title.php => s0168_excel_sheet_column_title/Solution.php} (96%) create mode 100644 src/Algorithms/s0168_excel_sheet_column_title/readme.md rename src/Algorithms/{0169.majority-element/majority-element.php => s0169_majority_element/Solution.php} (95%) create mode 100644 src/Algorithms/s0169_majority_element/readme.md rename src/Algorithms/{0171.excel-sheet-column-number/excel-sheet-column-number.php => s0171_excel_sheet_column_number/Solution.php} (95%) create mode 100644 src/Algorithms/s0171_excel_sheet_column_number/readme.md rename src/Algorithms/{0172.factorial-trailing-zeroes/factorial-trailing-zeroes.php => s0172_factorial_trailing_zeroes/Solution.php} (94%) create mode 100644 src/Algorithms/s0172_factorial_trailing_zeroes/readme.md rename src/Algorithms/{0174.dungeon-game/dungeon-game.php => s0174_dungeon_game/Solution.php} (96%) create mode 100644 src/Algorithms/s0174_dungeon_game/readme.md rename src/Algorithms/{0179.largest-number/largest-number.php => s0179_largest_number/Solution.php} (95%) create mode 100644 src/Algorithms/s0179_largest_number/readme.md rename src/Algorithms/{0771.jewels-and-stones/jewels-and-stones.php => s0771_jewels_and_stones/Solution.php} (100%) create mode 100644 src/Algorithms/s0771_jewels_and_stones/readme.md rename src/Algorithms/{0864.shortest-path-to-get-all-keys/shortest-path-to-get-all-keys.php => s0864_shortest_path_to_get_all_keys/Solution.php} (100%) create mode 100644 src/Algorithms/s0864_shortest_path_to_get_all_keys/readme.md rename src/Algorithms/{0973.k-closest-points-to-origin/k-closest-points-to-origin.php => s0973_k_closest_points_to_origin/Solution.php} (96%) create mode 100644 src/Algorithms/s0973_k_closest_points_to_origin/readme.md delete mode 100644 tests/CalculatorTest.php diff --git a/src/Algorithms/Calculator.php b/src/Algorithms/Calculator.php deleted file mode 100644 index 17159db..0000000 --- a/src/Algorithms/Calculator.php +++ /dev/null @@ -1,59 +0,0 @@ -2 <= nums.length <= 104 +* -109 <= nums[i] <= 109 +* -109 <= target <= 109 +* **Only one valid answer exists.** + +**Follow-up:** Can you come up with an algorithm that is less than O(n2) time complexity? diff --git a/src/Algorithms/0002.add-two-numbers/add-two-numbers.php b/src/Algorithms/s0002_add_two_numbers/Solution.php similarity index 96% rename from src/Algorithms/0002.add-two-numbers/add-two-numbers.php rename to src/Algorithms/s0002_add_two_numbers/Solution.php index d5ff555..4b6a4a2 100644 --- a/src/Algorithms/0002.add-two-numbers/add-two-numbers.php +++ b/src/Algorithms/s0002_add_two_numbers/Solution.php @@ -1,35 +1,35 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $l1 - * @param ListNode $l2 - * @return ListNode - */ - function addTwoNumbers($l1, $l2) { - $dummyHead = new ListNode(0); - $p = $l1; $q = $l2; $curr = $dummyHead; - $carry = 0; - while ($p != null || $q != null) { - $x = ($p != null) ? $p->val : 0; - $y = ($q != null) ? $q->val : 0; - $sum = $carry + $x + $y; - $carry = intval($sum / 10); - $curr->next = new ListNode($sum % 10); - $curr = $curr->next; - if ($p != null) $p = $p->next; - if ($q != null) $q = $q->next; - } - if ($carry > 0) { - $curr->next = new ListNode($carry); - } - return $dummyHead->next; - } +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $l1 + * @param ListNode $l2 + * @return ListNode + */ + function addTwoNumbers($l1, $l2) { + $dummyHead = new ListNode(0); + $p = $l1; $q = $l2; $curr = $dummyHead; + $carry = 0; + while ($p != null || $q != null) { + $x = ($p != null) ? $p->val : 0; + $y = ($q != null) ? $q->val : 0; + $sum = $carry + $x + $y; + $carry = intval($sum / 10); + $curr->next = new ListNode($sum % 10); + $curr = $curr->next; + if ($p != null) $p = $p->next; + if ($q != null) $q = $q->next; + } + if ($carry > 0) { + $curr->next = new ListNode($carry); + } + return $dummyHead->next; + } } diff --git a/src/Algorithms/s0002_add_two_numbers/readme.md b/src/Algorithms/s0002_add_two_numbers/readme.md new file mode 100644 index 0000000..6e67c19 --- /dev/null +++ b/src/Algorithms/s0002_add_two_numbers/readme.md @@ -0,0 +1,35 @@ +2\. Add Two Numbers + +Medium + +You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg) + +**Input:** l1 = [2,4,3], l2 = [5,6,4] + +**Output:** [7,0,8] + +**Explanation:** 342 + 465 = 807. + +**Example 2:** + +**Input:** l1 = [0], l2 = [0] + +**Output:** [0] + +**Example 3:** + +**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] + +**Output:** [8,9,9,9,0,0,0,1] + +**Constraints:** + +* The number of nodes in each linked list is in the range `[1, 100]`. +* `0 <= Node.val <= 9` +* It is guaranteed that the list represents a number that does not have leading zeros. \ No newline at end of file diff --git a/src/Algorithms/0003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.php b/src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php similarity index 96% rename from src/Algorithms/0003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.php rename to src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php index 1565b2b..f131766 100644 --- a/src/Algorithms/0003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.php +++ b/src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php @@ -1,20 +1,20 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function lengthOfLongestSubstring($s) { - if (strlen($s)==0) return 0; - $map = []; - $max = 0; - for ($i=0, $j=0; $i < strlen($s); ++$i) { - if (array_key_exists($s[$i], $map)){ - $j = max($j, $map[$s[$i]] + 1); - } - $map[$s[$i]] = $i; - $max = max($max, $i - $j + 1); - } - return $max; - } +class Solution { + + /** + * @param String $s + * @return Integer + */ + function lengthOfLongestSubstring($s) { + if (strlen($s)==0) return 0; + $map = []; + $max = 0; + for ($i=0, $j=0; $i < strlen($s); ++$i) { + if (array_key_exists($s[$i], $map)){ + $j = max($j, $map[$s[$i]] + 1); + } + $map[$s[$i]] = $i; + $max = max($max, $i - $j + 1); + } + return $max; + } } \ No newline at end of file diff --git a/src/Algorithms/s0003_longest_substring_without_repeating_characters/readme.md b/src/Algorithms/s0003_longest_substring_without_repeating_characters/readme.md new file mode 100644 index 0000000..bf1ef46 --- /dev/null +++ b/src/Algorithms/s0003_longest_substring_without_repeating_characters/readme.md @@ -0,0 +1,40 @@ +3\. Longest Substring Without Repeating Characters + +Medium + +Given a string `s`, find the length of the **longest substring** without repeating characters. + +**Example 1:** + +**Input:** s = "abcabcbb" + +**Output:** 3 + +**Explanation:** The answer is "abc", with the length of 3. + +**Example 2:** + +**Input:** s = "bbbbb" + +**Output:** 1 + +**Explanation:** The answer is "b", with the length of 1. + +**Example 3:** + +**Input:** s = "pwwkew" + +**Output:** 3 + +**Explanation:** The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + +**Example 4:** + +**Input:** s = "" + +**Output:** 0 + +**Constraints:** + +* 0 <= s.length <= 5 * 104 +* `s` consists of English letters, digits, symbols and spaces. \ No newline at end of file diff --git a/src/Algorithms/0004.median-of-two-sorted-arrays/median-of-two-sorted-arrays.php b/src/Algorithms/s0004_median_of_two_sorted_arrays/Solution.php similarity index 96% rename from src/Algorithms/0004.median-of-two-sorted-arrays/median-of-two-sorted-arrays.php rename to src/Algorithms/s0004_median_of_two_sorted_arrays/Solution.php index b518f98..bfd5153 100644 --- a/src/Algorithms/0004.median-of-two-sorted-arrays/median-of-two-sorted-arrays.php +++ b/src/Algorithms/s0004_median_of_two_sorted_arrays/Solution.php @@ -1,37 +1,37 @@ -class Solution { - - /** - * @param Integer[] $nums1 - * @param Integer[] $nums2 - * @return Float - */ - function findMedianSortedArrays($nums1, $nums2) { - $array = range(0, count($nums1) + count($nums2) - 1); - $p=0; $q=0; - - - for($i =0;$i< count($array);$i++) - { - if(($p$nums2[$q]) || $p==count($nums1)) - { - $array[$i]=$nums2[$q]; - $q++; - } - } - - if (intval(count($array) % 2)==0) - { - return doubleval($array[count($array) / 2] + $array[(count($array) / 2) - 1])/2; - } - else - { - return doubleval($array[count($array) / 2]); - } - } +class Solution { + + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Float + */ + function findMedianSortedArrays($nums1, $nums2) { + $array = range(0, count($nums1) + count($nums2) - 1); + $p=0; $q=0; + + + for($i =0;$i< count($array);$i++) + { + if(($p$nums2[$q]) || $p==count($nums1)) + { + $array[$i]=$nums2[$q]; + $q++; + } + } + + if (intval(count($array) % 2)==0) + { + return doubleval($array[count($array) / 2] + $array[(count($array) / 2) - 1])/2; + } + else + { + return doubleval($array[count($array) / 2]); + } + } } diff --git a/src/Algorithms/s0004_median_of_two_sorted_arrays/readme.md b/src/Algorithms/s0004_median_of_two_sorted_arrays/readme.md new file mode 100644 index 0000000..a463374 --- /dev/null +++ b/src/Algorithms/s0004_median_of_two_sorted_arrays/readme.md @@ -0,0 +1,50 @@ +4\. Median of Two Sorted Arrays + +Hard + +Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. + +The overall run time complexity should be `O(log (m+n))`. + +**Example 1:** + +**Input:** nums1 = [1,3], nums2 = [2] + +**Output:** 2.00000 + +**Explanation:** merged array = [1,2,3] and median is 2. + +**Example 2:** + +**Input:** nums1 = [1,2], nums2 = [3,4] + +**Output:** 2.50000 + +**Explanation:** merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. + +**Example 3:** + +**Input:** nums1 = [0,0], nums2 = [0,0] + +**Output:** 0.00000 + +**Example 4:** + +**Input:** nums1 = [], nums2 = [1] + +**Output:** 1.00000 + +**Example 5:** + +**Input:** nums1 = [2], nums2 = [] + +**Output:** 2.00000 + +**Constraints:** + +* `nums1.length == m` +* `nums2.length == n` +* `0 <= m <= 1000` +* `0 <= n <= 1000` +* `1 <= m + n <= 2000` +* -106 <= nums1[i], nums2[i] <= 106 \ No newline at end of file diff --git a/src/Algorithms/0005.longest-palindromic-substring/longest-palindromic-substring.php b/src/Algorithms/s0005_longest_palindromic_substring/Solution.php similarity index 97% rename from src/Algorithms/0005.longest-palindromic-substring/longest-palindromic-substring.php rename to src/Algorithms/s0005_longest_palindromic_substring/Solution.php index 7a43e92..ca2d331 100644 --- a/src/Algorithms/0005.longest-palindromic-substring/longest-palindromic-substring.php +++ b/src/Algorithms/s0005_longest_palindromic_substring/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param String $s - * @return String - */ - function longestPalindrome($s) { - if(strlen($s) == 0) { - return $s; - } - $dp = array_fill(0, strlen($s), array_fill(0, strlen($s), false)); - $longestPalindromeStart = 0; $longestPalindromeLength = 1; - for($i=strlen($s)-1;$i>=0;$i--){ - $dp[$i][$i] = true; //single character is a palindrome so making it true - for($j=$i+1;$j $longestPalindromeLength) { // update the length if greater than previous - $longestPalindromeLength = $j - $i + 1; - $longestPalindromeStart = $i; - } - } - } - } - // return the substring using starting and ending index - return substr($s, $longestPalindromeStart,$longestPalindromeLength); - } +class Solution { + + /** + * @param String $s + * @return String + */ + function longestPalindrome($s) { + if(strlen($s) == 0) { + return $s; + } + $dp = array_fill(0, strlen($s), array_fill(0, strlen($s), false)); + $longestPalindromeStart = 0; $longestPalindromeLength = 1; + for($i=strlen($s)-1;$i>=0;$i--){ + $dp[$i][$i] = true; //single character is a palindrome so making it true + for($j=$i+1;$j $longestPalindromeLength) { // update the length if greater than previous + $longestPalindromeLength = $j - $i + 1; + $longestPalindromeStart = $i; + } + } + } + } + // return the substring using starting and ending index + return substr($s, $longestPalindromeStart,$longestPalindromeLength); + } } \ No newline at end of file diff --git a/src/Algorithms/s0005_longest_palindromic_substring/readme.md b/src/Algorithms/s0005_longest_palindromic_substring/readme.md new file mode 100644 index 0000000..883ff5c --- /dev/null +++ b/src/Algorithms/s0005_longest_palindromic_substring/readme.md @@ -0,0 +1,34 @@ +5\. Longest Palindromic Substring + +Medium + +Given a string `s`, return _the longest palindromic substring_ in `s`. + +**Example 1:** + +**Input:** s = "babad" + +**Output:** "bab" **Note:** "aba" is also a valid answer. + +**Example 2:** + +**Input:** s = "cbbd" + +**Output:** "bb" + +**Example 3:** + +**Input:** s = "a" + +**Output:** "a" + +**Example 4:** + +**Input:** s = "ac" + +**Output:** "a" + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s` consist of only digits and English letters. \ No newline at end of file diff --git a/src/Algorithms/0006.zigzag-conversion/zigzag-conversion.php b/src/Algorithms/s0006_zigzag_conversion/Solution.php similarity index 96% rename from src/Algorithms/0006.zigzag-conversion/zigzag-conversion.php rename to src/Algorithms/s0006_zigzag_conversion/Solution.php index bb36bea..6a3e81a 100644 --- a/src/Algorithms/0006.zigzag-conversion/zigzag-conversion.php +++ b/src/Algorithms/s0006_zigzag_conversion/Solution.php @@ -1,24 +1,24 @@ -class Solution { - - /** - * @param String $s - * @param Integer $numRows - * @return String - */ - function convert($s, $numRows) { - if ($numRows == 1) return $s; - - $ret = ""; - $n = strlen($s); - $cycleLen = 2 * $numRows - 2; - - for ($i = 0; $i < $numRows; $i++) { - for ($j = 0; $j + $i < $n; $j += $cycleLen) { - $ret = $ret . $s[$j + $i]; - if ($i != 0 && $i != $numRows - 1 && $j + $cycleLen - $i < $n) - $ret = $ret . $s[$j + $cycleLen - $i]; - } - } - return $ret; - } +class Solution { + + /** + * @param String $s + * @param Integer $numRows + * @return String + */ + function convert($s, $numRows) { + if ($numRows == 1) return $s; + + $ret = ""; + $n = strlen($s); + $cycleLen = 2 * $numRows - 2; + + for ($i = 0; $i < $numRows; $i++) { + for ($j = 0; $j + $i < $n; $j += $cycleLen) { + $ret = $ret . $s[$j + $i]; + if ($i != 0 && $i != $numRows - 1 && $j + $cycleLen - $i < $n) + $ret = $ret . $s[$j + $cycleLen - $i]; + } + } + return $ret; + } } \ No newline at end of file diff --git a/src/Algorithms/s0006_zigzag_conversion/readme.md b/src/Algorithms/s0006_zigzag_conversion/readme.md new file mode 100644 index 0000000..4f55d57 --- /dev/null +++ b/src/Algorithms/s0006_zigzag_conversion/readme.md @@ -0,0 +1,39 @@ +6\. Zigzag Conversion + +Medium + +The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) + +P A H N A P L S I I G Y I R + +And then read line by line: `"PAHNAPLSIIGYIR"` + +Write the code that will take a string and make this conversion given a number of rows: + +string convert(string s, int numRows); + +**Example 1:** + +**Input:** s = "PAYPALISHIRING", numRows = 3 + +**Output:** "PAHNAPLSIIGYIR" + +**Example 2:** + +**Input:** s = "PAYPALISHIRING", numRows = 4 + +**Output:** "PINALSIGYAHRPI" + +**Explanation:** P I N A L S I G Y A H R P I + +**Example 3:** + +**Input:** s = "A", numRows = 1 + +**Output:** "A" + +**Constraints:** + +* `1 <= s.length <= 1000` +* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. +* `1 <= numRows <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0007.reverse-integer/reverse-integer.php b/src/Algorithms/s0007_reverse_integer/Solution.php similarity index 96% rename from src/Algorithms/0007.reverse-integer/reverse-integer.php rename to src/Algorithms/s0007_reverse_integer/Solution.php index 96b088e..1427a0e 100644 --- a/src/Algorithms/0007.reverse-integer/reverse-integer.php +++ b/src/Algorithms/s0007_reverse_integer/Solution.php @@ -1,16 +1,16 @@ -class Solution { - - /** - * @param Integer $x - * @return Integer - */ - function reverse($x) { - $rev = 0; - while ($x != 0) { - $rev = ($rev * 10) + ($x % 10); - $x = intval($x / 10); - } - if (intval($rev) > 2147483647 || intval($rev) < -2147483647 ) return 0; - return intval($rev); - } +class Solution { + + /** + * @param Integer $x + * @return Integer + */ + function reverse($x) { + $rev = 0; + while ($x != 0) { + $rev = ($rev * 10) + ($x % 10); + $x = intval($x / 10); + } + if (intval($rev) > 2147483647 || intval($rev) < -2147483647 ) return 0; + return intval($rev); + } } diff --git a/src/Algorithms/s0007_reverse_integer/readme.md b/src/Algorithms/s0007_reverse_integer/readme.md new file mode 100644 index 0000000..81dbb62 --- /dev/null +++ b/src/Algorithms/s0007_reverse_integer/readme.md @@ -0,0 +1,35 @@ +7\. Reverse Integer + +Medium + +Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return `0`. + +**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** + +**Example 1:** + +**Input:** x = 123 + +**Output:** 321 + +**Example 2:** + +**Input:** x = -123 + +**Output:** -321 + +**Example 3:** + +**Input:** x = 120 + +**Output:** 21 + +**Example 4:** + +**Input:** x = 0 + +**Output:** 0 + +**Constraints:** + +* -231 <= x <= 231 - 1 \ No newline at end of file diff --git a/src/Algorithms/0008.string-to-integer-atoi/string-to-integer-atoi.php b/src/Algorithms/s0008_string_to_integer_atoi/Solution.php similarity index 96% rename from src/Algorithms/0008.string-to-integer-atoi/string-to-integer-atoi.php rename to src/Algorithms/s0008_string_to_integer_atoi/Solution.php index f3b698d..85d34c6 100644 --- a/src/Algorithms/0008.string-to-integer-atoi/string-to-integer-atoi.php +++ b/src/Algorithms/s0008_string_to_integer_atoi/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param String $str - * @return Integer - */ - function myAtoi($str) { - if (trim($str) == '') - return 0; - $str = trim($str); - $i = 0; $ans = 0; $sign = 1; $len = strlen($str); - if ($str[$i] == '-' || $str[$i] == '+') - $sign = $str[$i++] == '+' ? 1 : -1; - for (; $i < $len; ++$i) { - $tmp = ord($str[$i]) - ord('0'); - if ($tmp < 0 || $tmp > 9) - break; - if ($ans > intval(2147483647 / 10) - || ($ans == intval(2147483647 / 10) && (2147483647 % 10) < $tmp)) { - return $sign == 1 ? 2147483647 : -2147483648; - } else - $ans = $ans * 10 + $tmp; - } - return $sign * $ans; - } +class Solution { + + /** + * @param String $str + * @return Integer + */ + function myAtoi($str) { + if (trim($str) == '') + return 0; + $str = trim($str); + $i = 0; $ans = 0; $sign = 1; $len = strlen($str); + if ($str[$i] == '-' || $str[$i] == '+') + $sign = $str[$i++] == '+' ? 1 : -1; + for (; $i < $len; ++$i) { + $tmp = ord($str[$i]) - ord('0'); + if ($tmp < 0 || $tmp > 9) + break; + if ($ans > intval(2147483647 / 10) + || ($ans == intval(2147483647 / 10) && (2147483647 % 10) < $tmp)) { + return $sign == 1 ? 2147483647 : -2147483648; + } else + $ans = $ans * 10 + $tmp; + } + return $sign * $ans; + } } diff --git a/src/Algorithms/s0008_string_to_integer_atoi/readme.md b/src/Algorithms/s0008_string_to_integer_atoi/readme.md new file mode 100644 index 0000000..af67f64 --- /dev/null +++ b/src/Algorithms/s0008_string_to_integer_atoi/readme.md @@ -0,0 +1,113 @@ +8\. String to Integer (atoi) + +Medium + +Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). + +The algorithm for `myAtoi(string s)` is as follows: + +1. Read in and ignore any leading whitespace. +2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. +3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. +4. Convert these digits into an integer (i.e. `"123" -> 123`, `"0032" -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). +5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. +6. Return the integer as the final result. + +**Note:** + +* Only the space character `' '` is considered a whitespace character. +* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. + +**Example 1:** + +**Input:** s = "42" + +**Output:** 42 + +**Explanation:** The underlined characters are what is read in, the caret is the current reader position. + + Step 1: "42" (no characters read because there is no leading whitespace) + ^ + Step 2: "42" (no characters read because there is neither a '-' nor '+') + ^ + Step 3: "42" ("42" is read in) + ^ + +The parsed integer is 42. Since 42 is in the range [-231, 231 - 1], the final result is 42. + +**Example 2:** + +**Input:** s = " -42" + +**Output:** -42 + +**Explanation:** + + Step 1: " -42" (leading whitespace is read and ignored) + ^ + Step 2: " -42" ('-' is read, so the result should be negative) + ^ + Step 3: " -42" ("42" is read in) + ^ + The parsed integer is -42. + +Since -42 is in the range [-231, 231 - 1], the final result is -42. + +**Example 3:** + +**Input:** s = "4193 with words" + +**Output:** 4193 + +**Explanation:** + + Step 1: "4193 with words" (no characters read because there is no leading whitespace) + ^ + Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') + ^ + Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) + ^ + The parsed integer is 4193. + +Since 4193 is in the range [-231, 231 - 1], the final result is 4193. + +**Example 4:** + +**Input:** s = "words and 987" + +**Output:** 0 + +**Explanation:** + + Step 1: "words and 987" (no characters read because there is no leading whitespace) + ^ + Step 2: "words and 987" (no characters read because there is neither a '-' nor '+') + ^ + Step 3: "words and 987" (reading stops immediately because there is a non-digit 'w') + ^ + The parsed integer is 0 because no digits were read. + +Since 0 is in the range [-231, 231 - 1], the final result is 0. + +**Example 5:** + +**Input:** s = "-91283472332" + +**Output:** -2147483648 + +**Explanation:** + + Step 1: "-91283472332" (no characters read because there is no leading whitespace) + ^ + Step 2: "-91283472332" ('-' is read, so the result should be negative) + ^ + Step 3: "-91283472332" ("91283472332" is read in) + ^ + The parsed integer is -91283472332. + +Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648. + +**Constraints:** + +* `0 <= s.length <= 200` +* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`. \ No newline at end of file diff --git a/src/Algorithms/0009.palindrome-number/palindrome-number.php b/src/Algorithms/s0009_palindrome_number/Solution.php similarity index 95% rename from src/Algorithms/0009.palindrome-number/palindrome-number.php rename to src/Algorithms/s0009_palindrome_number/Solution.php index 25a7c13..545b004 100644 --- a/src/Algorithms/0009.palindrome-number/palindrome-number.php +++ b/src/Algorithms/s0009_palindrome_number/Solution.php @@ -1,16 +1,16 @@ -class Solution { - - /** - * @param Integer $x - * @return Boolean - */ - function isPalindrome($x) { - if($x<0) return false; - $i = 0; $rev = 0; $ori = $x; - for($i=10; $x>0; $x= intval($x / 10)){ - $rev *= 10; - $rev += $x % $i; - } - return $rev==$ori; - } +class Solution { + + /** + * @param Integer $x + * @return Boolean + */ + function isPalindrome($x) { + if($x<0) return false; + $i = 0; $rev = 0; $ori = $x; + for($i=10; $x>0; $x= intval($x / 10)){ + $rev *= 10; + $rev += $x % $i; + } + return $rev==$ori; + } } \ No newline at end of file diff --git a/src/Algorithms/s0009_palindrome_number/readme.md b/src/Algorithms/s0009_palindrome_number/readme.md new file mode 100644 index 0000000..f05939b --- /dev/null +++ b/src/Algorithms/s0009_palindrome_number/readme.md @@ -0,0 +1,41 @@ +9\. Palindrome Number + +Easy + +Given an integer `x`, return `true` if `x` is palindrome integer. + +An integer is a **palindrome** when it reads the same backward as forward. For example, `121` is palindrome while `123` is not. + +**Example 1:** + +**Input:** x = 121 + +**Output:** true + +**Example 2:** + +**Input:** x = -121 + +**Output:** false + +**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. + +**Example 3:** + +**Input:** x = 10 + +**Output:** false + +**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome. + +**Example 4:** + +**Input:** x = -101 + +**Output:** false + +**Constraints:** + +* -231 <= x <= 231 - 1 + +**Follow up:** Could you solve it without converting the integer to a string? \ No newline at end of file diff --git a/src/Algorithms/0010.regular-expression-matching/regular-expression-matching.php b/src/Algorithms/s0010_regular_expression_matching/Solution.php similarity index 97% rename from src/Algorithms/0010.regular-expression-matching/regular-expression-matching.php rename to src/Algorithms/s0010_regular_expression_matching/Solution.php index c89af3e..8f6322f 100644 --- a/src/Algorithms/0010.regular-expression-matching/regular-expression-matching.php +++ b/src/Algorithms/s0010_regular_expression_matching/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param String $s - * @param String $p - * @return Boolean - */ - function isMatch($s, $p) { - $dp = array_fill(0, strlen($s) + 1, array_fill(0, strlen($p) + 1, false)); - $dp[strlen($s)][strlen($p)] = true; - - for ($i = strlen($s); $i >= 0; $i--){ - for ($j = strlen($p) - 1; $j >= 0; $j--){ - $first_match = ($i < strlen($s) && - ($p[$j] == $s[$i] || - $p[$j] == '.')); - if ($j + 1 < strlen($p) && $p[$j+1] == '*'){ - $dp[$i][$j] = $dp[$i][$j+2] || $first_match && $dp[$i+1][$j]; - } else { - $dp[$i][$j] = $first_match && $dp[$i+1][$j+1]; - } - } - } - return $dp[0][0]; - } +class Solution { + + /** + * @param String $s + * @param String $p + * @return Boolean + */ + function isMatch($s, $p) { + $dp = array_fill(0, strlen($s) + 1, array_fill(0, strlen($p) + 1, false)); + $dp[strlen($s)][strlen($p)] = true; + + for ($i = strlen($s); $i >= 0; $i--){ + for ($j = strlen($p) - 1; $j >= 0; $j--){ + $first_match = ($i < strlen($s) && + ($p[$j] == $s[$i] || + $p[$j] == '.')); + if ($j + 1 < strlen($p) && $p[$j+1] == '*'){ + $dp[$i][$j] = $dp[$i][$j+2] || $first_match && $dp[$i+1][$j]; + } else { + $dp[$i][$j] = $first_match && $dp[$i+1][$j+1]; + } + } + } + return $dp[0][0]; + } } \ No newline at end of file diff --git a/src/Algorithms/s0010_regular_expression_matching/readme.md b/src/Algorithms/s0010_regular_expression_matching/readme.md new file mode 100644 index 0000000..f614e74 --- /dev/null +++ b/src/Algorithms/s0010_regular_expression_matching/readme.md @@ -0,0 +1,56 @@ +10\. Regular Expression Matching + +Hard + +Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: + +* `'.'` Matches any single character. +* `'*'` Matches zero or more of the preceding element. + +The matching should cover the **entire** input string (not partial). + +**Example 1:** + +**Input:** s = "aa", p = "a" + +**Output:** false + +**Explanation:** "a" does not match the entire string "aa". + +**Example 2:** + +**Input:** s = "aa", p = "a\*" + +**Output:** true + +**Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". + +**Example 3:** + +**Input:** s = "ab", p = ".\*" + +**Output:** true + +**Explanation:** ".\*" means "zero or more (\*) of any character (.)". + +**Example 4:** + +**Input:** s = "aab", p = "c\*a\*b" + +**Output:** true + +**Explanation:** c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab". + +**Example 5:** + +**Input:** s = "mississippi", p = "mis\*is\*p\*." + +**Output:** false + +**Constraints:** + +* `1 <= s.length <= 20` +* `1 <= p.length <= 30` +* `s` contains only lowercase English letters. +* `p` contains only lowercase English letters, `'.'`, and `'*'`. +* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. \ No newline at end of file diff --git a/src/Algorithms/0011.container-with-most-water/container-with-most-water.php b/src/Algorithms/s0011_container_with_most_water/Solution.php similarity index 96% rename from src/Algorithms/0011.container-with-most-water/container-with-most-water.php rename to src/Algorithms/s0011_container_with_most_water/Solution.php index 7dacef9..35b310c 100644 --- a/src/Algorithms/0011.container-with-most-water/container-with-most-water.php +++ b/src/Algorithms/s0011_container_with_most_water/Solution.php @@ -1,18 +1,18 @@ -class Solution { - - /** - * @param Integer[] $height - * @return Integer - */ - function maxArea($height) { - $maxarea = 0; $l = 0; $r = count($height) - 1; - while ($l < $r) { - $maxarea = max($maxarea, min($height[$l], $height[$r]) * ($r - $l)); - if ($height[$l] < $height[$r]) - $l++; - else - $r--; - } - return $maxarea; - } +class Solution { + + /** + * @param Integer[] $height + * @return Integer + */ + function maxArea($height) { + $maxarea = 0; $l = 0; $r = count($height) - 1; + while ($l < $r) { + $maxarea = max($maxarea, min($height[$l], $height[$r]) * ($r - $l)); + if ($height[$l] < $height[$r]) + $l++; + else + $r--; + } + return $maxarea; + } } \ No newline at end of file diff --git a/src/Algorithms/s0011_container_with_most_water/readme.md b/src/Algorithms/s0011_container_with_most_water/readme.md new file mode 100644 index 0000000..5678844 --- /dev/null +++ b/src/Algorithms/s0011_container_with_most_water/readme.md @@ -0,0 +1,41 @@ +11\. Container With Most Water + +Medium + +Given `n` non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). `n` vertical lines are drawn such that the two endpoints of the line `i` is at (i, ai) and `(i, 0)`. Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. + +**Notice** that you may not slant the container. + +**Example 1:** + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg) + +**Input:** height = [1,8,6,2,5,4,8,3,7] + +**Output:** 49 + +**Explanation:** The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. + +**Example 2:** + +**Input:** height = [1,1] + +**Output:** 1 + +**Example 3:** + +**Input:** height = [4,3,2,1,4] + +**Output:** 16 + +**Example 4:** + +**Input:** height = [1,2,1] + +**Output:** 2 + +**Constraints:** + +* `n == height.length` +* 2 <= n <= 105 +* 0 <= height[i] <= 104 \ No newline at end of file diff --git a/src/Algorithms/0012.integer-to-roman/integer-to-roman.php b/src/Algorithms/s0012_integer_to_roman/Solution.php similarity index 96% rename from src/Algorithms/0012.integer-to-roman/integer-to-roman.php rename to src/Algorithms/s0012_integer_to_roman/Solution.php index 495e83a..af4f8ea 100644 --- a/src/Algorithms/0012.integer-to-roman/integer-to-roman.php +++ b/src/Algorithms/s0012_integer_to_roman/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param Integer $num - * @return String - */ - function intToRoman($num) { - $sb = ""; - $values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; - $roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; - $i = 0; - - while($num > 0){ - $repeats = intval($num/$values[$i]); - if($repeats >= 1){ - while($repeats != 0){ - $sb .= $roman[$i]; - $repeats--; - } - $num = $num - intval($num/$values[$i])*$values[$i]; - } - $i++; - } - return $sb; - } +class Solution { + + /** + * @param Integer $num + * @return String + */ + function intToRoman($num) { + $sb = ""; + $values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; + $roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; + $i = 0; + + while($num > 0){ + $repeats = intval($num/$values[$i]); + if($repeats >= 1){ + while($repeats != 0){ + $sb .= $roman[$i]; + $repeats--; + } + $num = $num - intval($num/$values[$i])*$values[$i]; + } + $i++; + } + return $sb; + } } \ No newline at end of file diff --git a/src/Algorithms/s0012_integer_to_roman/readme.md b/src/Algorithms/s0012_integer_to_roman/readme.md new file mode 100644 index 0000000..456e0cf --- /dev/null +++ b/src/Algorithms/s0012_integer_to_roman/readme.md @@ -0,0 +1,62 @@ +12\. Integer to Roman + +Medium + +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + + Symbol Value + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1000 + +For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: + +* `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. +* `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. +* `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. + +Given an integer, convert it to a roman numeral. + +**Example 1:** + +**Input:** num = 3 + +**Output:** "III" + +**Example 2:** + +**Input:** num = 4 + +**Output:** "IV" + +**Example 3:** + +**Input:** num = 9 + +**Output:** "IX" + +**Example 4:** + +**Input:** num = 58 + +**Output:** "LVIII" + +**Explanation:** L = 50, V = 5, III = 3. + +**Example 5:** + +**Input:** num = 1994 + +**Output:** "MCMXCIV" + +**Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. + +**Constraints:** + +* `1 <= num <= 3999` diff --git a/src/Algorithms/0013.roman-to-integer/roman-to-integer.php b/src/Algorithms/s0013_roman_to_integer/Solution.php similarity index 95% rename from src/Algorithms/0013.roman-to-integer/roman-to-integer.php rename to src/Algorithms/s0013_roman_to_integer/Solution.php index f622c92..0acda30 100644 --- a/src/Algorithms/0013.roman-to-integer/roman-to-integer.php +++ b/src/Algorithms/s0013_roman_to_integer/Solution.php @@ -1,36 +1,36 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function romanToInt($s) { - $map = [ - 'I' => 1, - 'V' => 5, - 'X' => 10, - 'L' => 50, - 'C' => 100, - 'D' => 500, - 'M' => 1000]; - - $result = 0; - for($i = 0; $i < strlen($s); $i++) { - $first = $map[$s[$i]]; - if($i <= strlen($s) - 2) { - $second = $map[$s[$i + 1]]; - if($second > $first) { - $result += $second - $first; - $i++; - } - else { - $result += $first; - } - } - else - $result += $first; - } - - return $result; - } +class Solution { + + /** + * @param String $s + * @return Integer + */ + function romanToInt($s) { + $map = [ + 'I' => 1, + 'V' => 5, + 'X' => 10, + 'L' => 50, + 'C' => 100, + 'D' => 500, + 'M' => 1000]; + + $result = 0; + for($i = 0; $i < strlen($s); $i++) { + $first = $map[$s[$i]]; + if($i <= strlen($s) - 2) { + $second = $map[$s[$i + 1]]; + if($second > $first) { + $result += $second - $first; + $i++; + } + else { + $result += $first; + } + } + else + $result += $first; + } + + return $result; + } } \ No newline at end of file diff --git a/src/Algorithms/s0013_roman_to_integer/readme.md b/src/Algorithms/s0013_roman_to_integer/readme.md new file mode 100644 index 0000000..14bbde8 --- /dev/null +++ b/src/Algorithms/s0013_roman_to_integer/readme.md @@ -0,0 +1,64 @@ +13\. Roman to Integer + +Easy + +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + + Symbol Value + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1000 + +For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: + +* `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. +* `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. +* `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. + +Given a roman numeral, convert it to an integer. + +**Example 1:** + +**Input:** s = "III" + +**Output:** 3 + +**Example 2:** + +**Input:** s = "IV" + +**Output:** 4 + +**Example 3:** + +**Input:** s = "IX" + +**Output:** 9 + +**Example 4:** + +**Input:** s = "LVIII" + +**Output:** 58 + +**Explanation:** L = 50, V= 5, III = 3. + +**Example 5:** + +**Input:** s = "MCMXCIV" + +**Output:** 1994 + +**Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. + +**Constraints:** + +* `1 <= s.length <= 15` +* `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`. +* It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`. diff --git a/src/Algorithms/0014.longest-common-prefix/longest-common-prefix.php b/src/Algorithms/s0014_longest_common_prefix/Solution.php similarity index 96% rename from src/Algorithms/0014.longest-common-prefix/longest-common-prefix.php rename to src/Algorithms/s0014_longest_common_prefix/Solution.php index a982730..9779c7f 100644 --- a/src/Algorithms/0014.longest-common-prefix/longest-common-prefix.php +++ b/src/Algorithms/s0014_longest_common_prefix/Solution.php @@ -1,39 +1,39 @@ -class Solution { - - /** - * @param String[] $strs - * @return String - */ - function longestCommonPrefix($strs) { - if ($strs == null || count($strs) == 0) - return ""; - $minLen = 2147483647; - foreach ($strs as $str) { - $minLen = min($minLen, strlen($str)); - } - $low = 1; - $high = $minLen; - while ($low <= $high) { - $middle = intval(($low + $high) / 2); - if (self::isCommonPrefix($strs, $middle)) - $low = $middle + 1; - else - $high = $middle - 1; - } - return substr($strs[0], 0, intval(($low + $high) / 2)); - } - - function isCommonPrefix($strs, $len){ - $str1 = substr($strs[0], 0, $len); - for ($i = 1; $i < count($strs); $i++) { - if (!self::startsWith($strs[$i], $str1)) { - return false; - } - } - return true; - } - - function startsWith($haystack, $needle) { - return strncmp($haystack, $needle, strlen($needle)) === 0; - } -} +class Solution { + + /** + * @param String[] $strs + * @return String + */ + function longestCommonPrefix($strs) { + if ($strs == null || count($strs) == 0) + return ""; + $minLen = 2147483647; + foreach ($strs as $str) { + $minLen = min($minLen, strlen($str)); + } + $low = 1; + $high = $minLen; + while ($low <= $high) { + $middle = intval(($low + $high) / 2); + if (self::isCommonPrefix($strs, $middle)) + $low = $middle + 1; + else + $high = $middle - 1; + } + return substr($strs[0], 0, intval(($low + $high) / 2)); + } + + function isCommonPrefix($strs, $len){ + $str1 = substr($strs[0], 0, $len); + for ($i = 1; $i < count($strs); $i++) { + if (!self::startsWith($strs[$i], $str1)) { + return false; + } + } + return true; + } + + function startsWith($haystack, $needle) { + return strncmp($haystack, $needle, strlen($needle)) === 0; + } +} diff --git a/src/Algorithms/s0014_longest_common_prefix/readme.md b/src/Algorithms/s0014_longest_common_prefix/readme.md new file mode 100644 index 0000000..3f23b8c --- /dev/null +++ b/src/Algorithms/s0014_longest_common_prefix/readme.md @@ -0,0 +1,27 @@ +14\. Longest Common Prefix + +Easy + +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string `""`. + +**Example 1:** + +**Input:** strs = ["flower","flow","flight"] + +**Output:** "fl" + +**Example 2:** + +**Input:** strs = ["dog","racecar","car"] + +**Output:** "" + +**Explanation:** There is no common prefix among the input strings. + +**Constraints:** + +* `1 <= strs.length <= 200` +* `0 <= strs[i].length <= 200` +* `strs[i]` consists of only lower-case English letters. \ No newline at end of file diff --git a/src/Algorithms/0015.3sum/3sum.php b/src/Algorithms/s0015_3sum/Solution.php similarity index 96% rename from src/Algorithms/0015.3sum/3sum.php rename to src/Algorithms/s0015_3sum/Solution.php index ba450ff..2214033 100644 --- a/src/Algorithms/0015.3sum/3sum.php +++ b/src/Algorithms/s0015_3sum/Solution.php @@ -1,39 +1,39 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer[][] - */ - function threeSum($nums) { - $res = []; - sort($nums); - $i = 0; $j = 0; $n = count($nums); $k = $n - 1; - if ($k < 2 || $nums[$k] < 0) { - return $res; - } - while ($i < $n - 2) { - if ($nums[$i] > 0) { - break; - } - $target = -$nums[$i]; - $j = $i + 1; - $k = $n - 1; - while ($j < $k) { - if ($nums[$k] < 0) { - break; - } - if ($nums[$j] + $nums[$k] == $target) { - $res[] = [$nums[$i], $nums[$j], $nums[$k]]; - while($j < $k && $nums[$j] == $nums[++$j]); - while($j < $k && $nums[$k] == $nums[--$k]); - } else if ($nums[$j] + $nums[$k] > $target) { - $k--; - } else { - $j++; - } - } - while ($i < $n - 2 && $nums[$i] == $nums[++$i]); - } - return $res; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer[][] + */ + function threeSum($nums) { + $res = []; + sort($nums); + $i = 0; $j = 0; $n = count($nums); $k = $n - 1; + if ($k < 2 || $nums[$k] < 0) { + return $res; + } + while ($i < $n - 2) { + if ($nums[$i] > 0) { + break; + } + $target = -$nums[$i]; + $j = $i + 1; + $k = $n - 1; + while ($j < $k) { + if ($nums[$k] < 0) { + break; + } + if ($nums[$j] + $nums[$k] == $target) { + $res[] = [$nums[$i], $nums[$j], $nums[$k]]; + while($j < $k && $nums[$j] == $nums[++$j]); + while($j < $k && $nums[$k] == $nums[--$k]); + } else if ($nums[$j] + $nums[$k] > $target) { + $k--; + } else { + $j++; + } + } + while ($i < $n - 2 && $nums[$i] == $nums[++$i]); + } + return $res; + } +} diff --git a/src/Algorithms/s0015_3sum/readme.md b/src/Algorithms/s0015_3sum/readme.md new file mode 100644 index 0000000..5a76027 --- /dev/null +++ b/src/Algorithms/s0015_3sum/readme.md @@ -0,0 +1,30 @@ +15\. 3Sum + +Medium + +Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. + +Notice that the solution set must not contain duplicate triplets. + +**Example 1:** + +**Input:** nums = [-1,0,1,2,-1,-4] + +**Output:** [[-1,-1,2],[-1,0,1]] + +**Example 2:** + +**Input:** nums = [] + +**Output:** [] + +**Example 3:** + +**Input:** nums = [0] + +**Output:** [] + +**Constraints:** + +* `0 <= nums.length <= 3000` +* -105 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/Algorithms/0016.3sum-closest/3sum-closest.php b/src/Algorithms/s0016_3sum_closest/Solution.php similarity index 96% rename from src/Algorithms/0016.3sum-closest/3sum-closest.php rename to src/Algorithms/s0016_3sum_closest/Solution.php index d4e3e04..d7c8856 100644 --- a/src/Algorithms/0016.3sum-closest/3sum-closest.php +++ b/src/Algorithms/s0016_3sum_closest/Solution.php @@ -1,35 +1,35 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $target - * @return Integer - */ - function threeSumClosest($nums, $target) { - sort($nums); - $min = 2147483647; - $res = 0; - for($i=2;$i-104 <= target <= 104 \ No newline at end of file diff --git a/src/Algorithms/0017.letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.php b/src/Algorithms/s0017_letter_combinations_of_a_phone_number/Solution.php similarity index 96% rename from src/Algorithms/0017.letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.php rename to src/Algorithms/s0017_letter_combinations_of_a_phone_number/Solution.php index 3f74a18..1e65df9 100644 --- a/src/Algorithms/0017.letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.php +++ b/src/Algorithms/s0017_letter_combinations_of_a_phone_number/Solution.php @@ -1,45 +1,45 @@ -class Solution { - public function __construct() { - $this->phone = [ - "2" => "abc", - "3" => "def", - "4" => "ghi", - "5" => "jkl", - "6" => "mno", - "7" => "pqrs", - "8" => "tuv", - "9" => "wxyz" - ]; - $this->output = []; - } - - function backtrack($combination, $next_digits) { - // if there is no more digits to check - if (strlen($next_digits) == 0) { - // the combination is done - array_push($this->output, $combination); - } - // if there are still digits to check - else { - // iterate over all letters which map - // the next available digit - $digit = substr($next_digits, 0, 1); - $letters = $this->phone[$digit]; - for ($i = 0; $i < strlen($letters); $i++) { - $letter = substr($this->phone[$digit], $i, 1); - // append the current letter to the combination - // and proceed to the next digits - self::backtrack($combination . $letter, substr($next_digits, 1)); - } - } - } - /** - * @param String $digits - * @return String[] - */ - function letterCombinations($digits) { - if (strlen($digits) != 0) - self::backtrack("", $digits); - return $this->output; - } -} +class Solution { + public function __construct() { + $this->phone = [ + "2" => "abc", + "3" => "def", + "4" => "ghi", + "5" => "jkl", + "6" => "mno", + "7" => "pqrs", + "8" => "tuv", + "9" => "wxyz" + ]; + $this->output = []; + } + + function backtrack($combination, $next_digits) { + // if there is no more digits to check + if (strlen($next_digits) == 0) { + // the combination is done + array_push($this->output, $combination); + } + // if there are still digits to check + else { + // iterate over all letters which map + // the next available digit + $digit = substr($next_digits, 0, 1); + $letters = $this->phone[$digit]; + for ($i = 0; $i < strlen($letters); $i++) { + $letter = substr($this->phone[$digit], $i, 1); + // append the current letter to the combination + // and proceed to the next digits + self::backtrack($combination . $letter, substr($next_digits, 1)); + } + } + } + /** + * @param String $digits + * @return String[] + */ + function letterCombinations($digits) { + if (strlen($digits) != 0) + self::backtrack("", $digits); + return $this->output; + } +} diff --git a/src/Algorithms/s0017_letter_combinations_of_a_phone_number/readme.md b/src/Algorithms/s0017_letter_combinations_of_a_phone_number/readme.md new file mode 100644 index 0000000..eb7480d --- /dev/null +++ b/src/Algorithms/s0017_letter_combinations_of_a_phone_number/readme.md @@ -0,0 +1,32 @@ +17\. Letter Combinations of a Phone Number + +Medium + +Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. + +A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. + +![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png) + +**Example 1:** + +**Input:** digits = "23" + +**Output:** ["ad","ae","af","bd","be","bf","cd","ce","cf"] + +**Example 2:** + +**Input:** digits = "" + +**Output:** [] + +**Example 3:** + +**Input:** digits = "2" + +**Output:** ["a","b","c"] + +**Constraints:** + +* `0 <= digits.length <= 4` +* `digits[i]` is a digit in the range `['2', '9']`. \ No newline at end of file diff --git a/src/Algorithms/0018.4sum/4sum.php b/src/Algorithms/s0018_4sum/Solution.php similarity index 96% rename from src/Algorithms/0018.4sum/4sum.php rename to src/Algorithms/s0018_4sum/Solution.php index d428be2..791a357 100644 --- a/src/Algorithms/0018.4sum/4sum.php +++ b/src/Algorithms/s0018_4sum/Solution.php @@ -1,55 +1,55 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $target - * @return Integer[][] - */ - function fourSum($nums, $target) { - $result = []; - sort($nums); - $sum = 0; - - for($i=0;$i$target){ - $l--; - } - else - $k++; - } - } - } - - - return $result; - } +class Solution { + + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer[][] + */ + function fourSum($nums, $target) { + $result = []; + sort($nums); + $sum = 0; + + for($i=0;$i$target){ + $l--; + } + else + $k++; + } + } + } + + + return $result; + } } diff --git a/src/Algorithms/s0018_4sum/readme.md b/src/Algorithms/s0018_4sum/readme.md new file mode 100644 index 0000000..ecf88ad --- /dev/null +++ b/src/Algorithms/s0018_4sum/readme.md @@ -0,0 +1,29 @@ +18\. 4Sum + +Medium + +Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that: + +* `0 <= a, b, c, d < n` +* `a`, `b`, `c`, and `d` are **distinct**. +* `nums[a] + nums[b] + nums[c] + nums[d] == target` + +You may return the answer in **any order**. + +**Example 1:** + +**Input:** nums = [1,0,-1,0,-2,2], target = 0 + +**Output:** [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] + +**Example 2:** + +**Input:** nums = [2,2,2,2,2], target = 8 + +**Output:** [[2,2,2,2]] + +**Constraints:** + +* `1 <= nums.length <= 200` +* -109 <= nums[i] <= 109 +* -109 <= target <= 109 \ No newline at end of file diff --git a/src/Algorithms/0019.remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.php b/src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php similarity index 95% rename from src/Algorithms/0019.remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.php rename to src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php index db209e2..688eb18 100644 --- a/src/Algorithms/0019.remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.php +++ b/src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php @@ -1,47 +1,47 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @param Integer $n - * @return ListNode - */ - function removeNthFromEnd($head, $n) { - $list = []; - $size = 1; - $a = $head; - - while($a->next != null){ - $list[] = $a; - $a=$a->next; - $size++; - } - $list[] = $a; - - $c = null; - - if($size==1){ - return $c; - } - if($size==$n){ - $head=$head->next; - return $head; - } - - $b=$list[$size-$n-1]; - - if($b->next->next == null) - $b->next=null; - else - $b->next=$b->next->next; - - return $head; - } +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @param Integer $n + * @return ListNode + */ + function removeNthFromEnd($head, $n) { + $list = []; + $size = 1; + $a = $head; + + while($a->next != null){ + $list[] = $a; + $a=$a->next; + $size++; + } + $list[] = $a; + + $c = null; + + if($size==1){ + return $c; + } + if($size==$n){ + $head=$head->next; + return $head; + } + + $b=$list[$size-$n-1]; + + if($b->next->next == null) + $b->next=null; + else + $b->next=$b->next->next; + + return $head; + } } \ No newline at end of file diff --git a/src/Algorithms/s0019_remove_nth_node_from_end_of_list/readme.md b/src/Algorithms/s0019_remove_nth_node_from_end_of_list/readme.md new file mode 100644 index 0000000..f2d135d --- /dev/null +++ b/src/Algorithms/s0019_remove_nth_node_from_end_of_list/readme.md @@ -0,0 +1,34 @@ +19\. Remove Nth Node From End of List + +Medium + +Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg) + +**Input:** head = [1,2,3,4,5], n = 2 + +**Output:** [1,2,3,5] + +**Example 2:** + +**Input:** head = [1], n = 1 + +**Output:** [] + +**Example 3:** + +**Input:** head = [1,2], n = 1 + +**Output:** [1] + +**Constraints:** + +* The number of nodes in the list is `sz`. +* `1 <= sz <= 30` +* `0 <= Node.val <= 100` +* `1 <= n <= sz` + +**Follow up:** Could you do this in one pass? \ No newline at end of file diff --git a/src/Algorithms/0020.valid-parentheses/valid-parentheses.php b/src/Algorithms/s0020_valid_parentheses/Solution.php similarity index 96% rename from src/Algorithms/0020.valid-parentheses/valid-parentheses.php rename to src/Algorithms/s0020_valid_parentheses/Solution.php index 4a39e75..58ef5b5 100644 --- a/src/Algorithms/0020.valid-parentheses/valid-parentheses.php +++ b/src/Algorithms/s0020_valid_parentheses/Solution.php @@ -1,36 +1,36 @@ -class Solution { - - /** - * @param String $s - * @return Boolean - */ - function isValid($s) { - $toClose=array_fill(0, strlen($s)>>1); - $open=0; - try{ - for($i=0; $i>1); + $open=0; + try{ + for($i=0; $i1 <= s.length <= 104 +* `s` consists of parentheses only `'()[]{}'`. \ No newline at end of file diff --git a/src/Algorithms/0021.merge-two-sorted-lists/merge-two-sorted-lists.php b/src/Algorithms/s0021_merge_two_sorted_lists/Solution.php similarity index 96% rename from src/Algorithms/0021.merge-two-sorted-lists/merge-two-sorted-lists.php rename to src/Algorithms/s0021_merge_two_sorted_lists/Solution.php index b87b24a..a5f7def 100644 --- a/src/Algorithms/0021.merge-two-sorted-lists/merge-two-sorted-lists.php +++ b/src/Algorithms/s0021_merge_two_sorted_lists/Solution.php @@ -1,40 +1,40 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $l1 - * @param ListNode $l2 - * @return ListNode - */ - function mergeTwoLists($l1, $l2) { - $res = new ListNode(0); - $cur = $res; - while ($l1 != null || $l2 != null) { - if ($l1 == null) { - $cur->next = new ListNode($l2->val); - $l2 = $l2->next; - } else if ($l2 == null) { - $cur->next = new ListNode($l1->val); - $l1 = $l1->next; - } else { - if ($l1->val < $l2->val) { - $cur->next = new ListNode($l1->val); - $l1 = $l1->next; - } else { - $cur->next = new ListNode($l2->val); - $l2 = $l2->next; - } - } - $cur = $cur->next; - } - - return $res->next; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $l1 + * @param ListNode $l2 + * @return ListNode + */ + function mergeTwoLists($l1, $l2) { + $res = new ListNode(0); + $cur = $res; + while ($l1 != null || $l2 != null) { + if ($l1 == null) { + $cur->next = new ListNode($l2->val); + $l2 = $l2->next; + } else if ($l2 == null) { + $cur->next = new ListNode($l1->val); + $l1 = $l1->next; + } else { + if ($l1->val < $l2->val) { + $cur->next = new ListNode($l1->val); + $l1 = $l1->next; + } else { + $cur->next = new ListNode($l2->val); + $l2 = $l2->next; + } + } + $cur = $cur->next; + } + + return $res->next; + } +} diff --git a/src/Algorithms/s0021_merge_two_sorted_lists/readme.md b/src/Algorithms/s0021_merge_two_sorted_lists/readme.md new file mode 100644 index 0000000..91a9f1c --- /dev/null +++ b/src/Algorithms/s0021_merge_two_sorted_lists/readme.md @@ -0,0 +1,31 @@ +21\. Merge Two Sorted Lists + +Easy + +Merge two sorted linked lists and return it as a **sorted** list. The list should be made by splicing together the nodes of the first two lists. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg) + +**Input:** l1 = [1,2,4], l2 = [1,3,4] + +**Output:** [1,1,2,3,4,4] + +**Example 2:** + +**Input:** l1 = [], l2 = [] + +**Output:** [] + +**Example 3:** + +**Input:** l1 = [], l2 = [0] + +**Output:** [0] + +**Constraints:** + +* The number of nodes in both lists is in the range `[0, 50]`. +* `-100 <= Node.val <= 100` +* Both `l1` and `l2` are sorted in **non-decreasing** order. \ No newline at end of file diff --git a/src/Algorithms/0022.generate-parentheses/generate-parentheses.php b/src/Algorithms/s0022_generate_parentheses/Solution.php similarity index 96% rename from src/Algorithms/0022.generate-parentheses/generate-parentheses.php rename to src/Algorithms/s0022_generate_parentheses/Solution.php index cc467ab..04cb18a 100644 --- a/src/Algorithms/0022.generate-parentheses/generate-parentheses.php +++ b/src/Algorithms/s0022_generate_parentheses/Solution.php @@ -1,27 +1,27 @@ -class Solution { - - var $list = []; - - function internal($s, $remainLeft, $remainRight) { - if ($remainRight == 0) { - $this->list[] = $s; - return; - } - if ($remainLeft == 0) self::internal($s . ')', 0, $remainRight - 1); - else if ($remainLeft == $remainRight) { - self::internal($s . "(", $remainLeft - 1, $remainRight); - } else if ($remainRight > $remainLeft) { - self::internal($s . "(", $remainLeft - 1, $remainRight); - self::internal($s . ')', $remainLeft, $remainRight - 1); - } - } - - /** - * @param Integer $n - * @return String[] - */ - function generateParenthesis($n) { - self::internal("", $n, $n); - return $this->list; - } -} +class Solution { + + var $list = []; + + function internal($s, $remainLeft, $remainRight) { + if ($remainRight == 0) { + $this->list[] = $s; + return; + } + if ($remainLeft == 0) self::internal($s . ')', 0, $remainRight - 1); + else if ($remainLeft == $remainRight) { + self::internal($s . "(", $remainLeft - 1, $remainRight); + } else if ($remainRight > $remainLeft) { + self::internal($s . "(", $remainLeft - 1, $remainRight); + self::internal($s . ')', $remainLeft, $remainRight - 1); + } + } + + /** + * @param Integer $n + * @return String[] + */ + function generateParenthesis($n) { + self::internal("", $n, $n); + return $this->list; + } +} diff --git a/src/Algorithms/s0022_generate_parentheses/readme.md b/src/Algorithms/s0022_generate_parentheses/readme.md new file mode 100644 index 0000000..72cab17 --- /dev/null +++ b/src/Algorithms/s0022_generate_parentheses/readme.md @@ -0,0 +1,21 @@ +22\. Generate Parentheses + +Medium + +Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_. + +**Example 1:** + +**Input:** n = 3 + +**Output:** ["((()))","(()())","(())()","()(())","()()()"] + +**Example 2:** + +**Input:** n = 1 + +**Output:** ["()"] + +**Constraints:** + +* `1 <= n <= 8` \ No newline at end of file diff --git a/src/Algorithms/0023.merge-k-sorted-lists/merge-k-sorted-lists.php b/src/Algorithms/s0023_merge_k_sorted_lists/Solution.php similarity index 96% rename from src/Algorithms/0023.merge-k-sorted-lists/merge-k-sorted-lists.php rename to src/Algorithms/s0023_merge_k_sorted_lists/Solution.php index 0845d09..e9c0dd7 100644 --- a/src/Algorithms/0023.merge-k-sorted-lists/merge-k-sorted-lists.php +++ b/src/Algorithms/s0023_merge_k_sorted_lists/Solution.php @@ -1,47 +1,47 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode[] $lists - * @return ListNode - */ - function mergeKLists($lists) { - if(count($lists) == 0) { - return null; - } - $l = null; - for($i = 0; $i < count($lists); ++$i) { - $l = self::mergeTwoLists($l, $lists[$i]); - } - return $l; - } - // AC in LeetCode-23 Merge Two Sorted Lists - function mergeTwoLists($l1, $l2) { - if($l1 == null) { - return $l2; - } else if($l2 == null) { - return $l1; - } - - $head = new ListNode(-1); - $cur = $head; - while($l1 != null && $l2 != null) { - $cur->next = $l1->val <= $l2->val ? $l1 : $l2; - $cur = $cur->next; - if($cur->val == $l1->val) { - $l1 = $l1->next; - } else { - $l2 = $l2->next; - } - } - $cur->next = $l1 != null ? $l1 : $l2; - return $head->next; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode[] $lists + * @return ListNode + */ + function mergeKLists($lists) { + if(count($lists) == 0) { + return null; + } + $l = null; + for($i = 0; $i < count($lists); ++$i) { + $l = self::mergeTwoLists($l, $lists[$i]); + } + return $l; + } + // AC in LeetCode-23 Merge Two Sorted Lists + function mergeTwoLists($l1, $l2) { + if($l1 == null) { + return $l2; + } else if($l2 == null) { + return $l1; + } + + $head = new ListNode(-1); + $cur = $head; + while($l1 != null && $l2 != null) { + $cur->next = $l1->val <= $l2->val ? $l1 : $l2; + $cur = $cur->next; + if($cur->val == $l1->val) { + $l1 = $l1->next; + } else { + $l2 = $l2->next; + } + } + $cur->next = $l1 != null ? $l1 : $l2; + return $head->next; + } +} diff --git a/src/Algorithms/s0023_merge_k_sorted_lists/readme.md b/src/Algorithms/s0023_merge_k_sorted_lists/readme.md new file mode 100644 index 0000000..f7a1b18 --- /dev/null +++ b/src/Algorithms/s0023_merge_k_sorted_lists/readme.md @@ -0,0 +1,36 @@ +23\. Merge k Sorted Lists + +Hard + +You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. + +_Merge all the linked-lists into one sorted linked-list and return it._ + +**Example 1:** + +**Input:** lists = [[1,4,5],[1,3,4],[2,6]] + +**Output:** [1,1,2,3,4,4,5,6] + +**Explanation:** The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 + +**Example 2:** + +**Input:** lists = [] + +**Output:** [] + +**Example 3:** + +**Input:** lists = [[]] + +**Output:** [] + +**Constraints:** + +* `k == lists.length` +* `0 <= k <= 10^4` +* `0 <= lists[i].length <= 500` +* `-10^4 <= lists[i][j] <= 10^4` +* `lists[i]` is sorted in **ascending order**. +* The sum of `lists[i].length` won't exceed `10^4`. \ No newline at end of file diff --git a/src/Algorithms/0024.swap-nodes-in-pairs/swap-nodes-in-pairs.php b/src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php similarity index 95% rename from src/Algorithms/0024.swap-nodes-in-pairs/swap-nodes-in-pairs.php rename to src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php index 652451c..96672b7 100644 --- a/src/Algorithms/0024.swap-nodes-in-pairs/swap-nodes-in-pairs.php +++ b/src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php @@ -1,27 +1,27 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @return ListNode - */ - function swapPairs($head) { - $cur = $head; - while ($cur != null && $cur->next != null){ - - $temp = $cur->val; - $cur->val = $cur->next->val; - $cur->next->val = $temp; - $cur = $cur->next->next; - } - - return $head; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @return ListNode + */ + function swapPairs($head) { + $cur = $head; + while ($cur != null && $cur->next != null){ + + $temp = $cur->val; + $cur->val = $cur->next->val; + $cur->next->val = $temp; + $cur = $cur->next->next; + } + + return $head; + } +} diff --git a/src/Algorithms/s0024_swap_nodes_in_pairs/readme.md b/src/Algorithms/s0024_swap_nodes_in_pairs/readme.md new file mode 100644 index 0000000..0bac19e --- /dev/null +++ b/src/Algorithms/s0024_swap_nodes_in_pairs/readme.md @@ -0,0 +1,30 @@ +24\. Swap Nodes in Pairs + +Medium + +Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg) + +**Input:** head = [1,2,3,4] + +**Output:** [2,1,4,3] + +**Example 2:** + +**Input:** head = [] + +**Output:** [] + +**Example 3:** + +**Input:** head = [1] + +**Output:** [1] + +**Constraints:** + +* The number of nodes in the list is in the range `[0, 100]`. +* `0 <= Node.val <= 100` \ No newline at end of file diff --git a/src/Algorithms/0025.reverse-nodes-in-k-group/reverse-nodes-in-k-group.php b/src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php similarity index 95% rename from src/Algorithms/0025.reverse-nodes-in-k-group/reverse-nodes-in-k-group.php rename to src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php index 8bf3351..78a08d3 100644 --- a/src/Algorithms/0025.reverse-nodes-in-k-group/reverse-nodes-in-k-group.php +++ b/src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php @@ -1,49 +1,49 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @param Integer $k - * @return ListNode - */ - function reverseKGroup($head, $k) { - if($head==null || $k<2){ - return $head; - } - - $temp = null; - $curr = $head; - $prev = null; - $count = 0; - - while($count<$k && $curr!=null){ - $temp = $curr->next; - $curr->next = $prev; - $prev = $curr; - $curr = $temp; - $count++; - } - - if($count<$k){ - while($count!=0){ - $temp = $prev->next; - $prev->next = $curr; - $curr = $prev; - $prev = $temp; - $count--; - } - return $curr; - } - - $head->next = self::reverseKGroup($curr,$k); - - return $prev; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @param Integer $k + * @return ListNode + */ + function reverseKGroup($head, $k) { + if($head==null || $k<2){ + return $head; + } + + $temp = null; + $curr = $head; + $prev = null; + $count = 0; + + while($count<$k && $curr!=null){ + $temp = $curr->next; + $curr->next = $prev; + $prev = $curr; + $curr = $temp; + $count++; + } + + if($count<$k){ + while($count!=0){ + $temp = $prev->next; + $prev->next = $curr; + $curr = $prev; + $prev = $temp; + $count--; + } + return $curr; + } + + $head->next = self::reverseKGroup($curr,$k); + + return $prev; + } +} diff --git a/src/Algorithms/s0025_reverse_nodes_in_k_group/readme.md b/src/Algorithms/s0025_reverse_nodes_in_k_group/readme.md new file mode 100644 index 0000000..3583098 --- /dev/null +++ b/src/Algorithms/s0025_reverse_nodes_in_k_group/readme.md @@ -0,0 +1,46 @@ +25\. Reverse Nodes in k-Group + +Hard + +Given a linked list, reverse the nodes of a linked list _k_ at a time and return its modified list. + +_k_ is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of _k_ then left-out nodes, in the end, should remain as it is. + +You may not alter the values in the list's nodes, only nodes themselves may be changed. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg) + +**Input:** head = [1,2,3,4,5], k = 2 + +**Output:** [2,1,4,3,5] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg) + +**Input:** head = [1,2,3,4,5], k = 3 + +**Output:** [3,2,1,4,5] + +**Example 3:** + +**Input:** head = [1,2,3,4,5], k = 1 + +**Output:** [1,2,3,4,5] + +**Example 4:** + +**Input:** head = [1], k = 1 + +**Output:** [1] + +**Constraints:** + +* The number of nodes in the list is in the range `sz`. +* `1 <= sz <= 5000` +* `0 <= Node.val <= 1000` +* `1 <= k <= sz` + +**Follow-up:** Can you solve the problem in O(1) extra memory space? \ No newline at end of file diff --git a/src/Algorithms/0026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.php b/src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php similarity index 94% rename from src/Algorithms/0026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.php rename to src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php index 7e76239..33d8698 100644 --- a/src/Algorithms/0026.remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.php +++ b/src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function removeDuplicates(&$nums) { - if (count($nums) < 2) - return count($nums); - - $j = 0; - $i = 1; - - while ($i < count($nums)) { - if ($nums[$i] == $nums[$j]) { - $i++; - } else { - $j++; - $nums[$j] = $nums[$i]; - $i++; - } - } - - return $j + 1; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function removeDuplicates(&$nums) { + if (count($nums) < 2) + return count($nums); + + $j = 0; + $i = 1; + + while ($i < count($nums)) { + if ($nums[$i] == $nums[$j]) { + $i++; + } else { + $j++; + $nums[$j] = $nums[$i]; + $i++; + } + } + + return $j + 1; + } +} diff --git a/src/Algorithms/s0026_remove_duplicates_from_sorted_array/readme.md b/src/Algorithms/s0026_remove_duplicates_from_sorted_array/readme.md new file mode 100644 index 0000000..b4e776e --- /dev/null +++ b/src/Algorithms/s0026_remove_duplicates_from_sorted_array/readme.md @@ -0,0 +1,49 @@ +26\. Remove Duplicates from Sorted Array + +Easy + +Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. + +Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. + +Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. + +Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. + +**Custom Judge:** + +The judge will test your solution with the following code: + + int[] nums = [...]; // Input array + int[] expectedNums = [...]; // The expected answer with correct length + + int k = removeDuplicates(nums); // Calls your implementation + + assert k == expectedNums.length; + for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; + } + +If all assertions pass, then your solution will be **accepted**. + +**Example 1:** + +**Input:** nums = [1,1,2] + +**Output:** 2, nums = [1,2,\_] + +**Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). + +**Example 2:** + +**Input:** nums = [0,0,1,1,1,2,2,3,3,4] + +**Output:** 5, nums = [0,1,2,3,4,\_,\_,\_,\_,\_] + +**Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). + +**Constraints:** + +* 0 <= nums.length <= 3 * 104 +* `-100 <= nums[i] <= 100` +* `nums` is sorted in **non-decreasing** order. \ No newline at end of file diff --git a/src/Algorithms/0027.remove-element/remove-element.php b/src/Algorithms/s0027_remove_element/Solution.php similarity index 95% rename from src/Algorithms/0027.remove-element/remove-element.php rename to src/Algorithms/s0027_remove_element/Solution.php index 614bbb2..e8d04b1 100644 --- a/src/Algorithms/0027.remove-element/remove-element.php +++ b/src/Algorithms/s0027_remove_element/Solution.php @@ -1,19 +1,19 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $val - * @return Integer - */ - function removeElement(&$nums, $val) { - $start = 0; - for($i = 0; $i < count($nums); $i++){ - if($nums[$i] != $val){ - $nums[$start] = $nums[$i]; - $start++; - } - } - - return $start; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @param Integer $val + * @return Integer + */ + function removeElement(&$nums, $val) { + $start = 0; + for($i = 0; $i < count($nums); $i++){ + if($nums[$i] != $val){ + $nums[$start] = $nums[$i]; + $start++; + } + } + + return $start; + } +} diff --git a/src/Algorithms/s0027_remove_element/readme.md b/src/Algorithms/s0027_remove_element/readme.md new file mode 100644 index 0000000..027b058 --- /dev/null +++ b/src/Algorithms/s0027_remove_element/readme.md @@ -0,0 +1,52 @@ +27\. Remove Element + +Easy + +Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The relative order of the elements may be changed. + +Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. + +Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. + +Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. + +**Custom Judge:** + +The judge will test your solution with the following code: + + int[] nums = [...]; // Input array + int val = ...; // Value to remove + int[] expectedNums = [...]; // The expected answer with correct length. + // It is sorted with no values equaling val. + + int k = removeElement(nums, val); // Calls your implementation + + assert k == expectedNums.length; + sort(nums, 0, k); // Sort the first k elements of nums + for (int i = 0; i < actualLength; i++) { + assert nums[i] == expectedNums[i]; + } + +If all assertions pass, then your solution will be **accepted**. + +**Example 1:** + +**Input:** nums = [3,2,2,3], val = 3 + +**Output:** 2, nums = [2,2,\_,\_] + +**Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). + +**Example 2:** + +**Input:** nums = [0,1,2,2,3,0,4,2], val = 2 + +**Output:** 5, nums = [0,1,4,0,3,\_,\_,\_] + +**Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). + +**Constraints:** + +* `0 <= nums.length <= 100` +* `0 <= nums[i] <= 50` +* `0 <= val <= 100` \ No newline at end of file diff --git a/src/Algorithms/0028.implement-strstr/implement-strstr.php b/src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/Solution.php similarity index 96% rename from src/Algorithms/0028.implement-strstr/implement-strstr.php rename to src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/Solution.php index b3ecb4d..ca51bc3 100644 --- a/src/Algorithms/0028.implement-strstr/implement-strstr.php +++ b/src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/Solution.php @@ -1,24 +1,24 @@ -class Solution { - - /** - * @param String $haystack - * @param String $needle - * @return Integer - */ - function strStr($haystack, $needle) { - if(strlen($needle) == 0) return 0; - if(strlen($haystack) == 0) return -1; - if(strlen($haystack) == 1 && strlen($needle) == 1){ - if($haystack[0] == $needle[0]){ - return 0; - } - } - - for($i = 0; $i < strlen($haystack) - strlen($needle) + 1; $i++){ - if($needle === substr($haystack, $i, strlen($needle))){ - return $i; - } - } - return -1; - } -} +class Solution { + + /** + * @param String $haystack + * @param String $needle + * @return Integer + */ + function strStr($haystack, $needle) { + if(strlen($needle) == 0) return 0; + if(strlen($haystack) == 0) return -1; + if(strlen($haystack) == 1 && strlen($needle) == 1){ + if($haystack[0] == $needle[0]){ + return 0; + } + } + + for($i = 0; $i < strlen($haystack) - strlen($needle) + 1; $i++){ + if($needle === substr($haystack, $i, strlen($needle))){ + return $i; + } + } + return -1; + } +} diff --git a/src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md b/src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md new file mode 100644 index 0000000..098bd24 --- /dev/null +++ b/src/Algorithms/s0028_find_the_index_of_the_first_occurrence_in_a_string/readme.md @@ -0,0 +1,36 @@ +28\. Implement strStr() + +Easy + +Implement [strStr()](http://www.cplusplus.com/reference/cstring/strstr/). + +Return the index of the first occurrence of needle in haystack, or `-1` if `needle` is not part of `haystack`. + +**Clarification:** + +What should we return when `needle` is an empty string? This is a great question to ask during an interview. + +For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's [strstr()](http://www.cplusplus.com/reference/cstring/strstr/) and Java's [indexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)). + +**Example 1:** + +**Input:** haystack = "hello", needle = "ll" + +**Output:** 2 + +**Example 2:** + +**Input:** haystack = "aaaaa", needle = "bba" + +**Output:** -1 + +**Example 3:** + +**Input:** haystack = "", needle = "" + +**Output:** 0 + +**Constraints:** + +* 0 <= haystack.length, needle.length <= 5 * 104 +* `haystack` and `needle` consist of only lower-case English characters. \ No newline at end of file diff --git a/src/Algorithms/0029.divide-two-integers/divide-two-integers.php b/src/Algorithms/s0029_divide_two_integers/Solution.php similarity index 96% rename from src/Algorithms/0029.divide-two-integers/divide-two-integers.php rename to src/Algorithms/s0029_divide_two_integers/Solution.php index 43586d2..fa27581 100644 --- a/src/Algorithms/0029.divide-two-integers/divide-two-integers.php +++ b/src/Algorithms/s0029_divide_two_integers/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param Integer $dividend - * @param Integer $divisor - * @return Integer - */ - function divide($dividend, $divisor) { - if ($dividend == -2147483648 && $divisor == -1) return 2147483647; - if (abs($divisor) == 1) { - if ($divisor > 0) return $dividend; - else return -$dividend; - } - $l1 = abs($dividend); $l2 = abs($divisor); - $sol = 0; - while($l1 >= $l2){ - $x = $l2; $y = 1; - while($l1 >= $x){ - $l1-=$x; - $sol+=$y; - $y+=$y; - $x+=$x; - } - } - if ($dividend > 0 && $divisor < 0 || $dividend<0 && $divisor>0) $sol = -$sol; - return $sol; - } -} +class Solution { + + /** + * @param Integer $dividend + * @param Integer $divisor + * @return Integer + */ + function divide($dividend, $divisor) { + if ($dividend == -2147483648 && $divisor == -1) return 2147483647; + if (abs($divisor) == 1) { + if ($divisor > 0) return $dividend; + else return -$dividend; + } + $l1 = abs($dividend); $l2 = abs($divisor); + $sol = 0; + while($l1 >= $l2){ + $x = $l2; $y = 1; + while($l1 >= $x){ + $l1-=$x; + $sol+=$y; + $y+=$y; + $x+=$x; + } + } + if ($dividend > 0 && $divisor < 0 || $dividend<0 && $divisor>0) $sol = -$sol; + return $sol; + } +} diff --git a/src/Algorithms/s0029_divide_two_integers/readme.md b/src/Algorithms/s0029_divide_two_integers/readme.md new file mode 100644 index 0000000..0d3aa2f --- /dev/null +++ b/src/Algorithms/s0029_divide_two_integers/readme.md @@ -0,0 +1,44 @@ +29\. Divide Two Integers + +Medium + +Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator. + +The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`. + +Return _the **quotient** after dividing_ `dividend` _by_ `divisor`. + +**Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: [−231, 231 − 1]. For this problem, if the quotient is **strictly greater than** [231 − 1], then return [231 − 1], and if the quotient is **strictly less than** [-231 − 1], then return [-231 − 1]. + +**Example 1:** + +**Input:** dividend = 10, divisor = 3 + +**Output:** 3 + +**Explanation:** 10/3 = 3.33333.. which is truncated to 3. + +**Example 2:** + +**Input:** dividend = 7, divisor = -3 + +**Output:** -2 + +**Explanation:** 7/-3 = -2.33333.. which is truncated to -2. + +**Example 3:** + +**Input:** dividend = 0, divisor = 1 + +**Output:** 0 + +**Example 4:** + +**Input:** dividend = 1, divisor = 1 + +**Output:** 1 + +**Constraints:** + +* -231 <= dividend, divisor <= 231 - 1 +* `divisor != 0` diff --git a/src/Algorithms/0030.substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.php b/src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php similarity index 97% rename from src/Algorithms/0030.substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.php rename to src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php index 267b60e..7f07b9f 100644 --- a/src/Algorithms/0030.substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.php +++ b/src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php @@ -1,34 +1,34 @@ -class Solution { - - /** - * @param String $s - * @param String[] $words - * @return Integer[] - */ - function findSubstring($s, $words) { - $sol = []; - if (count($words) == 0 || strlen($words[0]) == 0) return $sol; - $wordLen = strlen($words[0]); $listLen = count($words); $strLen = strlen($s); - $maxIdx = $strLen-$wordLen*$listLen; - if ($maxIdx < 0) return $sol; - $map = []; - foreach ($words as $ss) - $map[$ss] = ($map[$ss] == null ? 0 : $map[$ss]) + 1; - $temp = []; - for ($i = 0; $i < $wordLen; $i++){ - for ($j = $i; $j <= $maxIdx; $j+=$wordLen){ - for ($k = $listLen-1; $k >= 0; $k--){ - $str = substr($s, $k*$wordLen+$j, $wordLen); - $num = ($temp[$str] == null ? 0 : $temp[$str]) + 1; - if ($num > ($map[$str] == null ? 0 : $map[$str])){ - $j+=$k*$wordLen; - break; - }else if ($k == 0) {$sol[] = $j;} - else {$temp[$str] = $num;} - } - $temp = []; - } - } - return $sol; - } -} +class Solution { + + /** + * @param String $s + * @param String[] $words + * @return Integer[] + */ + function findSubstring($s, $words) { + $sol = []; + if (count($words) == 0 || strlen($words[0]) == 0) return $sol; + $wordLen = strlen($words[0]); $listLen = count($words); $strLen = strlen($s); + $maxIdx = $strLen-$wordLen*$listLen; + if ($maxIdx < 0) return $sol; + $map = []; + foreach ($words as $ss) + $map[$ss] = ($map[$ss] == null ? 0 : $map[$ss]) + 1; + $temp = []; + for ($i = 0; $i < $wordLen; $i++){ + for ($j = $i; $j <= $maxIdx; $j+=$wordLen){ + for ($k = $listLen-1; $k >= 0; $k--){ + $str = substr($s, $k*$wordLen+$j, $wordLen); + $num = ($temp[$str] == null ? 0 : $temp[$str]) + 1; + if ($num > ($map[$str] == null ? 0 : $map[$str])){ + $j+=$k*$wordLen; + break; + }else if ($k == 0) {$sol[] = $j;} + else {$temp[$str] = $num;} + } + $temp = []; + } + } + return $sol; + } +} diff --git a/src/Algorithms/s0030_substring_with_concatenation_of_all_words/readme.md b/src/Algorithms/s0030_substring_with_concatenation_of_all_words/readme.md new file mode 100644 index 0000000..e4075f4 --- /dev/null +++ b/src/Algorithms/s0030_substring_with_concatenation_of_all_words/readme.md @@ -0,0 +1,35 @@ +30\. Substring with Concatenation of All Words + +Hard + +You are given a string `s` and an array of strings `words` of **the same length**. Return all starting indices of substring(s) in `s` that is a concatenation of each word in `words` **exactly once**, **in any order**, and **without any intervening characters**. + +You can return the answer in **any order**. + +**Example 1:** + +**Input:** s = "barfoothefoobarman", words = ["foo","bar"] + +**Output:** [0,9] + +**Explanation:** Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively. The output order does not matter, returning [9,0] is fine too. + +**Example 2:** + +**Input:** s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] + +**Output:** [] + +**Example 3:** + +**Input:** s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] + +**Output:** [6,9,12] + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` consists of lower-case English letters. +* `1 <= words.length <= 5000` +* `1 <= words[i].length <= 30` +* `words[i]` consists of lower-case English letters. \ No newline at end of file diff --git a/src/Algorithms/0031.next-permutation/next-permutation.php b/src/Algorithms/s0031_next_permutation/Solution.php similarity index 96% rename from src/Algorithms/0031.next-permutation/next-permutation.php rename to src/Algorithms/s0031_next_permutation/Solution.php index 2575b1b..2fbe9e4 100644 --- a/src/Algorithms/0031.next-permutation/next-permutation.php +++ b/src/Algorithms/s0031_next_permutation/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return NULL - */ - function nextPermutation(&$nums) { - if(count($nums) == 0) return; - for($i = count($nums) - 2; $i >= 0; $i--){ - if($nums[$i] < $nums[$i + 1]){ - $j = $i + 1; - while($j < count($nums) && $nums[$j] > $nums[$i]) $j++; - self::swap($nums, $i, $j - 1); - self::reverse($nums, $i + 1, count($nums) - 1); - return; - } - } - self::reverse($nums, 0, count($nums) - 1); - } - function reverse(&$nums, $i, $j){ - while($i < $j) self::swap($nums, $i++, $j--); - } - function swap(&$nums, $a, $b){ - $temp = $nums[$a]; - $nums[$a] = $nums[$b]; - $nums[$b] = $temp; - } +class Solution { + + /** + * @param Integer[] $nums + * @return NULL + */ + function nextPermutation(&$nums) { + if(count($nums) == 0) return; + for($i = count($nums) - 2; $i >= 0; $i--){ + if($nums[$i] < $nums[$i + 1]){ + $j = $i + 1; + while($j < count($nums) && $nums[$j] > $nums[$i]) $j++; + self::swap($nums, $i, $j - 1); + self::reverse($nums, $i + 1, count($nums) - 1); + return; + } + } + self::reverse($nums, 0, count($nums) - 1); + } + function reverse(&$nums, $i, $j){ + while($i < $j) self::swap($nums, $i++, $j--); + } + function swap(&$nums, $a, $b){ + $temp = $nums[$a]; + $nums[$a] = $nums[$b]; + $nums[$b] = $temp; + } } diff --git a/src/Algorithms/s0031_next_permutation/readme.md b/src/Algorithms/s0031_next_permutation/readme.md new file mode 100644 index 0000000..bf3ed98 --- /dev/null +++ b/src/Algorithms/s0031_next_permutation/readme.md @@ -0,0 +1,38 @@ +31\. Next Permutation + +Medium + +Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers. + +If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). + +The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** [1,3,2] + +**Example 2:** + +**Input:** nums = [3,2,1] + +**Output:** [1,2,3] + +**Example 3:** + +**Input:** nums = [1,1,5] + +**Output:** [1,5,1] + +**Example 4:** + +**Input:** nums = [1] + +**Output:** [1] + +**Constraints:** + +* `1 <= nums.length <= 100` +* `0 <= nums[i] <= 100` \ No newline at end of file diff --git a/src/Algorithms/0032.longest-valid-parentheses/longest-valid-parentheses.php b/src/Algorithms/s0032_longest_valid_parentheses/Solution.php similarity index 97% rename from src/Algorithms/0032.longest-valid-parentheses/longest-valid-parentheses.php rename to src/Algorithms/s0032_longest_valid_parentheses/Solution.php index 46e4218..ec51417 100644 --- a/src/Algorithms/0032.longest-valid-parentheses/longest-valid-parentheses.php +++ b/src/Algorithms/s0032_longest_valid_parentheses/Solution.php @@ -1,30 +1,30 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function longestValidParentheses($s) { - $map = []; - $map['('] = ')'; - $map['['] = ']'; - $map['{'] = '}'; - $len = strlen($s); - $dp = array_fill(0, $len + 1, 0); - $dp[0] = 0; - $res = 0; - for($i = 1; $i <= $len; $i++) { - $c = $s[$i - 1]; - if($c != '(' && $c != '[' && $c != '{') { - if($dp[$i - 1] > 0 && $i - 2 - $dp[$i - 1] >= 0 && - ($map[$s[$i - 2 - $dp[$i - 1]]] == null ? '?' : $map[$s[$i - 2 - $dp[$i - 1]]]) == $c) - $dp[$i] = $dp[$i - 1] + $dp[$i - 2 - $dp[$i - 1]] + 2; - else if($i > 1 && ($map[$s[$i - 2]] == null ? '?' : $map[$s[$i - 2]]) == $c) { - $dp[$i] = $dp[$i - 2] + 2; - } - } - $res = max($res, $dp[$i]); - } - return $res; - } +class Solution { + + /** + * @param String $s + * @return Integer + */ + function longestValidParentheses($s) { + $map = []; + $map['('] = ')'; + $map['['] = ']'; + $map['{'] = '}'; + $len = strlen($s); + $dp = array_fill(0, $len + 1, 0); + $dp[0] = 0; + $res = 0; + for($i = 1; $i <= $len; $i++) { + $c = $s[$i - 1]; + if($c != '(' && $c != '[' && $c != '{') { + if($dp[$i - 1] > 0 && $i - 2 - $dp[$i - 1] >= 0 && + ($map[$s[$i - 2 - $dp[$i - 1]]] == null ? '?' : $map[$s[$i - 2 - $dp[$i - 1]]]) == $c) + $dp[$i] = $dp[$i - 1] + $dp[$i - 2 - $dp[$i - 1]] + 2; + else if($i > 1 && ($map[$s[$i - 2]] == null ? '?' : $map[$s[$i - 2]]) == $c) { + $dp[$i] = $dp[$i - 2] + 2; + } + } + $res = max($res, $dp[$i]); + } + return $res; + } } diff --git a/src/Algorithms/s0032_longest_valid_parentheses/readme.md b/src/Algorithms/s0032_longest_valid_parentheses/readme.md new file mode 100644 index 0000000..f11141d --- /dev/null +++ b/src/Algorithms/s0032_longest_valid_parentheses/readme.md @@ -0,0 +1,32 @@ +32\. Longest Valid Parentheses + +Hard + +Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring. + +**Example 1:** + +**Input:** s = "(()" + +**Output:** 2 + +**Explanation:** The longest valid parentheses substring is "()". + +**Example 2:** + +**Input:** s = ")()())" + +**Output:** 4 + +**Explanation:** The longest valid parentheses substring is "()()". + +**Example 3:** + +**Input:** s = "" + +**Output:** 0 + +**Constraints:** + +* 0 <= s.length <= 3 * 104 +* `s[i]` is `'('`, or `')'`. \ No newline at end of file diff --git a/src/Algorithms/0033.search-in-rotated-sorted-array/search-in-rotated-sorted-array.php b/src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php similarity index 96% rename from src/Algorithms/0033.search-in-rotated-sorted-array/search-in-rotated-sorted-array.php rename to src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php index 9b40316..b89936c 100644 --- a/src/Algorithms/0033.search-in-rotated-sorted-array/search-in-rotated-sorted-array.php +++ b/src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php @@ -1,31 +1,31 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $target - * @return Integer - */ - function search($nums, $target) { - $low = 0; $high = count($nums) - 1; - while ($low <= $high) { - $m = intval(($low + $high) / 2); - if ($nums[$m] == $target) { - return $m; - } - if ($nums[$low] <= $nums[$m]) { - if ($target >= $nums[$low] && $target <= $nums[$m]) { - $high = $m - 1; - } else { - $low = $m + 1; - } - } else { - if ($target >= $nums[$m] && $target <= $nums[$high]) { - $low = $m + 1; - } else { - $high = $m - 1; - } - } - } - return -1; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer + */ + function search($nums, $target) { + $low = 0; $high = count($nums) - 1; + while ($low <= $high) { + $m = intval(($low + $high) / 2); + if ($nums[$m] == $target) { + return $m; + } + if ($nums[$low] <= $nums[$m]) { + if ($target >= $nums[$low] && $target <= $nums[$m]) { + $high = $m - 1; + } else { + $low = $m + 1; + } + } else { + if ($target >= $nums[$m] && $target <= $nums[$high]) { + $low = $m + 1; + } else { + $high = $m - 1; + } + } + } + return -1; + } +} diff --git a/src/Algorithms/s0033_search_in_rotated_sorted_array/readme.md b/src/Algorithms/s0033_search_in_rotated_sorted_array/readme.md new file mode 100644 index 0000000..ebfff91 --- /dev/null +++ b/src/Algorithms/s0033_search_in_rotated_sorted_array/readme.md @@ -0,0 +1,37 @@ +33\. Search in Rotated Sorted Array + +Medium + +There is an integer array `nums` sorted in ascending order (with **distinct** values). + +Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. + +Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. + +You must write an algorithm with `O(log n)` runtime complexity. + +**Example 1:** + +**Input:** nums = [4,5,6,7,0,1,2], target = 0 + +**Output:** 4 + +**Example 2:** + +**Input:** nums = [4,5,6,7,0,1,2], target = 3 + +**Output:** -1 + +**Example 3:** + +**Input:** nums = [1], target = 0 + +**Output:** -1 + +**Constraints:** + +* `1 <= nums.length <= 5000` +* -104 <= nums[i] <= 104 +* All values of `nums` are **unique**. +* `nums` is an ascending array that is possibly rotated. +* -104 <= target <= 104 \ No newline at end of file diff --git a/src/Algorithms/0034.search-for-a-range/search-for-a-range.php b/src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/Solution.php similarity index 96% rename from src/Algorithms/0034.search-for-a-range/search-for-a-range.php rename to src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/Solution.php index bac5b7e..85336a3 100644 --- a/src/Algorithms/0034.search-for-a-range/search-for-a-range.php +++ b/src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/Solution.php @@ -1,36 +1,36 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $target - * @return Integer[] - */ - function searchRange($nums, $target) { - $n = count($nums); - $res = array_fill(0, 2, 0); - $beg = 0; - $end = $n-1; - while ($beg <= $end) { - $mid = $beg + intval(($end-$beg)/2); - if ($nums[$mid] < $target) { - $beg = $mid + 1; - } else { - $end = $mid - 1; - } - } - $res[0] = ($beg >= $n || $nums[$beg] != $target) ? -1 : $beg; - - $beg = 0; - $end = $n-1; - while ($beg <= $end) { - $mid = $beg + intval(($end-$beg)/2); - if ($nums[$mid] <= $target) { - $beg = $mid + 1; - } else { - $end = $mid - 1; - } - } - $res[1] = ($end < 0 || $nums[$end] != $target) ? -1 : $end; - return $res; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer[] + */ + function searchRange($nums, $target) { + $n = count($nums); + $res = array_fill(0, 2, 0); + $beg = 0; + $end = $n-1; + while ($beg <= $end) { + $mid = $beg + intval(($end-$beg)/2); + if ($nums[$mid] < $target) { + $beg = $mid + 1; + } else { + $end = $mid - 1; + } + } + $res[0] = ($beg >= $n || $nums[$beg] != $target) ? -1 : $beg; + + $beg = 0; + $end = $n-1; + while ($beg <= $end) { + $mid = $beg + intval(($end-$beg)/2); + if ($nums[$mid] <= $target) { + $beg = $mid + 1; + } else { + $end = $mid - 1; + } + } + $res[1] = ($end < 0 || $nums[$end] != $target) ? -1 : $end; + return $res; + } +} diff --git a/src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md b/src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md new file mode 100644 index 0000000..7c04eb2 --- /dev/null +++ b/src/Algorithms/s0034_find_first_and_last_position_of_element_in_sorted_array/readme.md @@ -0,0 +1,34 @@ +34\. Find First and Last Position of Element in Sorted Array + +Medium + +Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. + +If `target` is not found in the array, return `[-1, -1]`. + +You must write an algorithm with `O(log n)` runtime complexity. + +**Example 1:** + +**Input:** nums = [5,7,7,8,8,10], target = 8 + +**Output:** [3,4] + +**Example 2:** + +**Input:** nums = [5,7,7,8,8,10], target = 6 + +**Output:** [-1,-1] + +**Example 3:** + +**Input:** nums = [], target = 0 + +**Output:** [-1,-1] + +**Constraints:** + +* 0 <= nums.length <= 105 +* -109 <= nums[i] <= 109 +* `nums` is a non-decreasing array. +* -109 <= target <= 109 \ No newline at end of file diff --git a/src/Algorithms/0035.search-insert-position/search-insert-position.php b/src/Algorithms/s0035_search_insert_position/Solution.php similarity index 95% rename from src/Algorithms/0035.search-insert-position/search-insert-position.php rename to src/Algorithms/s0035_search_insert_position/Solution.php index bf73259..cfbef88 100644 --- a/src/Algorithms/0035.search-insert-position/search-insert-position.php +++ b/src/Algorithms/s0035_search_insert_position/Solution.php @@ -1,16 +1,16 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $target - * @return Integer - */ - function searchInsert($nums, $target) { - for($i = 0; $i < count($nums) && $nums[$i] <= $target; $i++) { - if ($nums[$i] == $target) { - return $i; - } - } - return $i; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer + */ + function searchInsert($nums, $target) { + for($i = 0; $i < count($nums) && $nums[$i] <= $target; $i++) { + if ($nums[$i] == $target) { + return $i; + } + } + return $i; + } +} diff --git a/src/Algorithms/s0035_search_insert_position/readme.md b/src/Algorithms/s0035_search_insert_position/readme.md new file mode 100644 index 0000000..94ead0d --- /dev/null +++ b/src/Algorithms/s0035_search_insert_position/readme.md @@ -0,0 +1,44 @@ +35\. Search Insert Position + +Easy + +Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. + +You must write an algorithm with `O(log n)` runtime complexity. + +**Example 1:** + +**Input:** nums = [1,3,5,6], target = 5 + +**Output:** 2 + +**Example 2:** + +**Input:** nums = [1,3,5,6], target = 2 + +**Output:** 1 + +**Example 3:** + +**Input:** nums = [1,3,5,6], target = 7 + +**Output:** 4 + +**Example 4:** + +**Input:** nums = [1,3,5,6], target = 0 + +**Output:** 0 + +**Example 5:** + +**Input:** nums = [1], target = 0 + +**Output:** 0 + +**Constraints:** + +* 1 <= nums.length <= 104 +* -104 <= nums[i] <= 104 +* `nums` contains **distinct** values sorted in **ascending** order. +* -104 <= target <= 104 \ No newline at end of file diff --git a/src/Algorithms/0036.valid-sudoku/valid-sudoku.php b/src/Algorithms/s0036_valid_sudoku/Solution.php similarity index 96% rename from src/Algorithms/0036.valid-sudoku/valid-sudoku.php rename to src/Algorithms/s0036_valid_sudoku/Solution.php index adb9bdd..3880150 100644 --- a/src/Algorithms/0036.valid-sudoku/valid-sudoku.php +++ b/src/Algorithms/s0036_valid_sudoku/Solution.php @@ -1,42 +1,42 @@ -class Solution { - - /** - * @param String[][] $board - * @return Boolean - */ - function isValidSudoku($board) { - $list = []; - for ($i = 0; $i < 9; $i++){ - for ($j = 0; $j < 9; $j++){ - $c = $board[$i][$j]; - if ($c == '.') continue; - if (in_array($c, $list)) return false; - $list[] = $c; - } - $list = []; - } - for ($i = 0; $i < 9; $i++){ - for ($j = 0; $j < 9; $j++){ - $c = $board[$j][$i]; - if ($c == '.') continue; - if (in_array($c, $list)) return false; - $list[] = $c; - } - $list = []; - } - for ($i = 0; $i < 3; $i++){ - for ($j = 0; $j < 3; $j++){ - for ($x = 3*$i; $x < 3+3*$i; $x++){ - for ($y = 3*$j; $y < 3+3*$j; $y++){ - $c = $board[$x][$y]; - if ($c == '.') continue; - if (in_array($c, $list)) return false; - $list[] = $c; - } - } - $list = []; - } - } - return true; - } -} +class Solution { + + /** + * @param String[][] $board + * @return Boolean + */ + function isValidSudoku($board) { + $list = []; + for ($i = 0; $i < 9; $i++){ + for ($j = 0; $j < 9; $j++){ + $c = $board[$i][$j]; + if ($c == '.') continue; + if (in_array($c, $list)) return false; + $list[] = $c; + } + $list = []; + } + for ($i = 0; $i < 9; $i++){ + for ($j = 0; $j < 9; $j++){ + $c = $board[$j][$i]; + if ($c == '.') continue; + if (in_array($c, $list)) return false; + $list[] = $c; + } + $list = []; + } + for ($i = 0; $i < 3; $i++){ + for ($j = 0; $j < 3; $j++){ + for ($x = 3*$i; $x < 3+3*$i; $x++){ + for ($y = 3*$j; $y < 3+3*$j; $y++){ + $c = $board[$x][$y]; + if ($c == '.') continue; + if (in_array($c, $list)) return false; + $list[] = $c; + } + } + $list = []; + } + } + return true; + } +} diff --git a/src/Algorithms/s0036_valid_sudoku/readme.md b/src/Algorithms/s0036_valid_sudoku/readme.md new file mode 100644 index 0000000..db58bb7 --- /dev/null +++ b/src/Algorithms/s0036_valid_sudoku/readme.md @@ -0,0 +1,58 @@ +36\. Valid Sudoku + +Medium + +Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: + +1. Each row must contain the digits `1-9` without repetition. +2. Each column must contain the digits `1-9` without repetition. +3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. + +**Note:** + +* A Sudoku board (partially filled) could be valid but is not necessarily solvable. +* Only the filled cells need to be validated according to the mentioned rules. + +**Example 1:** + +![](https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png) + +**Input:** + + board = + [["5","3",".",".","7",".",".",".","."] + ,["6",".",".","1","9","5",".",".","."] + ,[".","9","8",".",".",".",".","6","."] + ,["8",".",".",".","6",".",".",".","3"] + ,["4",".",".","8",".","3",".",".","1"] + ,["7",".",".",".","2",".",".",".","6"] + ,[".","6",".",".",".",".","2","8","."] + ,[".",".",".","4","1","9",".",".","5"] + ,[".",".",".",".","8",".",".","7","9"]] + +**Output:** true + +**Example 2:** + +**Input:** + + board = + [["8","3",".",".","7",".",".",".","."] + ,["6",".",".","1","9","5",".",".","."] + ,[".","9","8",".",".",".",".","6","."] + ,["8",".",".",".","6",".",".",".","3"] + ,["4",".",".","8",".","3",".",".","1"] + ,["7",".",".",".","2",".",".",".","6"] + ,[".","6",".",".",".",".","2","8","."] + ,[".",".",".","4","1","9",".",".","5"] + ,[".",".",".",".","8",".",".","7","9"]] + +**Output:** false + +**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. + +**Constraints:** + +* `board.length == 9` +* `board[i].length == 9` +* `board[i][j]` is a digit `1-9` or `'.'`. \ No newline at end of file diff --git a/src/Algorithms/0037.sudoku-solver/sudoku-solver.php b/src/Algorithms/s0037_sudoku_solver/Solution.php similarity index 97% rename from src/Algorithms/0037.sudoku-solver/sudoku-solver.php rename to src/Algorithms/s0037_sudoku_solver/Solution.php index 8ba0541..aacc0e2 100644 --- a/src/Algorithms/0037.sudoku-solver/sudoku-solver.php +++ b/src/Algorithms/s0037_sudoku_solver/Solution.php @@ -1,60 +1,60 @@ -class Solution { - public function __construct() { - $this->row = array_fill(0, 9, array_fill(0, 9, false)); - $this->col = array_fill(0, 9, array_fill(0, 9, false)); - $this->grid = array_fill(0, 9, array_fill(0, 9, false)); - $this->found = false; - } - - /** - * @param String[][] $board - * @return NULL - */ - function solveSudoku(&$board) { - for ($i = 0; $i < 9; ++$i) { - for ($j = 0; $j < 9; ++$j) { - if ($board[$i][$j] != '.') { - $this->row[$i][ord($board[$i][$j]) - ord('1')] = true; - $this->col[$j][ord($board[$i][$j]) - ord('1')] = true; - $this->grid[intval(($i / 3)) * 3 + intval(($j / 3)) % 3][ord($board[$i][$j]) - ord('1')] = true; - } - } - } - self::place(0, $board); - return; - } - function place($n, &$board) { - if ($n == 81) { - // board = g; - $this->found = true; - return; - } - - $i = intval($n / 9); $j = $n % 9; - $index = intval(($i / 3)) * 3 + intval(($j / 3)) % 3; - if ($board[$i][$j] == '.') { - for ($c = 0; $c < 9; ++$c) { - if (!$this->row[$i][$c] && !$this->col[$j][$c] && !$this->grid[$index][$c]) { - $this->row[$i][$c] = true; - $this->col[$j][$c] = true; - $this->grid[$index][$c] = true; - $board[$i][$j] = chr($c + ord('1')); - - self::place($n + 1, $board); - - if ($this->found) - return; - - $board[$i][$j] = '.'; - $this->row[$i][$c] = false; - $this->col[$j][$c] = false; - $this->grid[$index][$c] = false; - - } - } - } - else - self::place($n + 1, $board); - return; - } -} +class Solution { + public function __construct() { + $this->row = array_fill(0, 9, array_fill(0, 9, false)); + $this->col = array_fill(0, 9, array_fill(0, 9, false)); + $this->grid = array_fill(0, 9, array_fill(0, 9, false)); + $this->found = false; + } + + /** + * @param String[][] $board + * @return NULL + */ + function solveSudoku(&$board) { + for ($i = 0; $i < 9; ++$i) { + for ($j = 0; $j < 9; ++$j) { + if ($board[$i][$j] != '.') { + $this->row[$i][ord($board[$i][$j]) - ord('1')] = true; + $this->col[$j][ord($board[$i][$j]) - ord('1')] = true; + $this->grid[intval(($i / 3)) * 3 + intval(($j / 3)) % 3][ord($board[$i][$j]) - ord('1')] = true; + } + } + } + self::place(0, $board); + return; + } + function place($n, &$board) { + if ($n == 81) { + // board = g; + $this->found = true; + return; + } + + $i = intval($n / 9); $j = $n % 9; + $index = intval(($i / 3)) * 3 + intval(($j / 3)) % 3; + if ($board[$i][$j] == '.') { + for ($c = 0; $c < 9; ++$c) { + if (!$this->row[$i][$c] && !$this->col[$j][$c] && !$this->grid[$index][$c]) { + $this->row[$i][$c] = true; + $this->col[$j][$c] = true; + $this->grid[$index][$c] = true; + $board[$i][$j] = chr($c + ord('1')); + + self::place($n + 1, $board); + + if ($this->found) + return; + + $board[$i][$j] = '.'; + $this->row[$i][$c] = false; + $this->col[$j][$c] = false; + $this->grid[$index][$c] = false; + + } + } + } + else + self::place($n + 1, $board); + return; + } +} diff --git a/src/Algorithms/s0037_sudoku_solver/readme.md b/src/Algorithms/s0037_sudoku_solver/readme.md new file mode 100644 index 0000000..6640d2f --- /dev/null +++ b/src/Algorithms/s0037_sudoku_solver/readme.md @@ -0,0 +1,52 @@ +37\. Sudoku Solver + +Hard + +Write a program to solve a Sudoku puzzle by filling the empty cells. + +A sudoku solution must satisfy **all of the following rules**: + +1. Each of the digits `1-9` must occur exactly once in each row. +2. Each of the digits `1-9` must occur exactly once in each column. +3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid. + +The `'.'` character indicates empty cells. + +**Example 1:** + +![](https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png) + +**Input:** + + board = [["5","3",".",".","7",".",".",".","."], + ["6",".",".","1","9","5",".",".","."], + [".","9","8",".",".",".",".","6","."], + ["8",".",".",".","6",".",".",".","3"], + ["4",".",".","8",".","3",".",".","1"], + ["7",".",".",".","2",".",".",".","6"], + [".","6",".",".",".",".","2","8","."], + [".",".",".","4","1","9",".",".","5"], + [".",".",".",".","8",".",".","7","9"]] + +**Output:** + + [["5","3","4","6","7","8","9","1","2"], + ["6","7","2","1","9","5","3","4","8"], + ["1","9","8","3","4","2","5","6","7"], + ["8","5","9","7","6","1","4","2","3"], + ["4","2","6","8","5","3","7","9","1"], + ["7","1","3","9","2","4","8","5","6"], + ["9","6","1","5","3","7","2","8","4"], + ["2","8","7","4","1","9","6","3","5"], + ["3","4","5","2","8","6","1","7","9"]] + +**Explanation:** The input board is shown above and the only valid solution is shown below: + +![](https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png) + +**Constraints:** + +* `board.length == 9` +* `board[i].length == 9` +* `board[i][j]` is a digit or `'.'`. +* It is **guaranteed** that the input board has only one solution. \ No newline at end of file diff --git a/src/Algorithms/0038.count-and-say/count-and-say.php b/src/Algorithms/s0038_count_and_say/Solution.php similarity index 95% rename from src/Algorithms/0038.count-and-say/count-and-say.php rename to src/Algorithms/s0038_count_and_say/Solution.php index cd5208f..9a3209f 100644 --- a/src/Algorithms/0038.count-and-say/count-and-say.php +++ b/src/Algorithms/s0038_count_and_say/Solution.php @@ -1,30 +1,30 @@ -class Solution { - - /** - * @param Integer $n - * @return String - */ - function countAndSay($n) { - $s = "1"; - while($n>1){ - $sub = ""; - $i=0; $num=0; - $ch = ''; $pre=' '; - while($i<=strlen($s)){ - $ch = ($i==strlen($s) ? ' ': $s[$i]); - if(($pre!=' '&&$ch!=$pre)|| $ch==' '){ - $sub .= ($num==0? 1:$num)."".$pre; - $pre = $ch; - $num = 1; - }else{ - $num++; - $pre=$ch; - } - $i++; - } - $s = $sub; - $n--; - } - return $s; - } -} +class Solution { + + /** + * @param Integer $n + * @return String + */ + function countAndSay($n) { + $s = "1"; + while($n>1){ + $sub = ""; + $i=0; $num=0; + $ch = ''; $pre=' '; + while($i<=strlen($s)){ + $ch = ($i==strlen($s) ? ' ': $s[$i]); + if(($pre!=' '&&$ch!=$pre)|| $ch==' '){ + $sub .= ($num==0? 1:$num)."".$pre; + $pre = $ch; + $num = 1; + }else{ + $num++; + $pre=$ch; + } + $i++; + } + $s = $sub; + $n--; + } + return $s; + } +} diff --git a/src/Algorithms/s0038_count_and_say/readme.md b/src/Algorithms/s0038_count_and_say/readme.md new file mode 100644 index 0000000..a65458a --- /dev/null +++ b/src/Algorithms/s0038_count_and_say/readme.md @@ -0,0 +1,41 @@ +38\. Count and Say + +Medium + +The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula: + +* `countAndSay(1) = "1"` +* `countAndSay(n)` is the way you would "say" the digit string from `countAndSay(n-1)`, which is then converted into a different digit string. + +To determine how you "say" a digit string, split it into the **minimal** number of groups so that each group is a contiguous section all of the **same character.** Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. + +For example, the saying and conversion for digit string `"3322251"`: + +![](https://assets.leetcode.com/uploads/2020/10/23/countandsay.jpg) + +Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_. + +**Example 1:** + +**Input:** n = 1 + +**Output:** "1" + +**Explanation:** This is the base case. + +**Example 2:** + +**Input:** n = 4 + +**Output:** "1211" + +**Explanation:** + + countAndSay(1) = "1" + countAndSay(2) = say "1" = one 1 = "11" + countAndSay(3) = say "11" = two 1's = "21" + countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211" + +**Constraints:** + +* `1 <= n <= 30` \ No newline at end of file diff --git a/src/Algorithms/0039.combination-sum/combination-sum.php b/src/Algorithms/s0039_combination_sum/Solution.php similarity index 96% rename from src/Algorithms/0039.combination-sum/combination-sum.php rename to src/Algorithms/s0039_combination_sum/Solution.php index e433676..6d89521 100644 --- a/src/Algorithms/0039.combination-sum/combination-sum.php +++ b/src/Algorithms/s0039_combination_sum/Solution.php @@ -1,35 +1,35 @@ -class Solution { - - public function __construct() { - $this->sol = []; - $this->nums = null; - } - - /** - * @param Integer[] $candidates - * @param Integer $target - * @return Integer[][] - */ - function combinationSum($candidates, $target) { - sort($candidates); - $this->nums = $candidates; - $temp = []; - self::search($target, $temp, 0); - return $this->sol; - } - - function search($target, $list, $start){ - if ($target == 0) { - array_push($this->sol, $list); - return; - } - for ($i = $start; $i < count($this->nums); $i++){ - if ($this->nums[$i] > $target) break; - else { - array_push($list, $this->nums[$i]); - self::search($target - $this->nums[$i], $list, $i); - array_pop($list); - } - } - } -} +class Solution { + + public function __construct() { + $this->sol = []; + $this->nums = null; + } + + /** + * @param Integer[] $candidates + * @param Integer $target + * @return Integer[][] + */ + function combinationSum($candidates, $target) { + sort($candidates); + $this->nums = $candidates; + $temp = []; + self::search($target, $temp, 0); + return $this->sol; + } + + function search($target, $list, $start){ + if ($target == 0) { + array_push($this->sol, $list); + return; + } + for ($i = $start; $i < count($this->nums); $i++){ + if ($this->nums[$i] > $target) break; + else { + array_push($list, $this->nums[$i]); + self::search($target - $this->nums[$i], $list, $i); + array_pop($list); + } + } + } +} diff --git a/src/Algorithms/s0039_combination_sum/readme.md b/src/Algorithms/s0039_combination_sum/readme.md new file mode 100644 index 0000000..1f2c636 --- /dev/null +++ b/src/Algorithms/s0039_combination_sum/readme.md @@ -0,0 +1,52 @@ +39\. Combination Sum + +Medium + +Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. + +The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. + +It is **guaranteed** that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. + +**Example 1:** + +**Input:** candidates = [2,3,6,7], target = 7 + +**Output:** [[2,2,3],[7]] + +**Explanation:** + + 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. + 7 is a candidate, and 7 = 7. + These are the only two combinations. + +**Example 2:** + +**Input:** candidates = [2,3,5], target = 8 + +**Output:** [[2,2,2,2],[2,3,3],[3,5]] + +**Example 3:** + +**Input:** candidates = [2], target = 1 + +**Output:** [] + +**Example 4:** + +**Input:** candidates = [1], target = 1 + +**Output:** [[1]] + +**Example 5:** + +**Input:** candidates = [1], target = 2 + +**Output:** [[1,1]] + +**Constraints:** + +* `1 <= candidates.length <= 30` +* `1 <= candidates[i] <= 200` +* All elements of `candidates` are **distinct**. +* `1 <= target <= 500` \ No newline at end of file diff --git a/src/Algorithms/0040.combination-sum-ii/combination-sum-ii.php b/src/Algorithms/s0040_combination_sum_ii/Solution.php similarity index 96% rename from src/Algorithms/0040.combination-sum-ii/combination-sum-ii.php rename to src/Algorithms/s0040_combination_sum_ii/Solution.php index f22c428..e9790ff 100644 --- a/src/Algorithms/0040.combination-sum-ii/combination-sum-ii.php +++ b/src/Algorithms/s0040_combination_sum_ii/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param Integer[] $candidates - * @param Integer $target - * @return Integer[][] - */ - function combinationSum2($cand, $target) { - sort($cand); - $res = []; - $path = []; - self::dfs_com($cand, 0, $target, $path, $res); - return $res; - } - function dfs_com($cand, $cur, $target, $path, &$res) { - if ($target == 0) { - array_push($res, $path); - return; - } - if ($target < 0) return; - for ($i = $cur; $i < count($cand); $i++){ - if ($i > $cur && $cand[$i] == $cand[$i-1]) continue; - array_push($path, $cand[$i]); - self::dfs_com($cand, $i+1, $target - $cand[$i], $path, $res); - array_pop($path); - } - } -} +class Solution { + + /** + * @param Integer[] $candidates + * @param Integer $target + * @return Integer[][] + */ + function combinationSum2($cand, $target) { + sort($cand); + $res = []; + $path = []; + self::dfs_com($cand, 0, $target, $path, $res); + return $res; + } + function dfs_com($cand, $cur, $target, $path, &$res) { + if ($target == 0) { + array_push($res, $path); + return; + } + if ($target < 0) return; + for ($i = $cur; $i < count($cand); $i++){ + if ($i > $cur && $cand[$i] == $cand[$i-1]) continue; + array_push($path, $cand[$i]); + self::dfs_com($cand, $i+1, $target - $cand[$i], $path, $res); + array_pop($path); + } + } +} diff --git a/src/Algorithms/s0040_combination_sum_ii/readme.md b/src/Algorithms/s0040_combination_sum_ii/readme.md new file mode 100644 index 0000000..7502b7d --- /dev/null +++ b/src/Algorithms/s0040_combination_sum_ii/readme.md @@ -0,0 +1,39 @@ +40\. Combination Sum II + +Medium + +Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`. + +Each number in `candidates` may only be used **once** in the combination. + +**Note:** The solution set must not contain duplicate combinations. + +**Example 1:** + +**Input:** candidates = [10,1,2,7,6,1,5], target = 8 + +**Output:** + + [ + [1,1,6], + [1,2,5], + [1,7], + [2,6] + ] + +**Example 2:** + +**Input:** candidates = [2,5,2,1,2], target = 5 + +**Output:** + + [ + [1,2,2], + [5] + ] + +**Constraints:** + +* `1 <= candidates.length <= 100` +* `1 <= candidates[i] <= 50` +* `1 <= target <= 30` \ No newline at end of file diff --git a/src/Algorithms/0041.first-missing-positive/first-missing-positive.php b/src/Algorithms/s0041_first_missing_positive/Solution.php similarity index 96% rename from src/Algorithms/0041.first-missing-positive/first-missing-positive.php rename to src/Algorithms/s0041_first_missing_positive/Solution.php index 7e70d30..27a8a13 100644 --- a/src/Algorithms/0041.first-missing-positive/first-missing-positive.php +++ b/src/Algorithms/s0041_first_missing_positive/Solution.php @@ -1,21 +1,21 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function firstMissingPositive($nums) { - if(count($nums) == 0) return 1; - for($i = 0;$i < count($nums);$i++) { - while(($nums[$i] != $i + 1) && $nums[$i] >= 1 && $nums[$i] <= count($nums) && $nums[$nums[$i] - 1] != $nums[$i]) { - $tmp = $nums[$i] - 1; - $nums[$i] = $nums[$tmp]; - $nums[$tmp] = $tmp + 1; - } - } - for($i = 0;$i < count($nums);$i++) { - if($nums[$i] != $i + 1) return $i + 1; - } - return count($nums) + 1; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function firstMissingPositive($nums) { + if(count($nums) == 0) return 1; + for($i = 0;$i < count($nums);$i++) { + while(($nums[$i] != $i + 1) && $nums[$i] >= 1 && $nums[$i] <= count($nums) && $nums[$nums[$i] - 1] != $nums[$i]) { + $tmp = $nums[$i] - 1; + $nums[$i] = $nums[$tmp]; + $nums[$tmp] = $tmp + 1; + } + } + for($i = 0;$i < count($nums);$i++) { + if($nums[$i] != $i + 1) return $i + 1; + } + return count($nums) + 1; + } +} diff --git a/src/Algorithms/s0041_first_missing_positive/readme.md b/src/Algorithms/s0041_first_missing_positive/readme.md new file mode 100644 index 0000000..4cd0b1d --- /dev/null +++ b/src/Algorithms/s0041_first_missing_positive/readme.md @@ -0,0 +1,30 @@ +41\. First Missing Positive + +Hard + +Given an unsorted integer array `nums`, return the smallest missing positive integer. + +You must implement an algorithm that runs in `O(n)` time and uses constant extra space. + +**Example 1:** + +**Input:** nums = [1,2,0] + +**Output:** 3 + +**Example 2:** + +**Input:** nums = [3,4,-1,1] + +**Output:** 2 + +**Example 3:** + +**Input:** nums = [7,8,9,11,12] + +**Output:** 1 + +**Constraints:** + +* 1 <= nums.length <= 5 * 105 +* -231 <= nums[i] <= 231 - 1 \ No newline at end of file diff --git a/src/Algorithms/0042.trapping-rain-water/trapping-rain-water.php b/src/Algorithms/s0042_trapping_rain_water/Solution.php similarity index 100% rename from src/Algorithms/0042.trapping-rain-water/trapping-rain-water.php rename to src/Algorithms/s0042_trapping_rain_water/Solution.php diff --git a/src/Algorithms/s0042_trapping_rain_water/readme.md b/src/Algorithms/s0042_trapping_rain_water/readme.md new file mode 100644 index 0000000..b57de86 --- /dev/null +++ b/src/Algorithms/s0042_trapping_rain_water/readme.md @@ -0,0 +1,27 @@ +42\. Trapping Rain Water + +Hard + +Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png) + +**Input:** height = [0,1,0,2,1,0,1,3,2,1,2,1] + +**Output:** 6 + +**Explanation:** The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. + +**Example 2:** + +**Input:** height = [4,2,0,3,2,5] + +**Output:** 9 + +**Constraints:** + +* `n == height.length` +* 1 <= n <= 2 * 104 +* 0 <= height[i] <= 105 \ No newline at end of file diff --git a/src/Algorithms/0043.multiply-strings/multiply-strings.php b/src/Algorithms/s0043_multiply_strings/Solution.php similarity index 100% rename from src/Algorithms/0043.multiply-strings/multiply-strings.php rename to src/Algorithms/s0043_multiply_strings/Solution.php diff --git a/src/Algorithms/s0043_multiply_strings/readme.md b/src/Algorithms/s0043_multiply_strings/readme.md new file mode 100644 index 0000000..598241e --- /dev/null +++ b/src/Algorithms/s0043_multiply_strings/readme.md @@ -0,0 +1,25 @@ +43\. Multiply Strings + +Medium + +Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. + +**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. + +**Example 1:** + +**Input:** num1 = "2", num2 = "3" + +**Output:** "6" + +**Example 2:** + +**Input:** num1 = "123", num2 = "456" + +**Output:** "56088" + +**Constraints:** + +* `1 <= num1.length, num2.length <= 200` +* `num1` and `num2` consist of digits only. +* Both `num1` and `num2` do not contain any leading zero, except the number `0` itself. \ No newline at end of file diff --git a/src/Algorithms/0044.wildcard-matching/wildcard-matching.php b/src/Algorithms/s0044_wildcard_matching/Solution.php similarity index 100% rename from src/Algorithms/0044.wildcard-matching/wildcard-matching.php rename to src/Algorithms/s0044_wildcard_matching/Solution.php diff --git a/src/Algorithms/s0044_wildcard_matching/readme.md b/src/Algorithms/s0044_wildcard_matching/readme.md new file mode 100644 index 0000000..c8e3616 --- /dev/null +++ b/src/Algorithms/s0044_wildcard_matching/readme.md @@ -0,0 +1,54 @@ +44\. Wildcard Matching + +Hard + +Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where: + +* `'?'` Matches any single character. +* `'*'` Matches any sequence of characters (including the empty sequence). + +The matching should cover the **entire** input string (not partial). + +**Example 1:** + +**Input:** s = "aa", p = "a" + +**Output:** false + +**Explanation:** "a" does not match the entire string "aa". + +**Example 2:** + +**Input:** s = "aa", p = "\*" + +**Output:** true + +**Explanation:** '\*' matches any sequence. + +**Example 3:** + +**Input:** s = "cb", p = "?a" + +**Output:** false + +**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'. + +**Example 4:** + +**Input:** s = "adceb", p = "\*a\*b" + +**Output:** true + +**Explanation:** The first '\*' matches the empty sequence, while the second '\*' matches the substring "dce". + +**Example 5:** + +**Input:** s = "acdcb", p = "a\*c?b" + +**Output:** false + +**Constraints:** + +* `0 <= s.length, p.length <= 2000` +* `s` contains only lowercase English letters. +* `p` contains only lowercase English letters, `'?'` or `'*'`. \ No newline at end of file diff --git a/src/Algorithms/0045.jump-game-ii/jump-game-ii.php b/src/Algorithms/s0045_jump_game_ii/Solution.php similarity index 100% rename from src/Algorithms/0045.jump-game-ii/jump-game-ii.php rename to src/Algorithms/s0045_jump_game_ii/Solution.php diff --git a/src/Algorithms/s0045_jump_game_ii/readme.md b/src/Algorithms/s0045_jump_game_ii/readme.md new file mode 100644 index 0000000..10a43da --- /dev/null +++ b/src/Algorithms/s0045_jump_game_ii/readme.md @@ -0,0 +1,30 @@ +45\. Jump Game II + +Medium + +Given an array of non-negative integers `nums`, you are initially positioned at the first index of the array. + +Each element in the array represents your maximum jump length at that position. + +Your goal is to reach the last index in the minimum number of jumps. + +You can assume that you can always reach the last index. + +**Example 1:** + +**Input:** nums = [2,3,1,1,4] + +**Output:** 2 + +**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. + +**Example 2:** + +**Input:** nums = [2,3,0,1,4] + +**Output:** 2 + +**Constraints:** + +* 1 <= nums.length <= 104 +* `0 <= nums[i] <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0046.permutations/permutations.php b/src/Algorithms/s0046_permutations/Solution.php similarity index 100% rename from src/Algorithms/0046.permutations/permutations.php rename to src/Algorithms/s0046_permutations/Solution.php diff --git a/src/Algorithms/s0046_permutations/readme.md b/src/Algorithms/s0046_permutations/readme.md new file mode 100644 index 0000000..4d95634 --- /dev/null +++ b/src/Algorithms/s0046_permutations/readme.md @@ -0,0 +1,29 @@ +46\. Permutations + +Medium + +Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] + +**Example 2:** + +**Input:** nums = [0,1] + +**Output:** [[0,1],[1,0]] + +**Example 3:** + +**Input:** nums = [1] + +**Output:** [[1]] + +**Constraints:** + +* `1 <= nums.length <= 6` +* `-10 <= nums[i] <= 10` +* All the integers of `nums` are **unique**. \ No newline at end of file diff --git a/src/Algorithms/0047.permutations-ii/permutations-ii.php b/src/Algorithms/s0047_permutations_ii/Solution.php similarity index 100% rename from src/Algorithms/0047.permutations-ii/permutations-ii.php rename to src/Algorithms/s0047_permutations_ii/Solution.php diff --git a/src/Algorithms/s0047_permutations_ii/readme.md b/src/Algorithms/s0047_permutations_ii/readme.md new file mode 100644 index 0000000..ec5c40d --- /dev/null +++ b/src/Algorithms/s0047_permutations_ii/readme.md @@ -0,0 +1,22 @@ +47\. Permutations II + +Medium + +Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ + +**Example 1:** + +**Input:** nums = [1,1,2] + +**Output:** [[1,1,2], [1,2,1], [2,1,1]] + +**Example 2:** + +**Input:** nums = [1,2,3] + +**Output:** [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] + +**Constraints:** + +* `1 <= nums.length <= 8` +* `-10 <= nums[i] <= 10` \ No newline at end of file diff --git a/src/Algorithms/0048.rotate-image/rotate-image.php b/src/Algorithms/s0048_rotate_image/Solution.php similarity index 100% rename from src/Algorithms/0048.rotate-image/rotate-image.php rename to src/Algorithms/s0048_rotate_image/Solution.php diff --git a/src/Algorithms/s0048_rotate_image/readme.md b/src/Algorithms/s0048_rotate_image/readme.md new file mode 100644 index 0000000..7441873 --- /dev/null +++ b/src/Algorithms/s0048_rotate_image/readme.md @@ -0,0 +1,42 @@ +48\. Rotate Image + +Medium + +You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). + +You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg) + +**Input:** matrix = [[1,2,3],[4,5,6],[7,8,9]] + +**Output:** [[7,4,1],[8,5,2],[9,6,3]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg) + +**Input:** matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] + +**Output:** [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] + +**Example 3:** + +**Input:** matrix = [[1]] + +**Output:** [[1]] + +**Example 4:** + +**Input:** matrix = [[1,2],[3,4]] + +**Output:** [[3,1],[4,2]] + +**Constraints:** + +* `matrix.length == n` +* `matrix[i].length == n` +* `1 <= n <= 20` +* `-1000 <= matrix[i][j] <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0049.group-anagrams/group-anagrams.php b/src/Algorithms/s0049_group_anagrams/Solution.php similarity index 100% rename from src/Algorithms/0049.group-anagrams/group-anagrams.php rename to src/Algorithms/s0049_group_anagrams/Solution.php diff --git a/src/Algorithms/s0049_group_anagrams/readme.md b/src/Algorithms/s0049_group_anagrams/readme.md new file mode 100644 index 0000000..c1641ce --- /dev/null +++ b/src/Algorithms/s0049_group_anagrams/readme.md @@ -0,0 +1,31 @@ +49\. Group Anagrams + +Medium + +Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. + +An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + +**Example 1:** + +**Input:** strs = ["eat","tea","tan","ate","nat","bat"] + +**Output:** [["bat"],["nat","tan"],["ate","eat","tea"]] + +**Example 2:** + +**Input:** strs = [""] + +**Output:** [[""]] + +**Example 3:** + +**Input:** strs = ["a"] + +**Output:** [["a"]] + +**Constraints:** + +* 1 <= strs.length <= 104 +* `0 <= strs[i].length <= 100` +* `strs[i]` consists of lowercase English letters. \ No newline at end of file diff --git a/src/Algorithms/0050.powx-n/powx-n.php b/src/Algorithms/s0050_powx_n/Solution.php similarity index 100% rename from src/Algorithms/0050.powx-n/powx-n.php rename to src/Algorithms/s0050_powx_n/Solution.php diff --git a/src/Algorithms/s0050_powx_n/readme.md b/src/Algorithms/s0050_powx_n/readme.md new file mode 100644 index 0000000..3e93a2f --- /dev/null +++ b/src/Algorithms/s0050_powx_n/readme.md @@ -0,0 +1,31 @@ +50\. Pow(x, n) + +Medium + +Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., xn). + +**Example 1:** + +**Input:** x = 2.00000, n = 10 + +**Output:** 1024.00000 + +**Example 2:** + +**Input:** x = 2.10000, n = 3 + +**Output:** 9.26100 + +**Example 3:** + +**Input:** x = 2.00000, n = -2 + +**Output:** 0.25000 + +**Explanation:** 2\-2 = 1/22 = 1/4 = 0.25 + +**Constraints:** + +* `-100.0 < x < 100.0` +* -231 <= n <= 231-1 +* -104 <= xn <= 104 \ No newline at end of file diff --git a/src/Algorithms/0051.n-queens/n-queens.php b/src/Algorithms/s0051_n_queens/Solution.php similarity index 97% rename from src/Algorithms/0051.n-queens/n-queens.php rename to src/Algorithms/s0051_n_queens/Solution.php index ba77560..2641399 100644 --- a/src/Algorithms/0051.n-queens/n-queens.php +++ b/src/Algorithms/s0051_n_queens/Solution.php @@ -1,35 +1,35 @@ -class Solution { - - /** - * @param Integer $n - * @return String[][] - */ - function solveNQueens($n) { - $ans = []; - $colUsed = array_fill(0, $n, false); - $diagonals45Used = array_fill(0, 2 * $n - 1, false); - $diagonals135Used = array_fill(0, 2 * $n - 1, false); - $chars = array_fill(0, $n, array_fill(0, $n, '.')); - self::helper(0, $chars, $ans, $colUsed, $diagonals45Used, $diagonals135Used); - return $ans; - } - - function helper($row, &$chars, &$ans, &$colUsed, &$diagonals45Used, &$diagonals135Used){ - $N = count($chars); - if ($row == $N) { - $temp = []; - for ($i = 0; $i < $N; $i++) - array_push($temp, implode($chars[$i])); - array_push($ans, $temp); - }else{ - for ($i = 0; $i < $N; $i++){ - if ($colUsed[$i] || $diagonals45Used[$i+$row] || $diagonals135Used[$N-1-$row+$i]) continue; - $chars[$row][$i] = 'Q'; - $colUsed[$i] = $diagonals45Used[$i+$row] = $diagonals135Used[$N-1-$row+$i] = true; - self::helper($row+1, $chars, $ans, $colUsed, $diagonals45Used, $diagonals135Used); - $chars[$row][$i] = '.'; - $colUsed[$i] = $diagonals45Used[$i+$row] = $diagonals135Used[$N-1-$row+$i] = false; - } - } - } -} +class Solution { + + /** + * @param Integer $n + * @return String[][] + */ + function solveNQueens($n) { + $ans = []; + $colUsed = array_fill(0, $n, false); + $diagonals45Used = array_fill(0, 2 * $n - 1, false); + $diagonals135Used = array_fill(0, 2 * $n - 1, false); + $chars = array_fill(0, $n, array_fill(0, $n, '.')); + self::helper(0, $chars, $ans, $colUsed, $diagonals45Used, $diagonals135Used); + return $ans; + } + + function helper($row, &$chars, &$ans, &$colUsed, &$diagonals45Used, &$diagonals135Used){ + $N = count($chars); + if ($row == $N) { + $temp = []; + for ($i = 0; $i < $N; $i++) + array_push($temp, implode($chars[$i])); + array_push($ans, $temp); + }else{ + for ($i = 0; $i < $N; $i++){ + if ($colUsed[$i] || $diagonals45Used[$i+$row] || $diagonals135Used[$N-1-$row+$i]) continue; + $chars[$row][$i] = 'Q'; + $colUsed[$i] = $diagonals45Used[$i+$row] = $diagonals135Used[$N-1-$row+$i] = true; + self::helper($row+1, $chars, $ans, $colUsed, $diagonals45Used, $diagonals135Used); + $chars[$row][$i] = '.'; + $colUsed[$i] = $diagonals45Used[$i+$row] = $diagonals135Used[$N-1-$row+$i] = false; + } + } + } +} diff --git a/src/Algorithms/s0051_n_queens/readme.md b/src/Algorithms/s0051_n_queens/readme.md new file mode 100644 index 0000000..4227951 --- /dev/null +++ b/src/Algorithms/s0051_n_queens/readme.md @@ -0,0 +1,29 @@ +51\. N-Queens + +Hard + +The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. + +Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. + +Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/13/queens.jpg) + +**Input:** n = 4 + +**Output:** [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] + +**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above + +**Example 2:** + +**Input:** n = 1 + +**Output:** [["Q"]] + +**Constraints:** + +* `1 <= n <= 9` \ No newline at end of file diff --git a/src/Algorithms/0052.n-queens-ii/n-queens-ii.php b/src/Algorithms/s0052_n_queens_ii/Solution.php similarity index 96% rename from src/Algorithms/0052.n-queens-ii/n-queens-ii.php rename to src/Algorithms/s0052_n_queens_ii/Solution.php index f771247..37ac26d 100644 --- a/src/Algorithms/0052.n-queens-ii/n-queens-ii.php +++ b/src/Algorithms/s0052_n_queens_ii/Solution.php @@ -1,33 +1,33 @@ -class Solution { - - var $tot = 0; - /** - * @param Integer $n - * @return Integer - */ - function totalNQueens($n) { - $col = array_fill(0, $n, 0); - $cur = 0; - return self::totalQueens($n,$cur,$col); - } - - function totalQueens($n,$cur,&$col){ - if($cur == $n) $this->tot++; - else{ - for($i = 0; $i < $n; $i++){ - $ok = true; - $col[$cur] = $i; - for($j = 0; $j < $cur; $j++){ - if($col[$cur] == $col[$j] || $cur+$col[$cur] == $j + $col[$j] || $cur-$col[$cur] == $j - $col[$j]){ - $ok = false; - break; - } - } - if($ok){ - self::totalQueens($n,$cur+1,$col); - } - } - } - return $this->tot; - } -} +class Solution { + + var $tot = 0; + /** + * @param Integer $n + * @return Integer + */ + function totalNQueens($n) { + $col = array_fill(0, $n, 0); + $cur = 0; + return self::totalQueens($n,$cur,$col); + } + + function totalQueens($n,$cur,&$col){ + if($cur == $n) $this->tot++; + else{ + for($i = 0; $i < $n; $i++){ + $ok = true; + $col[$cur] = $i; + for($j = 0; $j < $cur; $j++){ + if($col[$cur] == $col[$j] || $cur+$col[$cur] == $j + $col[$j] || $cur-$col[$cur] == $j - $col[$j]){ + $ok = false; + break; + } + } + if($ok){ + self::totalQueens($n,$cur+1,$col); + } + } + } + return $this->tot; + } +} diff --git a/src/Algorithms/s0052_n_queens_ii/readme.md b/src/Algorithms/s0052_n_queens_ii/readme.md new file mode 100644 index 0000000..946096c --- /dev/null +++ b/src/Algorithms/s0052_n_queens_ii/readme.md @@ -0,0 +1,27 @@ +52\. N-Queens II + +Hard + +The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. + +Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/13/queens.jpg) + +**Input:** n = 4 + +**Output:** 2 + +**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown. + +**Example 2:** + +**Input:** n = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= n <= 9` \ No newline at end of file diff --git a/src/Algorithms/0053.maximum-subarray/maximum-subarray.php b/src/Algorithms/s0053_maximum_subarray/Solution.php similarity index 95% rename from src/Algorithms/0053.maximum-subarray/maximum-subarray.php rename to src/Algorithms/s0053_maximum_subarray/Solution.php index 5fcb754..3689c52 100644 --- a/src/Algorithms/0053.maximum-subarray/maximum-subarray.php +++ b/src/Algorithms/s0053_maximum_subarray/Solution.php @@ -1,17 +1,17 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function maxSubArray($nums) { - $sum =$nums[0]; - $n = count($nums); - $max=$sum; - for($i=1;$i<$n;$i++){ - $sum = $nums[$i]>$nums[$i]+$sum?$nums[$i]:$nums[$i]+$sum; - $max = $max > $sum? $max : $sum; - } - return $max; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function maxSubArray($nums) { + $sum =$nums[0]; + $n = count($nums); + $max=$sum; + for($i=1;$i<$n;$i++){ + $sum = $nums[$i]>$nums[$i]+$sum?$nums[$i]:$nums[$i]+$sum; + $max = $max > $sum? $max : $sum; + } + return $max; + } +} diff --git a/src/Algorithms/s0053_maximum_subarray/readme.md b/src/Algorithms/s0053_maximum_subarray/readme.md new file mode 100644 index 0000000..521093b --- /dev/null +++ b/src/Algorithms/s0053_maximum_subarray/readme.md @@ -0,0 +1,34 @@ +53\. Maximum Subarray + +Easy + +Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return _its sum_. + +A **subarray** is a **contiguous** part of an array. + +**Example 1:** + +**Input:** nums = [-2,1,-3,4,-1,2,1,-5,4] + +**Output:** 6 + +**Explanation:** [4,-1,2,1] has the largest sum = 6. + +**Example 2:** + +**Input:** nums = [1] + +**Output:** 1 + +**Example 3:** + +**Input:** nums = [5,4,-1,7,8] + +**Output:** 23 + +**Constraints:** + +* 1 <= nums.length <= 105 +* -104 <= nums[i] <= 104 + +**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle. \ No newline at end of file diff --git a/src/Algorithms/0054.spiral-matrix/spiral-matrix.php b/src/Algorithms/s0054_spiral_matrix/Solution.php similarity index 94% rename from src/Algorithms/0054.spiral-matrix/spiral-matrix.php rename to src/Algorithms/s0054_spiral_matrix/Solution.php index fa3f71b..e8c5187 100644 --- a/src/Algorithms/0054.spiral-matrix/spiral-matrix.php +++ b/src/Algorithms/s0054_spiral_matrix/Solution.php @@ -1,49 +1,49 @@ -class Solution { - - /** - * @param Integer[][] $matrix - * @return Integer[] - */ - function spiralOrder($matrix) { - if (count($matrix) == 0) - return []; - $count = count($matrix) * count($matrix[0]); - $res = []; - $i = 0; $j = 0; $row = count($matrix); $col = count($matrix[0]); $start1 = 0; $start2 = 1; - array_push($res, $matrix[0][0]); - while ($count > 1) - { - while ($j < $col - 1) - { - $j++; - array_push($res, $matrix[$i][$j]); - $count--; - } - while ($i < $row - 1) - { - $i++; - array_push($res, $matrix[$i][$j]); - $count--; - } - $row--; - $col--; - if ($count == 1) - break; - while ($j > $start1) - { - $j--; - array_push($res, $matrix[$i][$j]); - $count--; - } - while ($i > $start2) - { - $i--; - array_push($res, $matrix[$i][$j]); - $count--; - } - $start1++; - $start2++; - } - return $res; - } -} +class Solution { + + /** + * @param Integer[][] $matrix + * @return Integer[] + */ + function spiralOrder($matrix) { + if (count($matrix) == 0) + return []; + $count = count($matrix) * count($matrix[0]); + $res = []; + $i = 0; $j = 0; $row = count($matrix); $col = count($matrix[0]); $start1 = 0; $start2 = 1; + array_push($res, $matrix[0][0]); + while ($count > 1) + { + while ($j < $col - 1) + { + $j++; + array_push($res, $matrix[$i][$j]); + $count--; + } + while ($i < $row - 1) + { + $i++; + array_push($res, $matrix[$i][$j]); + $count--; + } + $row--; + $col--; + if ($count == 1) + break; + while ($j > $start1) + { + $j--; + array_push($res, $matrix[$i][$j]); + $count--; + } + while ($i > $start2) + { + $i--; + array_push($res, $matrix[$i][$j]); + $count--; + } + $start1++; + $start2++; + } + return $res; + } +} diff --git a/src/Algorithms/s0054_spiral_matrix/readme.md b/src/Algorithms/s0054_spiral_matrix/readme.md new file mode 100644 index 0000000..75abbda --- /dev/null +++ b/src/Algorithms/s0054_spiral_matrix/readme.md @@ -0,0 +1,28 @@ +54\. Spiral Matrix + +Medium + +Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg) + +**Input:** matrix = [[1,2,3],[4,5,6],[7,8,9]] + +**Output:** [1,2,3,6,9,8,7,4,5] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg) + +**Input:** matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] + +**Output:** [1,2,3,4,8,12,11,10,9,5,6,7] + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 10` +* `-100 <= matrix[i][j] <= 100` \ No newline at end of file diff --git a/src/Algorithms/0055.jump-game/jump-game.php b/src/Algorithms/s0055_jump_game/Solution.php similarity index 95% rename from src/Algorithms/0055.jump-game/jump-game.php rename to src/Algorithms/s0055_jump_game/Solution.php index 01ee272..238f1c3 100644 --- a/src/Algorithms/0055.jump-game/jump-game.php +++ b/src/Algorithms/s0055_jump_game/Solution.php @@ -1,22 +1,22 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Boolean - */ - function canJump($nums) { - if (count($nums) == 1) { - return true; - } - - $i = 0; - $lastIndex = count($nums) - 1; - for ($i = count($nums) - 2; $i >= 0; $i--) { - $step = $nums[$i]; - if ($i + $step >= $lastIndex) { - $lastIndex = $i; - } - } - return $lastIndex == 0; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Boolean + */ + function canJump($nums) { + if (count($nums) == 1) { + return true; + } + + $i = 0; + $lastIndex = count($nums) - 1; + for ($i = count($nums) - 2; $i >= 0; $i--) { + $step = $nums[$i]; + if ($i + $step >= $lastIndex) { + $lastIndex = $i; + } + } + return $lastIndex == 0; + } +} diff --git a/src/Algorithms/s0055_jump_game/readme.md b/src/Algorithms/s0055_jump_game/readme.md new file mode 100644 index 0000000..0f4d2db --- /dev/null +++ b/src/Algorithms/s0055_jump_game/readme.md @@ -0,0 +1,28 @@ +55\. Jump Game + +Medium + +You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. + +Return `true` _if you can reach the last index, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** nums = [2,3,1,1,4] + +**Output:** true + +**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. + +**Example 2:** + +**Input:** nums = [3,2,1,0,4] + +**Output:** false + +**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. + +**Constraints:** + +* 1 <= nums.length <= 104 +* 0 <= nums[i] <= 105 \ No newline at end of file diff --git a/src/Algorithms/0056.merge-intervals/merge-intervals.php b/src/Algorithms/s0056_merge_intervals/Solution.php similarity index 96% rename from src/Algorithms/0056.merge-intervals/merge-intervals.php rename to src/Algorithms/s0056_merge_intervals/Solution.php index 019ce66..b518a3c 100644 --- a/src/Algorithms/0056.merge-intervals/merge-intervals.php +++ b/src/Algorithms/s0056_merge_intervals/Solution.php @@ -1,44 +1,44 @@ -/** - * Definition for an interval. - * class Interval { - * public $start = 0; - * public $end = 0; - * function __construct(int $start = 0, int $end = 0) { - * $this->start = $start; - * $this->end = $end; - * } - * } - */ -class Solution { - - function cmp($a, $b) { - if ($a->start == $b->start) { - return 0; - } - return ($a->start < $b->start) ? -1 : 1; - } - - /** - * @param Interval[] $intervals - * @return Interval[] - */ - function merge($intervals) { - usort($intervals, 'self::cmp'); - $mergedIntervals = []; - - for ($i = 0; $i < count($intervals);) { - $interval = $intervals[$i]; - $start = $interval->start; - $end = $interval->end; - - while (++$i < count($intervals) && $intervals[$i]->start <= $end) { - if ($end < $intervals[$i]->end) { - $end = $intervals[$i]->end; - } - } - array_push($mergedIntervals, new Interval($start, $end)); - } - - return $mergedIntervals; - } -} +/** + * Definition for an interval. + * class Interval { + * public $start = 0; + * public $end = 0; + * function __construct(int $start = 0, int $end = 0) { + * $this->start = $start; + * $this->end = $end; + * } + * } + */ +class Solution { + + function cmp($a, $b) { + if ($a->start == $b->start) { + return 0; + } + return ($a->start < $b->start) ? -1 : 1; + } + + /** + * @param Interval[] $intervals + * @return Interval[] + */ + function merge($intervals) { + usort($intervals, 'self::cmp'); + $mergedIntervals = []; + + for ($i = 0; $i < count($intervals);) { + $interval = $intervals[$i]; + $start = $interval->start; + $end = $interval->end; + + while (++$i < count($intervals) && $intervals[$i]->start <= $end) { + if ($end < $intervals[$i]->end) { + $end = $intervals[$i]->end; + } + } + array_push($mergedIntervals, new Interval($start, $end)); + } + + return $mergedIntervals; + } +} diff --git a/src/Algorithms/s0056_merge_intervals/readme.md b/src/Algorithms/s0056_merge_intervals/readme.md new file mode 100644 index 0000000..d4409db --- /dev/null +++ b/src/Algorithms/s0056_merge_intervals/readme.md @@ -0,0 +1,27 @@ +56\. Merge Intervals + +Medium + +Given an array of `intervals` where intervals[i] = [starti, endi], merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. + +**Example 1:** + +**Input:** intervals = [[1,3],[2,6],[8,10],[15,18]] + +**Output:** [[1,6],[8,10],[15,18]] + +**Explanation:** Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. + +**Example 2:** + +**Input:** intervals = [[1,4],[4,5]] + +**Output:** [[1,5]] + +**Explanation:** Intervals [1,4] and [4,5] are considered overlapping. + +**Constraints:** + +* 1 <= intervals.length <= 104 +* `intervals[i].length == 2` +* 0 <= starti <= endi <= 104 \ No newline at end of file diff --git a/src/Algorithms/0057.insert-interval/insert-interval.php b/src/Algorithms/s0057_insert_interval/Solution.php similarity index 95% rename from src/Algorithms/0057.insert-interval/insert-interval.php rename to src/Algorithms/s0057_insert_interval/Solution.php index 2e7be00..bb0cad1 100644 --- a/src/Algorithms/0057.insert-interval/insert-interval.php +++ b/src/Algorithms/s0057_insert_interval/Solution.php @@ -1,44 +1,44 @@ -/** - * Definition for an interval. - * class Interval { - * public $start = 0; - * public $end = 0; - * function __construct(int $start = 0, int $end = 0) { - * $this->start = $start; - * $this->end = $end; - * } - * } - */ -class Solution { - - /** - * @param Interval[] $intervals - * @param Interval $newInterval - * @return Interval[] - */ - function insert($intervals, $newInterval) { - $res = []; - - $s = $newInterval->start; - $e = $newInterval->end; - - foreach($intervals as $i) { - if($i->start > $e) { - array_push($res, new Interval($s,$e)); - $s = $i->start; - $e = $i->end; - } - - if($s <= $i->end) { - $s = min($s, $i->start); - $e = max($e, $i->end); - } - else { - array_push($res, $i); - } - } - - array_push($res, new Interval($s,$e)); - return $res; - } -} +/** + * Definition for an interval. + * class Interval { + * public $start = 0; + * public $end = 0; + * function __construct(int $start = 0, int $end = 0) { + * $this->start = $start; + * $this->end = $end; + * } + * } + */ +class Solution { + + /** + * @param Interval[] $intervals + * @param Interval $newInterval + * @return Interval[] + */ + function insert($intervals, $newInterval) { + $res = []; + + $s = $newInterval->start; + $e = $newInterval->end; + + foreach($intervals as $i) { + if($i->start > $e) { + array_push($res, new Interval($s,$e)); + $s = $i->start; + $e = $i->end; + } + + if($s <= $i->end) { + $s = min($s, $i->start); + $e = max($e, $i->end); + } + else { + array_push($res, $i); + } + } + + array_push($res, new Interval($s,$e)); + return $res; + } +} diff --git a/src/Algorithms/s0057_insert_interval/readme.md b/src/Algorithms/s0057_insert_interval/readme.md new file mode 100644 index 0000000..1b94c01 --- /dev/null +++ b/src/Algorithms/s0057_insert_interval/readme.md @@ -0,0 +1,50 @@ +57\. Insert Interval + +Medium + +You are given an array of non-overlapping intervals `intervals` where intervals[i] = [starti, endi] represent the start and the end of the ith interval and `intervals` is sorted in ascending order by starti. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. + +Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by starti and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). + +Return `intervals` _after the insertion_. + +**Example 1:** + +**Input:** intervals = [[1,3],[6,9]], newInterval = [2,5] + +**Output:** [[1,5],[6,9]] + +**Example 2:** + +**Input:** intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] + +**Output:** [[1,2],[3,10],[12,16]] + +**Explanation:** Because the new interval `[4,8]` overlaps with `[3,5],[6,7],[8,10]`. + +**Example 3:** + +**Input:** intervals = [], newInterval = [5,7] + +**Output:** [[5,7]] + +**Example 4:** + +**Input:** intervals = [[1,5]], newInterval = [2,3] + +**Output:** [[1,5]] + +**Example 5:** + +**Input:** intervals = [[1,5]], newInterval = [2,7] + +**Output:** [[1,7]] + +**Constraints:** + +* 0 <= intervals.length <= 104 +* `intervals[i].length == 2` +* 0 <= starti <= endi <= 105 +* `intervals` is sorted by starti in **ascending** order. +* `newInterval.length == 2` +* 0 <= start <= end <= 105 \ No newline at end of file diff --git a/src/Algorithms/0058.length-of-last-word/length-of-last-word.php b/src/Algorithms/s0058_length_of_last_word/Solution.php similarity index 95% rename from src/Algorithms/0058.length-of-last-word/length-of-last-word.php rename to src/Algorithms/s0058_length_of_last_word/Solution.php index be38797..5a810cc 100644 --- a/src/Algorithms/0058.length-of-last-word/length-of-last-word.php +++ b/src/Algorithms/s0058_length_of_last_word/Solution.php @@ -1,20 +1,20 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function lengthOfLastWord($s) { - $length = 0; - $first = false; - for ($i = strlen($s) - 1; $i >= 0; $i--) { - if ($s[$i] == ' ' && $first) { - return $length; - } else if ($s[$i] != ' ') { - $first = true; - $length++; - } - } - return $length; - } -} +class Solution { + + /** + * @param String $s + * @return Integer + */ + function lengthOfLastWord($s) { + $length = 0; + $first = false; + for ($i = strlen($s) - 1; $i >= 0; $i--) { + if ($s[$i] == ' ' && $first) { + return $length; + } else if ($s[$i] != ' ') { + $first = true; + $length++; + } + } + return $length; + } +} diff --git a/src/Algorithms/s0058_length_of_last_word/readme.md b/src/Algorithms/s0058_length_of_last_word/readme.md new file mode 100644 index 0000000..96b9253 --- /dev/null +++ b/src/Algorithms/s0058_length_of_last_word/readme.md @@ -0,0 +1,37 @@ +58\. Length of Last Word + +Easy + +Given a string `s` consisting of some words separated by some number of spaces, return _the length of the **last** word in the string._ + +A **word** is a maximal substring consisting of non-space characters only. + +**Example 1:** + +**Input:** s = "Hello World" + +**Output:** 5 + +**Explanation:** The last word is "World" with length 5. + +**Example 2:** + +**Input:** s = " fly me to the moon " + +**Output:** 4 + +**Explanation:** The last word is "moon" with length 4. + +**Example 3:** + +**Input:** s = "luffy is still joyboy" + +**Output:** 6 + +**Explanation:** The last word is "joyboy" with length 6. + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` consists of only English letters and spaces `' '`. +* There will be at least one word in `s`. \ No newline at end of file diff --git a/src/Algorithms/0059.spiral-matrix-ii/spiral-matrix-ii.php b/src/Algorithms/s0059_spiral_matrix_ii/Solution.php similarity index 96% rename from src/Algorithms/0059.spiral-matrix-ii/spiral-matrix-ii.php rename to src/Algorithms/s0059_spiral_matrix_ii/Solution.php index 9b27e7d..f113001 100644 --- a/src/Algorithms/0059.spiral-matrix-ii/spiral-matrix-ii.php +++ b/src/Algorithms/s0059_spiral_matrix_ii/Solution.php @@ -1,19 +1,19 @@ -class Solution { - - /** - * @param Integer $n - * @return Integer[][] - */ - function generateMatrix($n) { - $res=array_fill(0, $n, array_fill(0, $n, 0)); - $next=1; - for($k=0;$k=$k;$j--)$res[$i][$j]=$next++; - for(++$j,--$i;$i>$k;$i--)$res[$i][$j]=$next++; - } - return $res; - } -} +class Solution { + + /** + * @param Integer $n + * @return Integer[][] + */ + function generateMatrix($n) { + $res=array_fill(0, $n, array_fill(0, $n, 0)); + $next=1; + for($k=0;$k=$k;$j--)$res[$i][$j]=$next++; + for(++$j,--$i;$i>$k;$i--)$res[$i][$j]=$next++; + } + return $res; + } +} diff --git a/src/Algorithms/s0059_spiral_matrix_ii/readme.md b/src/Algorithms/s0059_spiral_matrix_ii/readme.md new file mode 100644 index 0000000..51b1049 --- /dev/null +++ b/src/Algorithms/s0059_spiral_matrix_ii/readme.md @@ -0,0 +1,23 @@ +59\. Spiral Matrix II + +Medium + +Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg) + +**Input:** n = 3 + +**Output:** [[1,2,3],[8,9,4],[7,6,5]] + +**Example 2:** + +**Input:** n = 1 + +**Output:** [[1]] + +**Constraints:** + +* `1 <= n <= 20` \ No newline at end of file diff --git a/src/Algorithms/0060.permutation-sequence/permutation-sequence.php b/src/Algorithms/s0060_permutation_sequence/Solution.php similarity index 95% rename from src/Algorithms/0060.permutation-sequence/permutation-sequence.php rename to src/Algorithms/s0060_permutation_sequence/Solution.php index 41ff7cd..d489c9b 100644 --- a/src/Algorithms/0060.permutation-sequence/permutation-sequence.php +++ b/src/Algorithms/s0060_permutation_sequence/Solution.php @@ -1,25 +1,25 @@ -class Solution { - - /** - * @param Integer $n - * @param Integer $k - * @return String - */ - function getPermutation($n, $k) { - $k--; - $mod = 1; - $list = []; - for ($i = 1; $i <= $n; ++$i) { - array_push($list, $i); - $mod *= $i; - } - $sb = ""; - for ($i = 1; $i <= $n; ++$i) { - $mod = intval($mod / ($n-$i+1)); - $idx = intval($k/$mod); - $sb .= array_splice($list, $idx, 1)[0]; - $k = $k % $mod; - } - return $sb; - } -} +class Solution { + + /** + * @param Integer $n + * @param Integer $k + * @return String + */ + function getPermutation($n, $k) { + $k--; + $mod = 1; + $list = []; + for ($i = 1; $i <= $n; ++$i) { + array_push($list, $i); + $mod *= $i; + } + $sb = ""; + for ($i = 1; $i <= $n; ++$i) { + $mod = intval($mod / ($n-$i+1)); + $idx = intval($k/$mod); + $sb .= array_splice($list, $idx, 1)[0]; + $k = $k % $mod; + } + return $sb; + } +} diff --git a/src/Algorithms/s0060_permutation_sequence/readme.md b/src/Algorithms/s0060_permutation_sequence/readme.md new file mode 100644 index 0000000..a961d67 --- /dev/null +++ b/src/Algorithms/s0060_permutation_sequence/readme.md @@ -0,0 +1,39 @@ +60\. Permutation Sequence + +Hard + +The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations. + +By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`: + +1. `"123"` +2. `"132"` +3. `"213"` +4. `"231"` +5. `"312"` +6. `"321"` + +Given `n` and `k`, return the `kth` permutation sequence. + +**Example 1:** + +**Input:** n = 3, k = 3 + +**Output:** "213" + +**Example 2:** + +**Input:** n = 4, k = 9 + +**Output:** "2314" + +**Example 3:** + +**Input:** n = 3, k = 1 + +**Output:** "123" + +**Constraints:** + +* `1 <= n <= 9` +* `1 <= k <= n!` \ No newline at end of file diff --git a/src/Algorithms/0061.rotate-list/rotate-list.php b/src/Algorithms/s0061_rotate_list/Solution.php similarity index 95% rename from src/Algorithms/0061.rotate-list/rotate-list.php rename to src/Algorithms/s0061_rotate_list/Solution.php index 545c45c..bdb37a4 100644 --- a/src/Algorithms/0061.rotate-list/rotate-list.php +++ b/src/Algorithms/s0061_rotate_list/Solution.php @@ -1,57 +1,57 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @param Integer $k - * @return ListNode - */ - function rotateRight($head, $k) { - if($head == null){ - return $head; - } - $k = ($k == 0) ? 0 : $k % self::getLen($head); - if($k == 0){ - return $head; - } - $head1 = self::reverse(null, $head); - $dummyHead = new ListNode(0); - $dummyHead->next = $head1; - $cur = $dummyHead->next; - $pre = $dummyHead; - while($k > 0){ - $pre = $cur; - $cur = $cur->next; - $k--; - } - $pre->next = null; - $head2 = self::reverse(null, $cur); - return self::reverse($head2, $head1); - } - function getLen($head){ - $cnt = 0; - while($head != null){ - $cnt++; - $head = $head->next; - } - return $cnt; - } - function reverse($pre,$head) { - $tmp; - $cur = $head; - while($cur != null) { - $tmp = $cur->next; - $cur->next = $pre; - $pre = $cur; - $cur = $tmp; - } - return $pre; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @param Integer $k + * @return ListNode + */ + function rotateRight($head, $k) { + if($head == null){ + return $head; + } + $k = ($k == 0) ? 0 : $k % self::getLen($head); + if($k == 0){ + return $head; + } + $head1 = self::reverse(null, $head); + $dummyHead = new ListNode(0); + $dummyHead->next = $head1; + $cur = $dummyHead->next; + $pre = $dummyHead; + while($k > 0){ + $pre = $cur; + $cur = $cur->next; + $k--; + } + $pre->next = null; + $head2 = self::reverse(null, $cur); + return self::reverse($head2, $head1); + } + function getLen($head){ + $cnt = 0; + while($head != null){ + $cnt++; + $head = $head->next; + } + return $cnt; + } + function reverse($pre,$head) { + $tmp; + $cur = $head; + while($cur != null) { + $tmp = $cur->next; + $cur->next = $pre; + $pre = $cur; + $cur = $tmp; + } + return $pre; + } +} diff --git a/src/Algorithms/s0061_rotate_list/readme.md b/src/Algorithms/s0061_rotate_list/readme.md new file mode 100644 index 0000000..f9cce52 --- /dev/null +++ b/src/Algorithms/s0061_rotate_list/readme.md @@ -0,0 +1,27 @@ +61\. Rotate List + +Medium + +Given the `head` of a linked list, rotate the list to the right by `k` places. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg) + +**Input:** head = [1,2,3,4,5], k = 2 + +**Output:** [4,5,1,2,3] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg) + +**Input:** head = [0,1,2], k = 4 + +**Output:** [2,0,1] + +**Constraints:** + +* The number of nodes in the list is in the range `[0, 500]`. +* `-100 <= Node.val <= 100` +* 0 <= k <= 2 * 109 \ No newline at end of file diff --git a/src/Algorithms/0062.unique-paths/unique-paths.php b/src/Algorithms/s0062_unique_paths/Solution.php similarity index 95% rename from src/Algorithms/0062.unique-paths/unique-paths.php rename to src/Algorithms/s0062_unique_paths/Solution.php index cde6c0f..7c94e9f 100644 --- a/src/Algorithms/0062.unique-paths/unique-paths.php +++ b/src/Algorithms/s0062_unique_paths/Solution.php @@ -1,22 +1,22 @@ -class Solution { - - /** - * @param Integer $m - * @param Integer $n - * @return Integer - */ - function uniquePaths($m, $n) { - $dp=array_fill(0, $m, array_fill(0, $n, 0)); - - $dp[0] = array_fill(0, $n, 1); - - for($r=0;$r<$m;$r++) $dp[$r][0]=1; - - for($r=1;$r<$m;$r++){ - for($c=1;$c<$n;$c++){ - $dp[$r][$c]=$dp[$r-1][$c]+$dp[$r][$c-1]; - } - } - return $dp[$m-1][$n-1]; - } -} +class Solution { + + /** + * @param Integer $m + * @param Integer $n + * @return Integer + */ + function uniquePaths($m, $n) { + $dp=array_fill(0, $m, array_fill(0, $n, 0)); + + $dp[0] = array_fill(0, $n, 1); + + for($r=0;$r<$m;$r++) $dp[$r][0]=1; + + for($r=1;$r<$m;$r++){ + for($c=1;$c<$n;$c++){ + $dp[$r][$c]=$dp[$r-1][$c]+$dp[$r][$c-1]; + } + } + return $dp[$m-1][$n-1]; + } +} diff --git a/src/Algorithms/s0062_unique_paths/readme.md b/src/Algorithms/s0062_unique_paths/readme.md new file mode 100644 index 0000000..eaf4311 --- /dev/null +++ b/src/Algorithms/s0062_unique_paths/readme.md @@ -0,0 +1,47 @@ +62\. Unique Paths + +Medium + +A robot is located at the top-left corner of a `m x n` grid (marked 'Start' in the diagram below). + +The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). + +How many possible unique paths are there? + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) + +**Input:** m = 3, n = 7 + +**Output:** 28 + +**Example 2:** + +**Input:** m = 3, n = 2 + +**Output:** 3 + +**Explanation:** + + From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: + 1. Right -> Down -> Down + 2. Down -> Down -> Right + 3. Down -> Right -> Down + +**Example 3:** + +**Input:** m = 7, n = 3 + +**Output:** 28 + +**Example 4:** + +**Input:** m = 3, n = 3 + +**Output:** 6 + +**Constraints:** + +* `1 <= m, n <= 100` +* It's guaranteed that the answer will be less than or equal to 2 * 109. \ No newline at end of file diff --git a/src/Algorithms/0063.unique-paths-ii/unique-paths-ii.php b/src/Algorithms/s0063_unique_paths_ii/Solution.php similarity index 97% rename from src/Algorithms/0063.unique-paths-ii/unique-paths-ii.php rename to src/Algorithms/s0063_unique_paths_ii/Solution.php index ac63268..32ef0e0 100644 --- a/src/Algorithms/0063.unique-paths-ii/unique-paths-ii.php +++ b/src/Algorithms/s0063_unique_paths_ii/Solution.php @@ -1,32 +1,32 @@ -class Solution { - - /** - * @param Integer[][] $obstacleGrid - * @return Integer - */ - function uniquePathsWithObstacles($obstacleGrid) { - $rows = count($obstacleGrid); - $cols = count($obstacleGrid[0]); - $temp=array_fill(0, $rows, array_fill(0, $cols, 0)); - // If starting point is Obstacle, no way to reach end. - if($obstacleGrid[0][0]==1) - return 0; - // Starting point. - $temp[0][0]=1; - for($row=0;$row<$rows;$row++){ - for ($col=0;$col<$cols;$col++){ - if($col==0 && $row==0) - continue; - if($obstacleGrid[$row][$col]!=1){ - $upVal=($row-1)<0?0: $temp[$row-1][$col]; - $leftVal=($col-1)<0?0: $temp[$row][$col-1]; - // Number of ways to reach current cell. - // No. of ways to reach uppper cell + No.of ways to reach left cell. - $temp[$row][$col]=$upVal+$leftVal; - } - - } - } - return $temp[$rows-1][$cols-1]; - } -} +class Solution { + + /** + * @param Integer[][] $obstacleGrid + * @return Integer + */ + function uniquePathsWithObstacles($obstacleGrid) { + $rows = count($obstacleGrid); + $cols = count($obstacleGrid[0]); + $temp=array_fill(0, $rows, array_fill(0, $cols, 0)); + // If starting point is Obstacle, no way to reach end. + if($obstacleGrid[0][0]==1) + return 0; + // Starting point. + $temp[0][0]=1; + for($row=0;$row<$rows;$row++){ + for ($col=0;$col<$cols;$col++){ + if($col==0 && $row==0) + continue; + if($obstacleGrid[$row][$col]!=1){ + $upVal=($row-1)<0?0: $temp[$row-1][$col]; + $leftVal=($col-1)<0?0: $temp[$row][$col-1]; + // Number of ways to reach current cell. + // No. of ways to reach uppper cell + No.of ways to reach left cell. + $temp[$row][$col]=$upVal+$leftVal; + } + + } + } + return $temp[$rows-1][$cols-1]; + } +} diff --git a/src/Algorithms/s0063_unique_paths_ii/readme.md b/src/Algorithms/s0063_unique_paths_ii/readme.md new file mode 100644 index 0000000..2d511b1 --- /dev/null +++ b/src/Algorithms/s0063_unique_paths_ii/readme.md @@ -0,0 +1,36 @@ +63\. Unique Paths II + +Medium + +A robot is located at the top-left corner of a `m x n` grid (marked 'Start' in the diagram below). + +The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). + +Now consider if some obstacles are added to the grids. How many unique paths would there be? + +An obstacle and space is marked as `1` and `0` respectively in the grid. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg) + +**Input:** obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] + +**Output:** 2 + +**Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg) + +**Input:** obstacleGrid = [[0,1],[0,0]] + +**Output:** 1 + +**Constraints:** + +* `m == obstacleGrid.length` +* `n == obstacleGrid[i].length` +* `1 <= m, n <= 100` +* `obstacleGrid[i][j]` is `0` or `1`. \ No newline at end of file diff --git a/src/Algorithms/0064.minimum-path-sum/minimum-path-sum.php b/src/Algorithms/s0064_minimum_path_sum/Solution.php similarity index 96% rename from src/Algorithms/0064.minimum-path-sum/minimum-path-sum.php rename to src/Algorithms/s0064_minimum_path_sum/Solution.php index 2529e67..c6be698 100644 --- a/src/Algorithms/0064.minimum-path-sum/minimum-path-sum.php +++ b/src/Algorithms/s0064_minimum_path_sum/Solution.php @@ -1,21 +1,21 @@ -class Solution { - - /** - * @param Integer[][] $grid - * @return Integer - */ - function minPathSum($grid) { - $m = count($grid); $n = count($grid[0]); - $dp = array_fill(0, $m, array_fill(0, $n, 0)); - $dp[0][0] = $grid[0][0]; - for($i = 1; $i < $m; $i++) $dp[$i][0] = $dp[$i-1][0] + $grid[$i][0]; - for($i = 1; $i < $n; $i++) $dp[0][$i] = $dp[0][$i-1] + $grid[0][$i]; - - for($j = 1; $j < $n; $j++){ - for($i = 1; $i < $m; $i++){ - $dp[$i][$j] = $grid[$i][$j] + min($dp[$i-1][$j],$dp[$i][$j-1]); - } - } - return $dp[$m-1][$n-1]; - } -} +class Solution { + + /** + * @param Integer[][] $grid + * @return Integer + */ + function minPathSum($grid) { + $m = count($grid); $n = count($grid[0]); + $dp = array_fill(0, $m, array_fill(0, $n, 0)); + $dp[0][0] = $grid[0][0]; + for($i = 1; $i < $m; $i++) $dp[$i][0] = $dp[$i-1][0] + $grid[$i][0]; + for($i = 1; $i < $n; $i++) $dp[0][$i] = $dp[0][$i-1] + $grid[0][$i]; + + for($j = 1; $j < $n; $j++){ + for($i = 1; $i < $m; $i++){ + $dp[$i][$j] = $grid[$i][$j] + min($dp[$i-1][$j],$dp[$i][$j-1]); + } + } + return $dp[$m-1][$n-1]; + } +} diff --git a/src/Algorithms/s0064_minimum_path_sum/readme.md b/src/Algorithms/s0064_minimum_path_sum/readme.md new file mode 100644 index 0000000..fa60cb1 --- /dev/null +++ b/src/Algorithms/s0064_minimum_path_sum/readme.md @@ -0,0 +1,30 @@ +64\. Minimum Path Sum + +Medium + +Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. + +**Note:** You can only move either down or right at any point in time. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg) + +**Input:** grid = [[1,3,1],[1,5,1],[4,2,1]] + +**Output:** 7 + +**Explanation:** Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. + +**Example 2:** + +**Input:** grid = [[1,2,3],[4,5,6]] + +**Output:** 12 + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 200` +* `0 <= grid[i][j] <= 100` \ No newline at end of file diff --git a/src/Algorithms/0065.valid-number/valid-number.php b/src/Algorithms/s0065_valid_number/Solution.php similarity index 96% rename from src/Algorithms/0065.valid-number/valid-number.php rename to src/Algorithms/s0065_valid_number/Solution.php index 6763642..b65b8fc 100644 --- a/src/Algorithms/0065.valid-number/valid-number.php +++ b/src/Algorithms/s0065_valid_number/Solution.php @@ -1,58 +1,58 @@ -class Solution { - - /** - * @param String $s - * @return Boolean - */ - function isNumber($s) { - $isE = false; - $isPoint = false; - $lastChar = -1; - $llastChar = -1; - if(strlen($s)==1 && !(ord($s[0])>=48 && ord($s[0])<=57)){ - return false; - } - $s=trim($s); - for($i=0;$i=48 && $t<=57) || $t==101 || $t== 43 || $t==45 || $t==46)){ - return false; - } - if($t == 101){ - if($isE){ - return false; - } - if($i == strlen($s)-1){ - return false; - } - if($lastChar==43 || $lastChar==45 || $lastChar==46){ - if($llastChar == -1){ - return false; - } - } - $isE = true; - } - if($t == 46 ){ - if($isE){ - return false; - } - if($i == strlen($s)-1 && !($lastChar>=48 && $lastChar<=57)){ - return false; - } - if($isPoint){ - return false; - } - $isPoint = true; - } - if(($t==43 || $t==45)&& $i!=0 && ($lastChar!=101 ||($lastChar==101 && $i == strlen($s)-1))){ - return false; - } - $llastChar = $lastChar; - $lastChar = $t; - } - return true; - } -} +class Solution { + + /** + * @param String $s + * @return Boolean + */ + function isNumber($s) { + $isE = false; + $isPoint = false; + $lastChar = -1; + $llastChar = -1; + if(strlen($s)==1 && !(ord($s[0])>=48 && ord($s[0])<=57)){ + return false; + } + $s=trim($s); + for($i=0;$i=48 && $t<=57) || $t==101 || $t== 43 || $t==45 || $t==46)){ + return false; + } + if($t == 101){ + if($isE){ + return false; + } + if($i == strlen($s)-1){ + return false; + } + if($lastChar==43 || $lastChar==45 || $lastChar==46){ + if($llastChar == -1){ + return false; + } + } + $isE = true; + } + if($t == 46 ){ + if($isE){ + return false; + } + if($i == strlen($s)-1 && !($lastChar>=48 && $lastChar<=57)){ + return false; + } + if($isPoint){ + return false; + } + $isPoint = true; + } + if(($t==43 || $t==45)&& $i!=0 && ($lastChar!=101 ||($lastChar==101 && $i == strlen($s)-1))){ + return false; + } + $llastChar = $lastChar; + $lastChar = $t; + } + return true; + } +} diff --git a/src/Algorithms/s0065_valid_number/readme.md b/src/Algorithms/s0065_valid_number/readme.md new file mode 100644 index 0000000..da9099c --- /dev/null +++ b/src/Algorithms/s0065_valid_number/readme.md @@ -0,0 +1,54 @@ +65\. Valid Number + +Hard + +A **valid number** can be split up into these components (in order): + +1. A **decimal number** or an **integer**. +2. (Optional) An `'e'` or `'E'`, followed by an **integer**. + +A **decimal number** can be split up into these components (in order): + +1. (Optional) A sign character (either `'+'` or `'-'`). +2. One of the following formats: + 1. One or more digits, followed by a dot `'.'`. + 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. + 3. A dot `'.'`, followed by one or more digits. + +An **integer** can be split up into these components (in order): + +1. (Optional) A sign character (either `'+'` or `'-'`). +2. One or more digits. + +For example, all the following are valid numbers: `["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]`, while the following are not valid numbers: `["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]`. + +Given a string `s`, return `true` _if_ `s` _is a **valid number**_. + +**Example 1:** + +**Input:** s = "0" + +**Output:** true + +**Example 2:** + +**Input:** s = "e" + +**Output:** false + +**Example 3:** + +**Input:** s = "." + +**Output:** false + +**Example 4:** + +**Input:** s = ".1" + +**Output:** true + +**Constraints:** + +* `1 <= s.length <= 20` +* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`. \ No newline at end of file diff --git a/src/Algorithms/0066.plus-one/plus-one.php b/src/Algorithms/s0066_plus_one/Solution.php similarity index 96% rename from src/Algorithms/0066.plus-one/plus-one.php rename to src/Algorithms/s0066_plus_one/Solution.php index 8d2bb09..9e51d6c 100644 --- a/src/Algorithms/0066.plus-one/plus-one.php +++ b/src/Algorithms/s0066_plus_one/Solution.php @@ -1,24 +1,24 @@ -class Solution { - - /** - * @param Integer[] $digits - * @return Integer[] - */ - function plusOne($digits) { - $carry=1; - for($i=count($digits)-1;$i>=0;$i--){ - $temp=($digits[$i]+$carry)%10; - $carry=intval(($digits[$i]+$carry)/10); - $digits[$i]=$temp; - } - if($carry==0)return $digits; - else{ - $res=array_fill(0, count($digits) + 1, 0); - $res[0]=$carry; - for($i=0;$i=0;$i--){ + $temp=($digits[$i]+$carry)%10; + $carry=intval(($digits[$i]+$carry)/10); + $digits[$i]=$temp; + } + if($carry==0)return $digits; + else{ + $res=array_fill(0, count($digits) + 1, 0); + $res[0]=$carry; + for($i=0;$i= 0 || $j >= 0 || $carry > 0) - { - $sum = $carry; - if($i >= 0) $sum += ord($a[$i--]) - ord('0'); - if($j >= 0) $sum += ord($b[$j--]) - ord('0'); - $sb .= chr($sum % 2 + ord('0')); - $carry = intval($sum / 2); - } - return strrev($sb); - } +class Solution { + + /** + * @param String $a + * @param String $b + * @return String + */ + function addBinary($a, $b) { + $sb = ""; + $i = strlen($a) - 1; + $j = strlen($b) - 1; + $carry = 0; + + while($i >= 0 || $j >= 0 || $carry > 0) + { + $sum = $carry; + if($i >= 0) $sum += ord($a[$i--]) - ord('0'); + if($j >= 0) $sum += ord($b[$j--]) - ord('0'); + $sb .= chr($sum % 2 + ord('0')); + $carry = intval($sum / 2); + } + return strrev($sb); + } } diff --git a/src/Algorithms/s0067_add_binary/readme.md b/src/Algorithms/s0067_add_binary/readme.md new file mode 100644 index 0000000..ea1380e --- /dev/null +++ b/src/Algorithms/s0067_add_binary/readme.md @@ -0,0 +1,23 @@ +67\. Add Binary + +Easy + +Given two binary strings `a` and `b`, return _their sum as a binary string_. + +**Example 1:** + +**Input:** a = "11", b = "1" + +**Output:** "100" + +**Example 2:** + +**Input:** a = "1010", b = "1011" + +**Output:** "10101" + +**Constraints:** + +* 1 <= a.length, b.length <= 104 +* `a` and `b` consist only of `'0'` or `'1'` characters. +* Each string does not contain leading zeros except for the zero itself. \ No newline at end of file diff --git a/src/Algorithms/0068.text-justification/text-justification.php b/src/Algorithms/s0068_text_justification/Solution.php similarity index 96% rename from src/Algorithms/0068.text-justification/text-justification.php rename to src/Algorithms/s0068_text_justification/Solution.php index 331be36..0941b9e 100644 --- a/src/Algorithms/0068.text-justification/text-justification.php +++ b/src/Algorithms/s0068_text_justification/Solution.php @@ -1,43 +1,43 @@ -class Solution { - - /** - * @param String[] $words - * @param Integer $maxWidth - * @return String[] - */ - function fullJustify($words, $maxWidth) { - $n = count($words); - $beg = 0; - $res = []; - while ($beg < $n) { - $end = $beg; - $used = 0; - while ($end < $n && strlen($words[$end])+$used <= $maxWidth) { - $used += strlen($words[$end++])+1; - } - $sb = ""; - if ($end == $n) { - for ($i = $beg; $i < $end; ++$i) { - $sb .= $words[$i]; - if ($i < $end-1) $sb .= ' '; - } - } else { - $c = $maxWidth - $used + ($end-$beg); - $slots = $end - $beg - 1; - for ($i = 0; $i < $end-$beg-1; ++$i) { - $sb .= $words[$i+$beg]; - for ($j = 0; $j < intval($c/$slots); ++$j) { - $sb .= ' '; - } - if ($i < $c%$slots) $sb .= ' '; - } - $sb .= $words[$end-1]; - } - $c = $maxWidth - strlen($sb); - while ($c-- > 0) $sb .= ' '; - array_push($res, $sb); - $beg = $end; - } - return $res; - } +class Solution { + + /** + * @param String[] $words + * @param Integer $maxWidth + * @return String[] + */ + function fullJustify($words, $maxWidth) { + $n = count($words); + $beg = 0; + $res = []; + while ($beg < $n) { + $end = $beg; + $used = 0; + while ($end < $n && strlen($words[$end])+$used <= $maxWidth) { + $used += strlen($words[$end++])+1; + } + $sb = ""; + if ($end == $n) { + for ($i = $beg; $i < $end; ++$i) { + $sb .= $words[$i]; + if ($i < $end-1) $sb .= ' '; + } + } else { + $c = $maxWidth - $used + ($end-$beg); + $slots = $end - $beg - 1; + for ($i = 0; $i < $end-$beg-1; ++$i) { + $sb .= $words[$i+$beg]; + for ($j = 0; $j < intval($c/$slots); ++$j) { + $sb .= ' '; + } + if ($i < $c%$slots) $sb .= ' '; + } + $sb .= $words[$end-1]; + } + $c = $maxWidth - strlen($sb); + while ($c-- > 0) $sb .= ' '; + array_push($res, $sb); + $beg = $end; + } + return $res; + } } diff --git a/src/Algorithms/s0068_text_justification/readme.md b/src/Algorithms/s0068_text_justification/readme.md new file mode 100644 index 0000000..78e9dd7 --- /dev/null +++ b/src/Algorithms/s0068_text_justification/readme.md @@ -0,0 +1,45 @@ +68\. Text Justification + +Hard + +Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. + +You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. + +Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. + +For the last line of text, it should be left-justified and no extra space is inserted between words. + +**Note:** + +* A word is defined as a character sequence consisting of non-space characters only. +* Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. +* The input array `words` contains at least one word. + +**Example 1:** + +**Input:** words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 + +**Output:** [ "This is an", "example of text", "justification. " ] + +**Example 2:** + +**Input:** words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 + +**Output:** [ "What must be", "acknowledgment ", "shall be " ] + +**Explanation:** Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified becase it contains only one word. + +**Example 3:** + +**Input:** words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 + +**Output:** [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ] + +**Constraints:** + +* `1 <= words.length <= 300` +* `1 <= words[i].length <= 20` +* `words[i]` consists of only English letters and symbols. +* `1 <= maxWidth <= 100` +* `words[i].length <= maxWidth` \ No newline at end of file diff --git a/src/Algorithms/0069.sqrtx/sqrtx.php b/src/Algorithms/s0069_sqrtx/Solution.php similarity index 95% rename from src/Algorithms/0069.sqrtx/sqrtx.php rename to src/Algorithms/s0069_sqrtx/Solution.php index 9337ec2..6a51464 100644 --- a/src/Algorithms/0069.sqrtx/sqrtx.php +++ b/src/Algorithms/s0069_sqrtx/Solution.php @@ -1,25 +1,25 @@ -class Solution { - - /** - * @param Integer $x - * @return Integer - */ - function mySqrt($x) { - if ($x <= 1) return $x; - return self::binarySearch(1, intval($x / 2) + 1, $x); - } - - function binarySearch($l, $r, $val) { - while ($l < $r) { - $m = intval(($r - $l) / 2) + $l; - $v = $m * $m; - if ($v == $val) return $m; - else if ($v > $val) { - $r = $m; - } else { - $l = $m + 1; - } - } - return $l - 1; - } -} +class Solution { + + /** + * @param Integer $x + * @return Integer + */ + function mySqrt($x) { + if ($x <= 1) return $x; + return self::binarySearch(1, intval($x / 2) + 1, $x); + } + + function binarySearch($l, $r, $val) { + while ($l < $r) { + $m = intval(($r - $l) / 2) + $l; + $v = $m * $m; + if ($v == $val) return $m; + else if ($v > $val) { + $r = $m; + } else { + $l = $m + 1; + } + } + return $l - 1; + } +} diff --git a/src/Algorithms/s0069_sqrtx/readme.md b/src/Algorithms/s0069_sqrtx/readme.md new file mode 100644 index 0000000..005177f --- /dev/null +++ b/src/Algorithms/s0069_sqrtx/readme.md @@ -0,0 +1,27 @@ +69\. Sqrt(x) + +Easy + +Given a non-negative integer `x`, compute and return _the square root of_ `x`. + +Since the return type is an integer, the decimal digits are **truncated**, and only **the integer part** of the result is returned. + +**Note:** You are not allowed to use any built-in exponent function or operator, such as `pow(x, 0.5)` or `x ** 0.5`. + +**Example 1:** + +**Input:** x = 4 + +**Output:** 2 + +**Example 2:** + +**Input:** x = 8 + +**Output:** 2 + +**Explanation:** The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. + +**Constraints:** + +* 0 <= x <= 231 - 1 diff --git a/src/Algorithms/0070.climbing-stairs/climbing-stairs.php b/src/Algorithms/s0070_climbing_stairs/Solution.php similarity index 93% rename from src/Algorithms/0070.climbing-stairs/climbing-stairs.php rename to src/Algorithms/s0070_climbing_stairs/Solution.php index 8075fc8..d4efde6 100644 --- a/src/Algorithms/0070.climbing-stairs/climbing-stairs.php +++ b/src/Algorithms/s0070_climbing_stairs/Solution.php @@ -1,23 +1,23 @@ -class Solution { - - /** - * @param Integer $n - * @return Integer - */ - function climbStairs($n) { - if ($n == 2) - return 2; - else if ($n == 1) - return 1; - $a = 0; - $b = 1; - $c = 0; - for ($i = 0; $i < $n; $i++) - { - $c = $a + $b; - $a = $b; - $b = $c; - } - return $c; - } +class Solution { + + /** + * @param Integer $n + * @return Integer + */ + function climbStairs($n) { + if ($n == 2) + return 2; + else if ($n == 1) + return 1; + $a = 0; + $b = 1; + $c = 0; + for ($i = 0; $i < $n; $i++) + { + $c = $a + $b; + $a = $b; + $b = $c; + } + return $c; + } } diff --git a/src/Algorithms/s0070_climbing_stairs/readme.md b/src/Algorithms/s0070_climbing_stairs/readme.md new file mode 100644 index 0000000..41c3a2a --- /dev/null +++ b/src/Algorithms/s0070_climbing_stairs/readme.md @@ -0,0 +1,27 @@ +70\. Climbing Stairs + +Easy + +You are climbing a staircase. It takes `n` steps to reach the top. + +Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? + +**Example 1:** + +**Input:** n = 2 + +**Output:** 2 + +**Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps + +**Example 2:** + +**Input:** n = 3 + +**Output:** 3 + +**Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step + +**Constraints:** + +* `1 <= n <= 45` \ No newline at end of file diff --git a/src/Algorithms/0071.simplify-path/simplify-path.php b/src/Algorithms/s0071_simplify_path/Solution.php similarity index 96% rename from src/Algorithms/0071.simplify-path/simplify-path.php rename to src/Algorithms/s0071_simplify_path/Solution.php index 3e8451b..d6fa851 100644 --- a/src/Algorithms/0071.simplify-path/simplify-path.php +++ b/src/Algorithms/s0071_simplify_path/Solution.php @@ -1,20 +1,20 @@ -class Solution { - - /** - * @param String $path - * @return String - */ - function simplifyPath($path) { - if(null == $path || empty($path)) return ""; - $stack = new SplQueue(); - foreach(explode("/", $path) as $cur) { - if($cur == "..") {if (!$stack->isEmpty()) $stack->pop();} - else if($cur != "" && $cur != ".") $stack->push($cur); - } - - if($stack->isEmpty()) return "/"; - $sb = ""; - while(!$stack->isEmpty()) $sb .= "/" . $stack->shift(); - return $sb; - } +class Solution { + + /** + * @param String $path + * @return String + */ + function simplifyPath($path) { + if(null == $path || empty($path)) return ""; + $stack = new SplQueue(); + foreach(explode("/", $path) as $cur) { + if($cur == "..") {if (!$stack->isEmpty()) $stack->pop();} + else if($cur != "" && $cur != ".") $stack->push($cur); + } + + if($stack->isEmpty()) return "/"; + $sb = ""; + while(!$stack->isEmpty()) $sb .= "/" . $stack->shift(); + return $sb; + } } diff --git a/src/Algorithms/s0071_simplify_path/readme.md b/src/Algorithms/s0071_simplify_path/readme.md new file mode 100644 index 0000000..af8fa8b --- /dev/null +++ b/src/Algorithms/s0071_simplify_path/readme.md @@ -0,0 +1,52 @@ +71\. Simplify Path + +Medium + +Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**. + +In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names. + +The **canonical path** should have the following format: + +* The path starts with a single slash `'/'`. +* Any two directories are separated by a single slash `'/'`. +* The path does not end with a trailing `'/'`. +* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`) + +Return _the simplified **canonical path**_. + +**Example 1:** + +**Input:** path = "/home/" + +**Output:** "/home" + +**Explanation:** Note that there is no trailing slash after the last directory name. + +**Example 2:** + +**Input:** path = "/../" + +**Output:** "/" + +**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go. + +**Example 3:** + +**Input:** path = "/home//foo/" + +**Output:** "/home/foo" + +**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one. + +**Example 4:** + +**Input:** path = "/a/./b/../../c/" + +**Output:** "/c" + +**Constraints:** + +* `1 <= path.length <= 3000` +* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`. +* `path` is a valid absolute Unix path. \ No newline at end of file diff --git a/src/Algorithms/0072.edit-distance/edit-distance.php b/src/Algorithms/s0072_edit_distance/Solution.php similarity index 96% rename from src/Algorithms/0072.edit-distance/edit-distance.php rename to src/Algorithms/s0072_edit_distance/Solution.php index 4d868a4..c1acd94 100644 --- a/src/Algorithms/0072.edit-distance/edit-distance.php +++ b/src/Algorithms/s0072_edit_distance/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param String $word1 - * @param String $word2 - * @return Integer - */ - function minDistance($word1, $word2) { - $n1 = strlen($word1); $n2 = strlen($word2); - if ($n2 > $n1) - return self::minDistance($word2, $word1); - $dp = array_fill(0, $n2+1, 0); - for ($j = 0; $j <= $n2; $j++) - $dp[$j] = $j; - for ($i = 1; $i <= $n1; $i++) { - $pre = $dp[0]; - $dp[0] = $i; - for ($j = 1; $j <= $n2; $j++) { - $tmp = $dp[$j]; - $dp[$j] = $word1[$i-1] != $word2[$j-1] - ? 1 + min($pre, min($dp[$j], $dp[$j-1])) - : $pre; - $pre = $tmp; - } - } - return $dp[$n2]; - } +class Solution { + + /** + * @param String $word1 + * @param String $word2 + * @return Integer + */ + function minDistance($word1, $word2) { + $n1 = strlen($word1); $n2 = strlen($word2); + if ($n2 > $n1) + return self::minDistance($word2, $word1); + $dp = array_fill(0, $n2+1, 0); + for ($j = 0; $j <= $n2; $j++) + $dp[$j] = $j; + for ($i = 1; $i <= $n1; $i++) { + $pre = $dp[0]; + $dp[0] = $i; + for ($j = 1; $j <= $n2; $j++) { + $tmp = $dp[$j]; + $dp[$j] = $word1[$i-1] != $word2[$j-1] + ? 1 + min($pre, min($dp[$j], $dp[$j-1])) + : $pre; + $pre = $tmp; + } + } + return $dp[$n2]; + } } diff --git a/src/Algorithms/s0072_edit_distance/readme.md b/src/Algorithms/s0072_edit_distance/readme.md new file mode 100644 index 0000000..fbd054c --- /dev/null +++ b/src/Algorithms/s0072_edit_distance/readme.md @@ -0,0 +1,32 @@ +72\. Edit Distance + +Hard + +Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. + +You have the following three operations permitted on a word: + +* Insert a character +* Delete a character +* Replace a character + +**Example 1:** + +**Input:** word1 = "horse", word2 = "ros" + +**Output:** 3 + +**Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') + +**Example 2:** + +**Input:** word1 = "intention", word2 = "execution" + +**Output:** 5 + +**Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') + +**Constraints:** + +* `0 <= word1.length, word2.length <= 500` +* `word1` and `word2` consist of lowercase English letters. \ No newline at end of file diff --git a/src/Algorithms/0073.set-matrix-zeroes/set-matrix-zeroes.php b/src/Algorithms/s0073_set_matrix_zeroes/Solution.php similarity index 97% rename from src/Algorithms/0073.set-matrix-zeroes/set-matrix-zeroes.php rename to src/Algorithms/s0073_set_matrix_zeroes/Solution.php index def0ea5..2716852 100644 --- a/src/Algorithms/0073.set-matrix-zeroes/set-matrix-zeroes.php +++ b/src/Algorithms/s0073_set_matrix_zeroes/Solution.php @@ -1,35 +1,35 @@ -class Solution { - - /** - * @param Integer[][] $matrix - * @return NULL - */ - function setZeroes(&$matrix) { - if(count($matrix)==0 || count($matrix[0])==0) return ; - // check whether the first row has zero; - $firstRowZero = false; - for($j=0; $j-231 <= matrix[i][j] <= 231 - 1 + +**Follow up:** + +* A straightforward solution using `O(mn)` space is probably a bad idea. +* A simple improvement uses `O(m + n)` space, but still not the best solution. +* Could you devise a constant space solution? \ No newline at end of file diff --git a/src/Algorithms/0074.search-a-2d-matrix/search-a-2d-matrix.php b/src/Algorithms/s0074_search_a_2d_matrix/Solution.php similarity index 97% rename from src/Algorithms/0074.search-a-2d-matrix/search-a-2d-matrix.php rename to src/Algorithms/s0074_search_a_2d_matrix/Solution.php index f3d1c44..93b8829 100644 --- a/src/Algorithms/0074.search-a-2d-matrix/search-a-2d-matrix.php +++ b/src/Algorithms/s0074_search_a_2d_matrix/Solution.php @@ -1,20 +1,20 @@ -class Solution { - - /** - * @param Integer[][] $matrix - * @param Integer $target - * @return Boolean - */ - function searchMatrix($matrix, $target) { - if ($matrix == null || count($matrix) == 0 || $matrix[0] == null || count($matrix[0]) == 0) return false; - $col = count($matrix[0]) - 1; - $row = 0; - // start from the up left corner, if smaller than target, then go down, if larger then go left - while ($row < count($matrix) && $col >= 0) { - if ($matrix[$row][$col] == $target) return true; - if ($matrix[$row][$col] < $target) $row++; - else $col--; - } - return false; - } +class Solution { + + /** + * @param Integer[][] $matrix + * @param Integer $target + * @return Boolean + */ + function searchMatrix($matrix, $target) { + if ($matrix == null || count($matrix) == 0 || $matrix[0] == null || count($matrix[0]) == 0) return false; + $col = count($matrix[0]) - 1; + $row = 0; + // start from the up left corner, if smaller than target, then go down, if larger then go left + while ($row < count($matrix) && $col >= 0) { + if ($matrix[$row][$col] == $target) return true; + if ($matrix[$row][$col] < $target) $row++; + else $col--; + } + return false; + } } diff --git a/src/Algorithms/s0074_search_a_2d_matrix/readme.md b/src/Algorithms/s0074_search_a_2d_matrix/readme.md new file mode 100644 index 0000000..ce4e033 --- /dev/null +++ b/src/Algorithms/s0074_search_a_2d_matrix/readme.md @@ -0,0 +1,31 @@ +74\. Search a 2D Matrix + +Medium + +Write an efficient algorithm that searches for a value in an `m x n` matrix. This matrix has the following properties: + +* Integers in each row are sorted from left to right. +* The first integer of each row is greater than the last integer of the previous row. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/05/mat.jpg) + +**Input:** matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg) + +**Input:** matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 + +**Output:** false + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 100` +* -104 <= matrix[i][j], target <= 104 \ No newline at end of file diff --git a/src/Algorithms/0075.sort-colors/sort-colors.php b/src/Algorithms/s0075_sort_colors/Solution.php similarity index 95% rename from src/Algorithms/0075.sort-colors/sort-colors.php rename to src/Algorithms/s0075_sort_colors/Solution.php index 6fa29b5..e16107f 100644 --- a/src/Algorithms/0075.sort-colors/sort-colors.php +++ b/src/Algorithms/s0075_sort_colors/Solution.php @@ -1,31 +1,31 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return NULL - */ - function sortColors(&$nums) { - $red = 0; $white; - $temp = 0; - for($i = 0; $i < count($nums); $i++) { - if($nums[$i] == 0) { - self::swap($nums, $red,$i); - $red++; - } - } - $white = $red; - - for($i = 0; $i < count($nums); $i++) { - if($nums[$i] == 1) { - self::swap($nums, $white,$i); - $white++; - } - } - } - - function swap(&$array, $i, $j) { - $temp = $array[$i]; - $array[$i] = $array[$j]; - $array[$j] = $temp; - } +class Solution { + + /** + * @param Integer[] $nums + * @return NULL + */ + function sortColors(&$nums) { + $red = 0; $white; + $temp = 0; + for($i = 0; $i < count($nums); $i++) { + if($nums[$i] == 0) { + self::swap($nums, $red,$i); + $red++; + } + } + $white = $red; + + for($i = 0; $i < count($nums); $i++) { + if($nums[$i] == 1) { + self::swap($nums, $white,$i); + $white++; + } + } + } + + function swap(&$array, $i, $j) { + $temp = $array[$i]; + $array[$i] = $array[$j]; + $array[$j] = $temp; + } } diff --git a/src/Algorithms/s0075_sort_colors/readme.md b/src/Algorithms/s0075_sort_colors/readme.md new file mode 100644 index 0000000..4062c6f --- /dev/null +++ b/src/Algorithms/s0075_sort_colors/readme.md @@ -0,0 +1,41 @@ +75\. Sort Colors + +Medium + +Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + +We will use the integers `0`, `1`, and `2` to represent the color red, white, and blue, respectively. + +You must solve this problem without using the library's sort function. + +**Example 1:** + +**Input:** nums = [2,0,2,1,1,0] + +**Output:** [0,0,1,1,2,2] + +**Example 2:** + +**Input:** nums = [2,0,1] + +**Output:** [0,1,2] + +**Example 3:** + +**Input:** nums = [0] + +**Output:** [0] + +**Example 4:** + +**Input:** nums = [1] + +**Output:** [1] + +**Constraints:** + +* `n == nums.length` +* `1 <= n <= 300` +* `nums[i]` is `0`, `1`, or `2`. + +**Follow up:** Could you come up with a one-pass algorithm using only constant extra space? \ No newline at end of file diff --git a/src/Algorithms/0076.minimum-window-substring/minimum-window-substring.php b/src/Algorithms/s0076_minimum_window_substring/Solution.php similarity index 96% rename from src/Algorithms/0076.minimum-window-substring/minimum-window-substring.php rename to src/Algorithms/s0076_minimum_window_substring/Solution.php index d06d62c..316a372 100644 --- a/src/Algorithms/0076.minimum-window-substring/minimum-window-substring.php +++ b/src/Algorithms/s0076_minimum_window_substring/Solution.php @@ -1,44 +1,44 @@ -class Solution { - - /** - * @param String $s - * @param String $t - * @return String - */ - function minWindow($s, $t) { - $alphabetSize = 256; - $T = strlen($t); //The number of characters in t - $S = strlen($s); - - if ($S < $T) return ""; - $tCount = array_fill(0, $alphabetSize, 0); - //Create frequency table for the string t - foreach(str_split($t) as $c){ - $tCount[ord($c)]++; - } - - - $left = 0; - $right = 0; - - $N = strlen($s); - $min = 2147483647; - $res = [-1, -1]; - - while ($right < $N){ - while($right < $N && $T > 0){ - if (--$tCount[ord($s[$right++])] >= 0) $T--; - } - //At this point we are either at the end or we have a substring in S that covers all of T. - while ($left < $right && $T == 0){ - if ($right-$left < $min){ - $min = $right - $left; - $res = [$left, $right]; - } - if (++$tCount[ord($s[$left++])] > 0) $T++; - } - } - - return $min == 2147483647 ? "" : substr($s, $res[0], $res[1] - $res[0]); - } +class Solution { + + /** + * @param String $s + * @param String $t + * @return String + */ + function minWindow($s, $t) { + $alphabetSize = 256; + $T = strlen($t); //The number of characters in t + $S = strlen($s); + + if ($S < $T) return ""; + $tCount = array_fill(0, $alphabetSize, 0); + //Create frequency table for the string t + foreach(str_split($t) as $c){ + $tCount[ord($c)]++; + } + + + $left = 0; + $right = 0; + + $N = strlen($s); + $min = 2147483647; + $res = [-1, -1]; + + while ($right < $N){ + while($right < $N && $T > 0){ + if (--$tCount[ord($s[$right++])] >= 0) $T--; + } + //At this point we are either at the end or we have a substring in S that covers all of T. + while ($left < $right && $T == 0){ + if ($right-$left < $min){ + $min = $right - $left; + $res = [$left, $right]; + } + if (++$tCount[ord($s[$left++])] > 0) $T++; + } + } + + return $min == 2147483647 ? "" : substr($s, $res[0], $res[1] - $res[0]); + } } diff --git a/src/Algorithms/s0076_minimum_window_substring/readme.md b/src/Algorithms/s0076_minimum_window_substring/readme.md new file mode 100644 index 0000000..7c7d492 --- /dev/null +++ b/src/Algorithms/s0076_minimum_window_substring/readme.md @@ -0,0 +1,42 @@ +76\. Minimum Window Substring + +Hard + +Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window substring** of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window. If there is no such substring__, return the empty string_ `""`_._ + +The testcases will be generated such that the answer is **unique**. + +A **substring** is a contiguous sequence of characters within the string. + +**Example 1:** + +**Input:** s = "ADOBECODEBANC", t = "ABC" + +**Output:** "BANC" + +**Explanation:** The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. + +**Example 2:** + +**Input:** s = "a", t = "a" + +**Output:** "a" + +**Explanation:** The entire string s is the minimum window. + +**Example 3:** + +**Input:** s = "a", t = "aa" + +**Output:** "" + +**Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. + +**Constraints:** + +* `m == s.length` +* `n == t.length` +* 1 <= m, n <= 105 +* `s` and `t` consist of uppercase and lowercase English letters. + +**Follow up:** Could you find an algorithm that runs in `O(m + n)` time? \ No newline at end of file diff --git a/src/Algorithms/0077.combinations/combinations.php b/src/Algorithms/s0077_combinations/Solution.php similarity index 96% rename from src/Algorithms/0077.combinations/combinations.php rename to src/Algorithms/s0077_combinations/Solution.php index ddb4ac7..979a73d 100644 --- a/src/Algorithms/0077.combinations/combinations.php +++ b/src/Algorithms/s0077_combinations/Solution.php @@ -1,24 +1,24 @@ -class Solution { - - /** - * @param Integer $n - * @param Integer $k - * @return Integer[][] - */ - function combine($n, $k) { - $list = []; - self::backtrack($list, [], $n, 1,$k); - return $list; - } - - function backtrack(&$list, $tempList, $n, $start,$k) { - if(count($tempList) <= $k) { - if(count($tempList) == $k) array_push($list, $tempList); - for($i = $start; $i <= $n; $i++) { - array_push($tempList, $i); - self::backtrack($list, $tempList, $n, $i + 1, $k); - array_pop($tempList); - } - } - } -} +class Solution { + + /** + * @param Integer $n + * @param Integer $k + * @return Integer[][] + */ + function combine($n, $k) { + $list = []; + self::backtrack($list, [], $n, 1,$k); + return $list; + } + + function backtrack(&$list, $tempList, $n, $start,$k) { + if(count($tempList) <= $k) { + if(count($tempList) == $k) array_push($list, $tempList); + for($i = $start; $i <= $n; $i++) { + array_push($tempList, $i); + self::backtrack($list, $tempList, $n, $i + 1, $k); + array_pop($tempList); + } + } + } +} diff --git a/src/Algorithms/s0077_combinations/readme.md b/src/Algorithms/s0077_combinations/readme.md new file mode 100644 index 0000000..eaae4b4 --- /dev/null +++ b/src/Algorithms/s0077_combinations/readme.md @@ -0,0 +1,24 @@ +77\. Combinations + +Medium + +Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers out of the range_ `[1, n]`. + +You may return the answer in **any order**. + +**Example 1:** + +**Input:** n = 4, k = 2 + +**Output:** [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] + +**Example 2:** + +**Input:** n = 1, k = 1 + +**Output:** [[1]] + +**Constraints:** + +* `1 <= n <= 20` +* `1 <= k <= n` \ No newline at end of file diff --git a/src/Algorithms/0078.subsets/subsets.php b/src/Algorithms/s0078_subsets/Solution.php similarity index 96% rename from src/Algorithms/0078.subsets/subsets.php rename to src/Algorithms/s0078_subsets/Solution.php index 271db83..4be7e2f 100644 --- a/src/Algorithms/0078.subsets/subsets.php +++ b/src/Algorithms/s0078_subsets/Solution.php @@ -1,25 +1,25 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer[][] - */ - function subsets($nums) { - $count = intval(pow(2,count($nums))); - $result = []; - for ($i = 0; $i < $count; $i++) { - $list = []; - $temp = $i; - $index = 0; - while ($temp != 0) { - if (($temp & 1) == 1) { - array_push($list, $nums[$index]); - } - $index++; - $temp = $temp >> 1; - } - array_push($result, $list); - } - return $result; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer[][] + */ + function subsets($nums) { + $count = intval(pow(2,count($nums))); + $result = []; + for ($i = 0; $i < $count; $i++) { + $list = []; + $temp = $i; + $index = 0; + while ($temp != 0) { + if (($temp & 1) == 1) { + array_push($list, $nums[$index]); + } + $index++; + $temp = $temp >> 1; + } + array_push($result, $list); + } + return $result; + } +} diff --git a/src/Algorithms/s0078_subsets/readme.md b/src/Algorithms/s0078_subsets/readme.md new file mode 100644 index 0000000..2bd42ee --- /dev/null +++ b/src/Algorithms/s0078_subsets/readme.md @@ -0,0 +1,25 @@ +78\. Subsets + +Medium + +Given an integer array `nums` of **unique** elements, return _all possible subsets (the power set)_. + +The solution set **must not** contain duplicate subsets. Return the solution in **any order**. + +**Example 1:** + +**Input:** nums = [1,2,3] + +**Output:** [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] + +**Example 2:** + +**Input:** nums = [0] + +**Output:** [[],[0]] + +**Constraints:** + +* `1 <= nums.length <= 10` +* `-10 <= nums[i] <= 10` +* All the numbers of `nums` are **unique**. \ No newline at end of file diff --git a/src/Algorithms/0079.word-search/word-search.php b/src/Algorithms/s0079_word_search/Solution.php similarity index 97% rename from src/Algorithms/0079.word-search/word-search.php rename to src/Algorithms/s0079_word_search/Solution.php index 469a8a4..840c4b0 100644 --- a/src/Algorithms/0079.word-search/word-search.php +++ b/src/Algorithms/s0079_word_search/Solution.php @@ -1,31 +1,31 @@ -class Solution { - - /** - * @param String[][] $board - * @param String $word - * @return Boolean - */ - function exist($board, $word) { - if (count($board) == 0) return false; - $n = count($board); $m = count($board[0]); - if (strlen($word) > $m*$n) return false; - $visited = array_fill(0, $n, array_fill(0, $m, false)); - for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) - if (self::help($i, $j, 0, $board, $word, $visited)) return true; - return false; - } - - function help($i, $j, $k, $board, $word, $visited){ - if ($k == strlen($word)) return true; - if ($i >= count($board) || $i < 0 || $j >= count($board[0]) || $j < 0) - return false; - if ($visited[$i][$j] || $board[$i][$j] != $word[$k]) return false; - $visited[$i][$j] = true; - $b = self::help($i+1, $j, $k+1, $board, $word, $visited) || - self::help($i-1, $j, $k+1, $board, $word, $visited) || - self::help($i, $j-1, $k+1, $board, $word, $visited) || - self::help($i, $j+1, $k+1, $board, $word, $visited); - $visited[$i][$j] = false; - return $b; - } -} +class Solution { + + /** + * @param String[][] $board + * @param String $word + * @return Boolean + */ + function exist($board, $word) { + if (count($board) == 0) return false; + $n = count($board); $m = count($board[0]); + if (strlen($word) > $m*$n) return false; + $visited = array_fill(0, $n, array_fill(0, $m, false)); + for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) + if (self::help($i, $j, 0, $board, $word, $visited)) return true; + return false; + } + + function help($i, $j, $k, $board, $word, $visited){ + if ($k == strlen($word)) return true; + if ($i >= count($board) || $i < 0 || $j >= count($board[0]) || $j < 0) + return false; + if ($visited[$i][$j] || $board[$i][$j] != $word[$k]) return false; + $visited[$i][$j] = true; + $b = self::help($i+1, $j, $k+1, $board, $word, $visited) || + self::help($i-1, $j, $k+1, $board, $word, $visited) || + self::help($i, $j-1, $k+1, $board, $word, $visited) || + self::help($i, $j+1, $k+1, $board, $word, $visited); + $visited[$i][$j] = false; + return $b; + } +} diff --git a/src/Algorithms/s0079_word_search/readme.md b/src/Algorithms/s0079_word_search/readme.md new file mode 100644 index 0000000..0500297 --- /dev/null +++ b/src/Algorithms/s0079_word_search/readme.md @@ -0,0 +1,41 @@ +79\. Word Search + +Medium + +Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_. + +The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/04/word2.jpg) + +**Input:** board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg) + +**Input:** board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" + +**Output:** true + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/10/15/word3.jpg) + +**Input:** board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" + +**Output:** false + +**Constraints:** + +* `m == board.length` +* `n = board[i].length` +* `1 <= m, n <= 6` +* `1 <= word.length <= 15` +* `board` and `word` consists of only lowercase and uppercase English letters. + +**Follow up:** Could you use search pruning to make your solution faster with a larger `board`? \ No newline at end of file diff --git a/src/Algorithms/0080.remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.php b/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php similarity index 95% rename from src/Algorithms/0080.remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.php rename to src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php index bdfde10..f4badd5 100644 --- a/src/Algorithms/0080.remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.php +++ b/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function removeDuplicates(&$nums) { - $j = 0; $c = 0; - for ($i = 1; $i < count($nums); $i++) { - if ($nums[$i] == $nums[$j]) { - $c++; - } - if ($nums[$i] == $nums[$j] && $c == 2) { - $c--; - continue; - } else if ($nums[$i] != $nums[$j]) { - $c = 0; - } - $j++; - $tmp = $nums[$i]; - $nums[$i] = $nums[$j]; - $nums[$j] = $tmp; - } - return $j+1; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function removeDuplicates(&$nums) { + $j = 0; $c = 0; + for ($i = 1; $i < count($nums); $i++) { + if ($nums[$i] == $nums[$j]) { + $c++; + } + if ($nums[$i] == $nums[$j] && $c == 2) { + $c--; + continue; + } else if ($nums[$i] != $nums[$j]) { + $c = 0; + } + $j++; + $tmp = $nums[$i]; + $nums[$i] = $nums[$j]; + $nums[$j] = $tmp; + } + return $j+1; + } +} diff --git a/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/readme.md b/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/readme.md new file mode 100644 index 0000000..fa021a5 --- /dev/null +++ b/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/readme.md @@ -0,0 +1,49 @@ +80\. Remove Duplicates from Sorted Array II + +Medium + +Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. + +Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. + +Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. + +Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. + +**Custom Judge:** + +The judge will test your solution with the following code: + + int[] nums = [...]; // Input array + int[] expectedNums = [...]; // The expected answer with correct length + + int k = removeDuplicates(nums); // Calls your implementation + + assert k == expectedNums.length; + for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; + } + +If all assertions pass, then your solution will be **accepted**. + +**Example 1:** + +**Input:** nums = [1,1,1,2,2,3] + +**Output:** 5, nums = [1,1,2,2,3,\_] + +**Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). + +**Example 2:** + +**Input:** nums = [0,0,1,1,1,1,2,3,3] + +**Output:** 7, nums = [0,0,1,1,2,3,3,\_,\_] + +**Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* -104 <= nums[i] <= 104 +* `nums` is sorted in **non-decreasing** order. \ No newline at end of file diff --git a/src/Algorithms/0081.search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.php b/src/Algorithms/s0081_search_in_rotated_sorted_array_ii/Solution.php similarity index 95% rename from src/Algorithms/0081.search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.php rename to src/Algorithms/s0081_search_in_rotated_sorted_array_ii/Solution.php index 1afd5b5..8e7c2ed 100644 --- a/src/Algorithms/0081.search-in-rotated-sorted-array-ii/search-in-rotated-sorted-array-ii.php +++ b/src/Algorithms/s0081_search_in_rotated_sorted_array_ii/Solution.php @@ -1,17 +1,17 @@ -class Solution { - - /** - * @param Integer[] $nums - * @param Integer $target - * @return Boolean - */ - function search($nums, $target) { - $n = count($nums); - $m = intval($n/2); - for($i=0; $i<$m; $i++) - if($nums[$i] == $target) return true; - for($i=$m; $i<$n; $i++) - if($nums[$i] == $target) return true; - return false; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @param Integer $target + * @return Boolean + */ + function search($nums, $target) { + $n = count($nums); + $m = intval($n/2); + for($i=0; $i<$m; $i++) + if($nums[$i] == $target) return true; + for($i=$m; $i<$n; $i++) + if($nums[$i] == $target) return true; + return false; + } +} diff --git a/src/Algorithms/s0081_search_in_rotated_sorted_array_ii/readme.md b/src/Algorithms/s0081_search_in_rotated_sorted_array_ii/readme.md new file mode 100644 index 0000000..a251430 --- /dev/null +++ b/src/Algorithms/s0081_search_in_rotated_sorted_array_ii/readme.md @@ -0,0 +1,32 @@ +81\. Search in Rotated Sorted Array II + +Medium + +There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). + +Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. + +Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ + +You must decrease the overall operation steps as much as possible. + +**Example 1:** + +**Input:** nums = [2,5,6,0,0,1,2], target = 0 + +**Output:** true + +**Example 2:** + +**Input:** nums = [2,5,6,0,0,1,2], target = 3 + +**Output:** false + +**Constraints:** + +* `1 <= nums.length <= 5000` +* -104 <= nums[i] <= 104 +* `nums` is guaranteed to be rotated at some pivot. +* -104 <= target <= 104 + +**Follow up:** This problem is similar to [Search in Rotated Sorted Array](https://github.com/javadev/LeetCode-in-Java/tree/main/src/main/java/g0001_0100/s0033_search_in_rotated_sorted_array/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why? \ No newline at end of file diff --git a/src/Algorithms/0082.remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.php b/src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/Solution.php similarity index 96% rename from src/Algorithms/0082.remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.php rename to src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/Solution.php index 3986906..c6b5e69 100644 --- a/src/Algorithms/0082.remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.php +++ b/src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/Solution.php @@ -1,38 +1,38 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @return ListNode - */ - function deleteDuplicates($head) { - if($head == null || $head->next == null) return $head; - $dummy = new ListNode(-1); - $dummy->next = $head; - $prev=$dummy; - $slow=$dummy->next; - $fast=$slow->next; - while($slow != null && $fast != null) { - if($slow->val == $fast->val) { - while($fast != null && $slow->val == $fast->val) { - $fast = $fast->next; - } - $prev->next = $fast; - $slow = $prev->next; - $fast = $slow == null ? null : $slow->next; - } else { - $prev = $slow; - $slow = $slow->next; - $fast = $fast->next; - } - } - return $dummy->next; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @return ListNode + */ + function deleteDuplicates($head) { + if($head == null || $head->next == null) return $head; + $dummy = new ListNode(-1); + $dummy->next = $head; + $prev=$dummy; + $slow=$dummy->next; + $fast=$slow->next; + while($slow != null && $fast != null) { + if($slow->val == $fast->val) { + while($fast != null && $slow->val == $fast->val) { + $fast = $fast->next; + } + $prev->next = $fast; + $slow = $prev->next; + $fast = $slow == null ? null : $slow->next; + } else { + $prev = $slow; + $slow = $slow->next; + $fast = $fast->next; + } + } + return $dummy->next; + } +} diff --git a/src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/readme.md b/src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/readme.md new file mode 100644 index 0000000..ec77e80 --- /dev/null +++ b/src/Algorithms/s0082_remove_duplicates_from_sorted_list_ii/readme.md @@ -0,0 +1,27 @@ +82\. Remove Duplicates from Sorted List II + +Medium + +Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg) + +**Input:** head = [1,2,3,3,4,4,5] + +**Output:** [1,2,5] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg) + +**Input:** head = [1,1,1,2,3] + +**Output:** [2,3] + +**Constraints:** + +* The number of nodes in the list is in the range `[0, 300]`. +* `-100 <= Node.val <= 100` +* The list is guaranteed to be **sorted** in ascending order. \ No newline at end of file diff --git a/src/Algorithms/0083.remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.php b/src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php similarity index 95% rename from src/Algorithms/0083.remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.php rename to src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php index de92283..ebdf938 100644 --- a/src/Algorithms/0083.remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.php +++ b/src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php @@ -1,30 +1,30 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @return ListNode - */ - function deleteDuplicates($head) { - if($head==null || $head->next == null) return $head; - $prev = $head; - $node = $head->next; - while( $node!= null){ - if($node->val != $prev->val){ - $prev = $node; - $node = $node->next; - }else{ - $prev->next = $node->next; - $node = $node->next; - } - } - return $head; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @return ListNode + */ + function deleteDuplicates($head) { + if($head==null || $head->next == null) return $head; + $prev = $head; + $node = $head->next; + while( $node!= null){ + if($node->val != $prev->val){ + $prev = $node; + $node = $node->next; + }else{ + $prev->next = $node->next; + $node = $node->next; + } + } + return $head; + } +} diff --git a/src/Algorithms/s0083_remove_duplicates_from_sorted_list/readme.md b/src/Algorithms/s0083_remove_duplicates_from_sorted_list/readme.md new file mode 100644 index 0000000..fc80422 --- /dev/null +++ b/src/Algorithms/s0083_remove_duplicates_from_sorted_list/readme.md @@ -0,0 +1,27 @@ +83\. Remove Duplicates from Sorted List + +Easy + +Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/04/list1.jpg) + +**Input:** head = [1,1,2] + +**Output:** [1,2] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/04/list2.jpg) + +**Input:** head = [1,1,2,3,3] + +**Output:** [1,2,3] + +**Constraints:** + +* The number of nodes in the list is in the range `[0, 300]`. +* `-100 <= Node.val <= 100` +* The list is guaranteed to be **sorted** in ascending order. \ No newline at end of file diff --git a/src/Algorithms/0084.largest-rectangle-in-histogram/largest-rectangle-in-histogram.php b/src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php similarity index 97% rename from src/Algorithms/0084.largest-rectangle-in-histogram/largest-rectangle-in-histogram.php rename to src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php index 43ede3b..b2d206a 100644 --- a/src/Algorithms/0084.largest-rectangle-in-histogram/largest-rectangle-in-histogram.php +++ b/src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php @@ -1,15 +1,15 @@ -class Solution { - - /** - * @param Integer[] $heights - * @return Integer - */ - function largestRectangleArea($heights) { - $max = 0; $i = 0; - $stack = []; - while($i < count($heights) || count($stack) != 0) - if($i < count($heights) && (count($stack) == 0 || $heights[$i] >= $heights[end($stack)])) array_push($stack, $i++); - else $max = max($max, $heights[array_pop($stack)] * (count($stack) == 0 ? $i : $i - end($stack) - 1)); - return $max; - } -} +class Solution { + + /** + * @param Integer[] $heights + * @return Integer + */ + function largestRectangleArea($heights) { + $max = 0; $i = 0; + $stack = []; + while($i < count($heights) || count($stack) != 0) + if($i < count($heights) && (count($stack) == 0 || $heights[$i] >= $heights[end($stack)])) array_push($stack, $i++); + else $max = max($max, $heights[array_pop($stack)] * (count($stack) == 0 ? $i : $i - end($stack) - 1)); + return $max; + } +} diff --git a/src/Algorithms/s0084_largest_rectangle_in_histogram/readme.md b/src/Algorithms/s0084_largest_rectangle_in_histogram/readme.md new file mode 100644 index 0000000..96ca2d0 --- /dev/null +++ b/src/Algorithms/s0084_largest_rectangle_in_histogram/readme.md @@ -0,0 +1,28 @@ +84\. Largest Rectangle in Histogram + +Hard + +Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg) + +**Input:** heights = [2,1,5,6,2,3] + +**Output:** 10 + +**Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg) + +**Input:** heights = [2,4] + +**Output:** 4 + +**Constraints:** + +* 1 <= heights.length <= 105 +* 0 <= heights[i] <= 104 \ No newline at end of file diff --git a/src/Algorithms/0085.maximal-rectangle/maximal-rectangle.php b/src/Algorithms/s0085_maximal_rectangle/Solution.php similarity index 96% rename from src/Algorithms/0085.maximal-rectangle/maximal-rectangle.php rename to src/Algorithms/s0085_maximal_rectangle/Solution.php index 6f9c15a..d92b403 100644 --- a/src/Algorithms/0085.maximal-rectangle/maximal-rectangle.php +++ b/src/Algorithms/s0085_maximal_rectangle/Solution.php @@ -1,51 +1,51 @@ -class Solution { - - /** - * @param String[][] $matrix - * @return Integer - */ - function maximalRectangle($matrix) { - $maxSize = 0; - for ($i = 0; $i < count($matrix); $i++) { - for ($j = 0; $j < count($matrix[0]); $j++) { - if ($matrix[$i][$j] == '1') { - $maxSize = max(self::rectangleSize($matrix, $i, $j), $maxSize); - } - } - } - - return $maxSize; - } - - function rectangleSize(&$matrix, $row, $col) { - $maxSize; $rowSize; $size; - $i = $row + 1; $j = $col + 1; - $maxSize = $rowSize = $size = 1; - - while ($i < count($matrix) && $matrix[$i++][$col] == '1') { - $rowSize++; - } - - $maxSize = $size = $rowSize; - - while ($j < count($matrix[0])) { - if ($matrix[$row][$j] == '0' ) { - break; - } - - for ($k = $row; $k < $row + $rowSize; $k++) { - if ($matrix[$k][$j] == '0') { //if a '0' is found, reshape the rectangle - $oldrowSize = $rowSize; - $rowSize = $k - $row; - $size -= ($j - $col) * ($oldrowSize - $rowSize); - } - } - - $size += $rowSize; - $maxSize = max($maxSize, $size); - $j++; - } - - return $maxSize; - } -} +class Solution { + + /** + * @param String[][] $matrix + * @return Integer + */ + function maximalRectangle($matrix) { + $maxSize = 0; + for ($i = 0; $i < count($matrix); $i++) { + for ($j = 0; $j < count($matrix[0]); $j++) { + if ($matrix[$i][$j] == '1') { + $maxSize = max(self::rectangleSize($matrix, $i, $j), $maxSize); + } + } + } + + return $maxSize; + } + + function rectangleSize(&$matrix, $row, $col) { + $maxSize; $rowSize; $size; + $i = $row + 1; $j = $col + 1; + $maxSize = $rowSize = $size = 1; + + while ($i < count($matrix) && $matrix[$i++][$col] == '1') { + $rowSize++; + } + + $maxSize = $size = $rowSize; + + while ($j < count($matrix[0])) { + if ($matrix[$row][$j] == '0' ) { + break; + } + + for ($k = $row; $k < $row + $rowSize; $k++) { + if ($matrix[$k][$j] == '0') { //if a '0' is found, reshape the rectangle + $oldrowSize = $rowSize; + $rowSize = $k - $row; + $size -= ($j - $col) * ($oldrowSize - $rowSize); + } + } + + $size += $rowSize; + $maxSize = max($maxSize, $size); + $j++; + } + + return $maxSize; + } +} diff --git a/src/Algorithms/s0085_maximal_rectangle/readme.md b/src/Algorithms/s0085_maximal_rectangle/readme.md new file mode 100644 index 0000000..5dd4dde --- /dev/null +++ b/src/Algorithms/s0085_maximal_rectangle/readme.md @@ -0,0 +1,46 @@ +85\. Maximal Rectangle + +Hard + +Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg) + +**Input:** matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] + +**Output:** 6 + +**Explanation:** The maximal rectangle is shown in the above picture. + +**Example 2:** + +**Input:** matrix = [] + +**Output:** 0 + +**Example 3:** + +**Input:** matrix = [["0"]] + +**Output:** 0 + +**Example 4:** + +**Input:** matrix = [["1"]] + +**Output:** 1 + +**Example 5:** + +**Input:** matrix = [["0","0"]] + +**Output:** 0 + +**Constraints:** + +* `rows == matrix.length` +* `cols == matrix[i].length` +* `0 <= row, cols <= 200` +* `matrix[i][j]` is `'0'` or `'1'`. \ No newline at end of file diff --git a/src/Algorithms/0086.partition-list/partition-list.php b/src/Algorithms/s0086_partition_list/Solution.php similarity index 96% rename from src/Algorithms/0086.partition-list/partition-list.php rename to src/Algorithms/s0086_partition_list/Solution.php index ebd3b2e..16268fc 100644 --- a/src/Algorithms/0086.partition-list/partition-list.php +++ b/src/Algorithms/s0086_partition_list/Solution.php @@ -1,45 +1,45 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @param Integer $x - * @return ListNode - */ - function partition($head, $x) { - if($head == null || $head->next == null) return $head; - //split the answer into two part and then combine them, use prevPart and restPart as dummy heads; - $prevPart = new ListNode(-1); - $restPart = new ListNode(-1); - $prev = $prevPart; - $rest = $restPart; - while($head != null){ - if($head->val < $x){ - $prev->next = new ListNode($head->val); - $prev = $prev->next; - }else{ - $rest->next = new ListNode($head->val); - $rest = $rest->next; - } - $head = $head->next; - } - $tail = self::getTail($prevPart); - //put `>= val` numbers at tail of `< val` numbers - $tail->next = $restPart->next; - return $prevPart->next; - } - - function getTail($head){ - while($head->next != null){ - $head = $head->next; - } - return $head; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @param Integer $x + * @return ListNode + */ + function partition($head, $x) { + if($head == null || $head->next == null) return $head; + //split the answer into two part and then combine them, use prevPart and restPart as dummy heads; + $prevPart = new ListNode(-1); + $restPart = new ListNode(-1); + $prev = $prevPart; + $rest = $restPart; + while($head != null){ + if($head->val < $x){ + $prev->next = new ListNode($head->val); + $prev = $prev->next; + }else{ + $rest->next = new ListNode($head->val); + $rest = $rest->next; + } + $head = $head->next; + } + $tail = self::getTail($prevPart); + //put `>= val` numbers at tail of `< val` numbers + $tail->next = $restPart->next; + return $prevPart->next; + } + + function getTail($head){ + while($head->next != null){ + $head = $head->next; + } + return $head; + } +} diff --git a/src/Algorithms/s0086_partition_list/readme.md b/src/Algorithms/s0086_partition_list/readme.md new file mode 100644 index 0000000..eafe899 --- /dev/null +++ b/src/Algorithms/s0086_partition_list/readme.md @@ -0,0 +1,27 @@ +86\. Partition List + +Medium + +Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. + +You should **preserve** the original relative order of the nodes in each of the two partitions. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/04/partition.jpg) + +**Input:** head = [1,4,3,2,5,2], x = 3 + +**Output:** [1,2,2,4,3,5] + +**Example 2:** + +**Input:** head = [2,1], x = 2 + +**Output:** [1,2] + +**Constraints:** + +* The number of nodes in the list is in the range `[0, 200]`. +* `-100 <= Node.val <= 100` +* `-200 <= x <= 200` \ No newline at end of file diff --git a/src/Algorithms/0087.scramble-string/scramble-string.php b/src/Algorithms/s0087_scramble_string/Solution.php similarity index 97% rename from src/Algorithms/0087.scramble-string/scramble-string.php rename to src/Algorithms/s0087_scramble_string/Solution.php index 8782342..2ff3134 100644 --- a/src/Algorithms/0087.scramble-string/scramble-string.php +++ b/src/Algorithms/s0087_scramble_string/Solution.php @@ -1,36 +1,36 @@ -class Solution { - - /** - * @param String $s1 - * @param String $s2 - * @return Boolean - */ - function isScramble($s1, $s2) { - if ($s1 == null && $s2 == null) return true; - if (strlen($s1) != strlen($s2)) return false; - return self::helper($s1, $s2, 0, 0, strlen($s1)); - } - - function helper($cs1, $cs2, $s1, $s2, $len) { - if ($len == 0) return true; - $same = true; - for ($i = 0; $i < $len; $i++) { - if ($cs1[$s1 + $i] != $cs2[$s2 + $i]) { - $same = false; - break; - } - } - if ($same) return true; - $letters = array_fill(0, 26, 0); - for ($i = 0; $i < $len; $i++) { - $letters[ord($cs1[$s1 + $i]) - ord('a')]++; - $letters[ord($cs2[$s2 + $i]) - ord('a')]--; - } - foreach ($letters as $cnt) if ($cnt != 0) return false; - for ($i = 1; $i < $len; $i++) { - if (self::helper($cs1, $cs2, $s1, $s2, $i) && self::helper($cs1, $cs2, $s1 + $i, $s2 + $i, $len - $i)) return true; - if (self::helper($cs1, $cs2, $s1, $s2 + $len - $i, $i) && self::helper($cs1, $cs2, $s1 + $i, $s2, $len - $i)) return true; - } - return false; - } -} +class Solution { + + /** + * @param String $s1 + * @param String $s2 + * @return Boolean + */ + function isScramble($s1, $s2) { + if ($s1 == null && $s2 == null) return true; + if (strlen($s1) != strlen($s2)) return false; + return self::helper($s1, $s2, 0, 0, strlen($s1)); + } + + function helper($cs1, $cs2, $s1, $s2, $len) { + if ($len == 0) return true; + $same = true; + for ($i = 0; $i < $len; $i++) { + if ($cs1[$s1 + $i] != $cs2[$s2 + $i]) { + $same = false; + break; + } + } + if ($same) return true; + $letters = array_fill(0, 26, 0); + for ($i = 0; $i < $len; $i++) { + $letters[ord($cs1[$s1 + $i]) - ord('a')]++; + $letters[ord($cs2[$s2 + $i]) - ord('a')]--; + } + foreach ($letters as $cnt) if ($cnt != 0) return false; + for ($i = 1; $i < $len; $i++) { + if (self::helper($cs1, $cs2, $s1, $s2, $i) && self::helper($cs1, $cs2, $s1 + $i, $s2 + $i, $len - $i)) return true; + if (self::helper($cs1, $cs2, $s1, $s2 + $len - $i, $i) && self::helper($cs1, $cs2, $s1 + $i, $s2, $len - $i)) return true; + } + return false; + } +} diff --git a/src/Algorithms/s0087_scramble_string/readme.md b/src/Algorithms/s0087_scramble_string/readme.md new file mode 100644 index 0000000..82d8b8a --- /dev/null +++ b/src/Algorithms/s0087_scramble_string/readme.md @@ -0,0 +1,39 @@ +87\. Scramble String + +Hard + +We can scramble a string s to get a string t using the following algorithm: + +1. If the length of the string is 1, stop. +2. If the length of the string is > 1, do the following: + * Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`. + * **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`. + * Apply step 1 recursively on each of the two substrings `x` and `y`. + +Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`. + +**Example 1:** + +**Input:** s1 = "great", s2 = "rgeat" + +**Output:** true + +**Explanation:** One possible scenario applied on s1 is: "great" --> "gr/eat" // divide at random index. "gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order. "gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at ranom index each of them. "g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t". "r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order. The algorithm stops now and the result string is "rgeat" which is s2. As there is one possible scenario that led s1 to be scrambled to s2, we return true. + +**Example 2:** + +**Input:** s1 = "abcde", s2 = "caebd" + +**Output:** false + +**Example 3:** + +**Input:** s1 = "a", s2 = "a" + +**Output:** true + +**Constraints:** + +* `s1.length == s2.length` +* `1 <= s1.length <= 30` +* `s1` and `s2` consist of lower-case English letters. \ No newline at end of file diff --git a/src/Algorithms/0088.merge-sorted-array/merge-sorted-array.php b/src/Algorithms/s0088_merge_sorted_array/Solution.php similarity index 96% rename from src/Algorithms/0088.merge-sorted-array/merge-sorted-array.php rename to src/Algorithms/s0088_merge_sorted_array/Solution.php index 4f9c3cf..f04f5f1 100644 --- a/src/Algorithms/0088.merge-sorted-array/merge-sorted-array.php +++ b/src/Algorithms/s0088_merge_sorted_array/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param Integer[] $nums1 - * @param Integer $m - * @param Integer[] $nums2 - * @param Integer $n - * @return NULL - */ - function merge(&$nums1, $m, $nums2, $n) { - $i = $m-1; $j = $n-1; $x = count($nums1); - for($c = count($nums1) - 1; $c >= 0; $c--) { - if ($i>=0 && $j>=0 && $nums1[$i] >= $nums2[$j]) { - $nums1[$c] = $nums1[$i]; - --$i; - } else if ($i>=0 && $j>=0 && $nums2[$j] > $nums1[$i]) { - $nums1[$c] = $nums2[$j]; - --$j; - } else if($i<0 && $j>=0) { - $nums1[$c] = $nums2[$j]; - --$j; - } else { - $nums1[$c] = $nums1[$i]; - --$i; - } - } - } -} +class Solution { + + /** + * @param Integer[] $nums1 + * @param Integer $m + * @param Integer[] $nums2 + * @param Integer $n + * @return NULL + */ + function merge(&$nums1, $m, $nums2, $n) { + $i = $m-1; $j = $n-1; $x = count($nums1); + for($c = count($nums1) - 1; $c >= 0; $c--) { + if ($i>=0 && $j>=0 && $nums1[$i] >= $nums2[$j]) { + $nums1[$c] = $nums1[$i]; + --$i; + } else if ($i>=0 && $j>=0 && $nums2[$j] > $nums1[$i]) { + $nums1[$c] = $nums2[$j]; + --$j; + } else if($i<0 && $j>=0) { + $nums1[$c] = $nums2[$j]; + --$j; + } else { + $nums1[$c] = $nums1[$i]; + --$i; + } + } + } +} diff --git a/src/Algorithms/s0088_merge_sorted_array/readme.md b/src/Algorithms/s0088_merge_sorted_array/readme.md new file mode 100644 index 0000000..c75ddb8 --- /dev/null +++ b/src/Algorithms/s0088_merge_sorted_array/readme.md @@ -0,0 +1,43 @@ +88\. Merge Sorted Array + +Easy + +You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively. + +**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**. + +The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. + +**Example 1:** + +**Input:** nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 + +**Output:** [1,2,2,3,5,6] + +**Explanation:** The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. + +**Example 2:** + +**Input:** nums1 = [1], m = 1, nums2 = [], n = 0 + +**Output:** [1] + +**Explanation:** The arrays we are merging are [1] and []. The result of the merge is [1]. + +**Example 3:** + +**Input:** nums1 = [0], m = 0, nums2 = [1], n = 1 + +**Output:** [1] + +**Explanation:** The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. + +**Constraints:** + +* `nums1.length == m + n` +* `nums2.length == n` +* `0 <= m, n <= 200` +* `1 <= m + n <= 200` +* -109 <= nums1[i], nums2[j] <= 109 + +**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time? \ No newline at end of file diff --git a/src/Algorithms/0089.gray-code/gray-code.php b/src/Algorithms/s0089_gray_code/Solution.php similarity index 95% rename from src/Algorithms/0089.gray-code/gray-code.php rename to src/Algorithms/s0089_gray_code/Solution.php index 60d58e7..2ec94b9 100644 --- a/src/Algorithms/0089.gray-code/gray-code.php +++ b/src/Algorithms/s0089_gray_code/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param Integer $n - * @return Integer[] - */ - function grayCode($n) { - $ans = []; - self::subGray($n, $ans); - return $ans; - } - - function subGray($n, &$ans) { - if ($n == 0) { - array_push($ans, 0); - } else { - // left half - self::subGray($n - 1, $ans); - // double - $offset = count($ans); - for ($i = $offset - 1; $i >= 0; $i--) { - array_push($ans, $ans[$i] + $offset); - } - } - } -} +class Solution { + + /** + * @param Integer $n + * @return Integer[] + */ + function grayCode($n) { + $ans = []; + self::subGray($n, $ans); + return $ans; + } + + function subGray($n, &$ans) { + if ($n == 0) { + array_push($ans, 0); + } else { + // left half + self::subGray($n - 1, $ans); + // double + $offset = count($ans); + for ($i = $offset - 1; $i >= 0; $i--) { + array_push($ans, $ans[$i] + $offset); + } + } + } +} diff --git a/src/Algorithms/s0089_gray_code/readme.md b/src/Algorithms/s0089_gray_code/readme.md new file mode 100644 index 0000000..dd36b15 --- /dev/null +++ b/src/Algorithms/s0089_gray_code/readme.md @@ -0,0 +1,31 @@ +89\. Gray Code + +Medium + +An **n-bit gray code sequence** is a sequence of 2n integers where: + +* Every integer is in the **inclusive** range [0, 2n - 1], +* The first integer is `0`, +* An integer appears **no more than once** in the sequence, +* The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and +* The binary representation of the **first** and **last** integers differs by **exactly one bit**. + +Given an integer `n`, return _any valid **n-bit gray code sequence**_. + +**Example 1:** + +**Input:** n = 2 + +**Output:** [0,1,3,2] + +**Explanation:** The binary representation of [0,1,3,2] is [00,01,11,10]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit + +**Example 2:** + +**Input:** n = 1 + +**Output:** [0,1] + +**Constraints:** + +* `1 <= n <= 16` \ No newline at end of file diff --git a/src/Algorithms/0090.subsets-ii/subsets-ii.php b/src/Algorithms/s0090_subsets_ii/Solution.php similarity index 96% rename from src/Algorithms/0090.subsets-ii/subsets-ii.php rename to src/Algorithms/s0090_subsets_ii/Solution.php index 2af978d..c8c9abb 100644 --- a/src/Algorithms/0090.subsets-ii/subsets-ii.php +++ b/src/Algorithms/s0090_subsets_ii/Solution.php @@ -1,31 +1,31 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer[][] - */ - function subsetsWithDup($nums) { - $result = []; - if($nums == null || count($nums) == 0) return $result; - sort($nums); - array_push($result, []); - self::dfs($nums, [], $result, 0); - return $result; - } - - function dfs($nums, $list, &$result, $index) { - - if($index == count($nums)) { - return; - } - for($i=$index; $i $index && $nums[$i-1] == $nums[$i]) { - continue; - } - array_push($list, $nums[$i]); - array_push($result, $list); - self::dfs($nums, $list, $result, $i+1); - array_pop($list); - } - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer[][] + */ + function subsetsWithDup($nums) { + $result = []; + if($nums == null || count($nums) == 0) return $result; + sort($nums); + array_push($result, []); + self::dfs($nums, [], $result, 0); + return $result; + } + + function dfs($nums, $list, &$result, $index) { + + if($index == count($nums)) { + return; + } + for($i=$index; $i $index && $nums[$i-1] == $nums[$i]) { + continue; + } + array_push($list, $nums[$i]); + array_push($result, $list); + self::dfs($nums, $list, $result, $i+1); + array_pop($list); + } + } +} diff --git a/src/Algorithms/s0090_subsets_ii/readme.md b/src/Algorithms/s0090_subsets_ii/readme.md new file mode 100644 index 0000000..2b1e553 --- /dev/null +++ b/src/Algorithms/s0090_subsets_ii/readme.md @@ -0,0 +1,24 @@ +90\. Subsets II + +Medium + +Given an integer array `nums` that may contain duplicates, return _all possible subsets (the power set)_. + +The solution set **must not** contain duplicate subsets. Return the solution in **any order**. + +**Example 1:** + +**Input:** nums = [1,2,2] + +**Output:** [[],[1],[1,2],[1,2,2],[2],[2,2]] + +**Example 2:** + +**Input:** nums = [0] + +**Output:** [[],[0]] + +**Constraints:** + +* `1 <= nums.length <= 10` +* `-10 <= nums[i] <= 10` \ No newline at end of file diff --git a/src/Algorithms/0091.decode-ways/decode-ways.php b/src/Algorithms/s0091_decode_ways/Solution.php similarity index 94% rename from src/Algorithms/0091.decode-ways/decode-ways.php rename to src/Algorithms/s0091_decode_ways/Solution.php index f4fa9e0..a54fd4c 100644 --- a/src/Algorithms/0091.decode-ways/decode-ways.php +++ b/src/Algorithms/s0091_decode_ways/Solution.php @@ -1,30 +1,30 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function numDecodings($s) { - if(strlen($s) == 0) - return 0; - - $prev = 26; - $result = 0; - $first = 1; $second = 1; - - for($i = strlen($s) - 1; $i >= 0; $i--) - { - $digit = ord($s[$i]) - ord('0'); - - if($digit == 0) - $result = 0; - else - $result = $first + ($digit * 10 + $prev <= 26 ? $second : 0); - - $second = $first; - $first = $result; - $prev = $digit; - } - return $result; - } -} +class Solution { + + /** + * @param String $s + * @return Integer + */ + function numDecodings($s) { + if(strlen($s) == 0) + return 0; + + $prev = 26; + $result = 0; + $first = 1; $second = 1; + + for($i = strlen($s) - 1; $i >= 0; $i--) + { + $digit = ord($s[$i]) - ord('0'); + + if($digit == 0) + $result = 0; + else + $result = $first + ($digit * 10 + $prev <= 26 ? $second : 0); + + $second = $first; + $first = $result; + $prev = $digit; + } + return $result; + } +} diff --git a/src/Algorithms/s0091_decode_ways/readme.md b/src/Algorithms/s0091_decode_ways/readme.md new file mode 100644 index 0000000..2536da6 --- /dev/null +++ b/src/Algorithms/s0091_decode_ways/readme.md @@ -0,0 +1,55 @@ +91\. Decode Ways + +Medium + +A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: + +'A' -> "1" 'B' -> "2" ... 'Z' -> "26" + +To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106"` can be mapped into: + +* `"AAJF"` with the grouping `(1 1 10 6)` +* `"KJF"` with the grouping `(11 10 6)` + +Note that the grouping `(1 11 06)` is invalid because `"06"` cannot be mapped into `'F'` since `"6"` is different from `"06"`. + +Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. + +The answer is guaranteed to fit in a **32-bit** integer. + +**Example 1:** + +**Input:** s = "12" + +**Output:** 2 + +**Explanation:** "12" could be decoded as "AB" (1 2) or "L" (12). + +**Example 2:** + +**Input:** s = "226" + +**Output:** 3 + +**Explanation:** "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). + +**Example 3:** + +**Input:** s = "0" + +**Output:** 0 + +**Explanation:** There is no character that is mapped to a number starting with 0. The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0. Hence, there are no valid ways to decode this since all digits need to be mapped. + +**Example 4:** + +**Input:** s = "06" + +**Output:** 0 + +**Explanation:** "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). + +**Constraints:** + +* `1 <= s.length <= 100` +* `s` contains only digits and may contain leading zero(s). \ No newline at end of file diff --git a/src/Algorithms/0092.reverse-linked-list-ii/reverse-linked-list-ii.php b/src/Algorithms/s0092_reverse_linked_list_ii/Solution.php similarity index 96% rename from src/Algorithms/0092.reverse-linked-list-ii/reverse-linked-list-ii.php rename to src/Algorithms/s0092_reverse_linked_list_ii/Solution.php index 6621d2d..cf07893 100644 --- a/src/Algorithms/0092.reverse-linked-list-ii/reverse-linked-list-ii.php +++ b/src/Algorithms/s0092_reverse_linked_list_ii/Solution.php @@ -1,45 +1,45 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @param Integer $m - * @param Integer $n - * @return ListNode - */ - function reverseBetween($head, $m, $n) { - $dummy = new ListNode(-1); - $pre; $cur; - $connection; $tail; // tail points to the last node of the reversed sub-list - $pre = $dummy; - $dummy->next = $head; - - // this loop aims to find the connection node and the first node to be reversed. - for($i=0; $i<$m-1; $i++) { - $pre = $pre->next; - } - $connection = $pre; - $tail = $cur = $pre->next; - - $temp; - // this loop is just like the similar problem(https://leetcode.com/problems/reverse-linked-list/) - for($i=$m; $i<=$n; $i++) { - $temp = $cur->next; - $cur->next = $pre; - $pre = $cur; - $cur = $temp; - } - - // adjust the connection points - $tail->next = $cur; - $connection->next = $pre; - return $dummy->next; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @param Integer $m + * @param Integer $n + * @return ListNode + */ + function reverseBetween($head, $m, $n) { + $dummy = new ListNode(-1); + $pre; $cur; + $connection; $tail; // tail points to the last node of the reversed sub-list + $pre = $dummy; + $dummy->next = $head; + + // this loop aims to find the connection node and the first node to be reversed. + for($i=0; $i<$m-1; $i++) { + $pre = $pre->next; + } + $connection = $pre; + $tail = $cur = $pre->next; + + $temp; + // this loop is just like the similar problem(https://leetcode.com/problems/reverse-linked-list/) + for($i=$m; $i<=$n; $i++) { + $temp = $cur->next; + $cur->next = $pre; + $pre = $cur; + $cur = $temp; + } + + // adjust the connection points + $tail->next = $cur; + $connection->next = $pre; + return $dummy->next; + } +} diff --git a/src/Algorithms/s0092_reverse_linked_list_ii/readme.md b/src/Algorithms/s0092_reverse_linked_list_ii/readme.md new file mode 100644 index 0000000..f5575f0 --- /dev/null +++ b/src/Algorithms/s0092_reverse_linked_list_ii/readme.md @@ -0,0 +1,28 @@ +92\. Reverse Linked List II + +Medium + +Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg) + +**Input:** head = [1,2,3,4,5], left = 2, right = 4 + +**Output:** [1,4,3,2,5] + +**Example 2:** + +**Input:** head = [5], left = 1, right = 1 + +**Output:** [5] + +**Constraints:** + +* The number of nodes in the list is `n`. +* `1 <= n <= 500` +* `-500 <= Node.val <= 500` +* `1 <= left <= right <= n` + +**Follow up:** Could you do it in one pass? \ No newline at end of file diff --git a/src/Algorithms/0093.restore-ip-addresses/restore-ip-addresses.php b/src/Algorithms/s0093_restore_ip_addresses/Solution.php similarity index 96% rename from src/Algorithms/0093.restore-ip-addresses/restore-ip-addresses.php rename to src/Algorithms/s0093_restore_ip_addresses/Solution.php index e6c8505..6e47e1e 100644 --- a/src/Algorithms/0093.restore-ip-addresses/restore-ip-addresses.php +++ b/src/Algorithms/s0093_restore_ip_addresses/Solution.php @@ -1,53 +1,53 @@ -class Solution { - - var $s; - var $res; - var $parts; - - /** - * @param String $s - * @return String[] - */ - function restoreIpAddresses($s) { - $this->res = []; - $this->s = $s; - $this->parts = array_fill(0, 4, 0); - self::helper(-1, 0, 0); - return $this->res; - } - - function helper($num, $nextIdx, $partIdx) { - //base case, wraping up - if ($partIdx >= 4) { - return; - } - if ($nextIdx >= strlen($this->s)) { - if ($partIdx == 3 && $num != -1) { - $this->parts[$partIdx] = $num; - self::parseIp(); - } - return; - } - $nextDigit = ord($this->s[$nextIdx]) - ord('0'); - $possibleNum = $num == -1 ? $nextDigit : $num * 10 + $nextDigit; - if ($possibleNum <= 255 ) { - //trying increase this position next (if it's not 0) - if ($possibleNum > 0 || ($possibleNum == 0 && $nextIdx == strlen($this->s) - 1)) - self::helper($possibleNum, $nextIdx + 1, $partIdx); - //save for current position and try for next one from scratch - $this->parts[$partIdx] = $possibleNum; - self::helper(-1, $nextIdx + 1, $partIdx + 1); - $this->parts[$partIdx] = -1; - } - } - function parseIp() { - $sb = ""; - for ($i = 0; $i < count($this->parts); $i++) { - $sb .= $this->parts[$i]; - if ( $i < count($this->parts) - 1) - $sb .= '.'; - } - array_push($this->res, $sb); - } - +class Solution { + + var $s; + var $res; + var $parts; + + /** + * @param String $s + * @return String[] + */ + function restoreIpAddresses($s) { + $this->res = []; + $this->s = $s; + $this->parts = array_fill(0, 4, 0); + self::helper(-1, 0, 0); + return $this->res; + } + + function helper($num, $nextIdx, $partIdx) { + //base case, wraping up + if ($partIdx >= 4) { + return; + } + if ($nextIdx >= strlen($this->s)) { + if ($partIdx == 3 && $num != -1) { + $this->parts[$partIdx] = $num; + self::parseIp(); + } + return; + } + $nextDigit = ord($this->s[$nextIdx]) - ord('0'); + $possibleNum = $num == -1 ? $nextDigit : $num * 10 + $nextDigit; + if ($possibleNum <= 255 ) { + //trying increase this position next (if it's not 0) + if ($possibleNum > 0 || ($possibleNum == 0 && $nextIdx == strlen($this->s) - 1)) + self::helper($possibleNum, $nextIdx + 1, $partIdx); + //save for current position and try for next one from scratch + $this->parts[$partIdx] = $possibleNum; + self::helper(-1, $nextIdx + 1, $partIdx + 1); + $this->parts[$partIdx] = -1; + } + } + function parseIp() { + $sb = ""; + for ($i = 0; $i < count($this->parts); $i++) { + $sb .= $this->parts[$i]; + if ( $i < count($this->parts) - 1) + $sb .= '.'; + } + array_push($this->res, $sb); + } + } diff --git a/src/Algorithms/s0093_restore_ip_addresses/readme.md b/src/Algorithms/s0093_restore_ip_addresses/readme.md new file mode 100644 index 0000000..c2dc1d5 --- /dev/null +++ b/src/Algorithms/s0093_restore_ip_addresses/readme.md @@ -0,0 +1,44 @@ +93\. Restore IP Addresses + +Medium + +A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. + +* For example, `"0.1.2.201"` and `"192.168.1.1"` are **valid** IP addresses, but `"0.011.255.245"`, `"192.168.1.312"` and `"192.168@1.1"` are **invalid** IP addresses. + +Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. + +**Example 1:** + +**Input:** s = "25525511135" + +**Output:** ["255.255.11.135","255.255.111.35"] + +**Example 2:** + +**Input:** s = "0000" + +**Output:** ["0.0.0.0"] + +**Example 3:** + +**Input:** s = "1111" + +**Output:** ["1.1.1.1"] + +**Example 4:** + +**Input:** s = "010010" + +**Output:** ["0.10.0.10","0.100.1.0"] + +**Example 5:** + +**Input:** s = "101023" + +**Output:** ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"] + +**Constraints:** + +* `0 <= s.length <= 20` +* `s` consists of digits only. \ No newline at end of file diff --git a/src/Algorithms/0094.binary-tree-inorder-traversal/binary-tree-inorder-traversal.php b/src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php similarity index 95% rename from src/Algorithms/0094.binary-tree-inorder-traversal/binary-tree-inorder-traversal.php rename to src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php index a227595..fe0df35 100644 --- a/src/Algorithms/0094.binary-tree-inorder-traversal/binary-tree-inorder-traversal.php +++ b/src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php @@ -1,27 +1,27 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - var $elements = []; - - /** - * @param TreeNode $root - * @return Integer[] - */ - function inorderTraversal($root) { - if ($root == null) { - return $this->elements; - } - self::inorderTraversal($root->left); - array_push($this->elements, $root->val); - self::inorderTraversal($root->right); - return $this->elements; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + var $elements = []; + + /** + * @param TreeNode $root + * @return Integer[] + */ + function inorderTraversal($root) { + if ($root == null) { + return $this->elements; + } + self::inorderTraversal($root->left); + array_push($this->elements, $root->val); + self::inorderTraversal($root->right); + return $this->elements; + } +} diff --git a/src/Algorithms/s0094_binary_tree_inorder_traversal/readme.md b/src/Algorithms/s0094_binary_tree_inorder_traversal/readme.md new file mode 100644 index 0000000..5068d01 --- /dev/null +++ b/src/Algorithms/s0094_binary_tree_inorder_traversal/readme.md @@ -0,0 +1,48 @@ +94\. Binary Tree Inorder Traversal + +Easy + +Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg) + +**Input:** root = [1,null,2,3] + +**Output:** [1,3,2] + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Example 3:** + +**Input:** root = [1] + +**Output:** [1] + +**Example 4:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_5.jpg) + +**Input:** root = [1,2] + +**Output:** [2,1] + +**Example 5:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_4.jpg) + +**Input:** root = [1,null,2] + +**Output:** [1,2] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 100]`. +* `-100 <= Node.val <= 100` + +**Follow up:** Recursive solution is trivial, could you do it iteratively? \ No newline at end of file diff --git a/src/Algorithms/0095.unique-binary-search-trees-ii/unique-binary-search-trees-ii.php b/src/Algorithms/s0095_unique_binary_search_trees_ii/Solution.php similarity index 96% rename from src/Algorithms/0095.unique-binary-search-trees-ii/unique-binary-search-trees-ii.php rename to src/Algorithms/s0095_unique_binary_search_trees_ii/Solution.php index 87ae240..2d4fdc0 100644 --- a/src/Algorithms/0095.unique-binary-search-trees-ii/unique-binary-search-trees-ii.php +++ b/src/Algorithms/s0095_unique_binary_search_trees_ii/Solution.php @@ -1,52 +1,52 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param Integer $n - * @return TreeNode[] - */ - function generateTrees($n) { - if ($n == 0) { - return []; - } - $results = self::helper(1, $n); - return $results; - } - - function helper($begin, $end) { - $results = []; - if ($begin > $end) { - array_push($results, null); - return $results; - } - if ($begin == $end) { - array_push($results, new TreeNode($begin)); - return $results; - } - - for ($i = $begin; $i <= $end; $i++) { - $lstLeft = self::helper($begin, $i - 1); - $lstRight = self::helper($i + 1, $end); - - for ($j = 0; $j < count($lstLeft); $j++) { - $lNode = $lstLeft[$j]; - for ($k = 0; $k < count($lstRight); $k++) { - $rNode = $lstRight[$k]; - $root = new TreeNode($i); - $root->left = $lNode; - $root->right = $rNode; - array_push($results, $root); - } - } - } - return $results; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param Integer $n + * @return TreeNode[] + */ + function generateTrees($n) { + if ($n == 0) { + return []; + } + $results = self::helper(1, $n); + return $results; + } + + function helper($begin, $end) { + $results = []; + if ($begin > $end) { + array_push($results, null); + return $results; + } + if ($begin == $end) { + array_push($results, new TreeNode($begin)); + return $results; + } + + for ($i = $begin; $i <= $end; $i++) { + $lstLeft = self::helper($begin, $i - 1); + $lstRight = self::helper($i + 1, $end); + + for ($j = 0; $j < count($lstLeft); $j++) { + $lNode = $lstLeft[$j]; + for ($k = 0; $k < count($lstRight); $k++) { + $rNode = $lstRight[$k]; + $root = new TreeNode($i); + $root->left = $lNode; + $root->right = $rNode; + array_push($results, $root); + } + } + } + return $results; + } +} diff --git a/src/Algorithms/s0095_unique_binary_search_trees_ii/readme.md b/src/Algorithms/s0095_unique_binary_search_trees_ii/readme.md new file mode 100644 index 0000000..bab97bf --- /dev/null +++ b/src/Algorithms/s0095_unique_binary_search_trees_ii/readme.md @@ -0,0 +1,23 @@ +95\. Unique Binary Search Trees II + +Medium + +Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg) + +**Input:** n = 3 + +**Output:** [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] + +**Example 2:** + +**Input:** n = 1 + +**Output:** [[1]] + +**Constraints:** + +* `1 <= n <= 8` \ No newline at end of file diff --git a/src/Algorithms/0096.unique-binary-search-trees/unique-binary-search-trees.php b/src/Algorithms/s0096_unique_binary_search_trees/Solution.php similarity index 95% rename from src/Algorithms/0096.unique-binary-search-trees/unique-binary-search-trees.php rename to src/Algorithms/s0096_unique_binary_search_trees/Solution.php index bf100e5..be7d56b 100644 --- a/src/Algorithms/0096.unique-binary-search-trees/unique-binary-search-trees.php +++ b/src/Algorithms/s0096_unique_binary_search_trees/Solution.php @@ -1,19 +1,19 @@ -class Solution { - - /** - * @param Integer $n - * @return Integer - */ - function numTrees($n) { - $dp = array_fill(0, $n + 1, 0);; - $dp[0] = $dp[1] = 1; // null is also a BST; - - for($i = 2 ; $i <= $n; $i++){ - $dp[$i] = 0; - for($j = 0 ; $j < $i ; $j++){ - $dp[$i] += $dp[$j] * $dp[$i - $j - 1]; - } - } - return $dp[$n]; - } -} +class Solution { + + /** + * @param Integer $n + * @return Integer + */ + function numTrees($n) { + $dp = array_fill(0, $n + 1, 0);; + $dp[0] = $dp[1] = 1; // null is also a BST; + + for($i = 2 ; $i <= $n; $i++){ + $dp[$i] = 0; + for($j = 0 ; $j < $i ; $j++){ + $dp[$i] += $dp[$j] * $dp[$i - $j - 1]; + } + } + return $dp[$n]; + } +} diff --git a/src/Algorithms/s0096_unique_binary_search_trees/readme.md b/src/Algorithms/s0096_unique_binary_search_trees/readme.md new file mode 100644 index 0000000..de6a286 --- /dev/null +++ b/src/Algorithms/s0096_unique_binary_search_trees/readme.md @@ -0,0 +1,23 @@ +96\. Unique Binary Search Trees + +Medium + +Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg) + +**Input:** n = 3 + +**Output:** 5 + +**Example 2:** + +**Input:** n = 1 + +**Output:** 1 + +**Constraints:** + +* `1 <= n <= 19` \ No newline at end of file diff --git a/src/Algorithms/0097.interleaving-string/interleaving-string.php b/src/Algorithms/s0097_interleaving_string/Solution.php similarity index 96% rename from src/Algorithms/0097.interleaving-string/interleaving-string.php rename to src/Algorithms/s0097_interleaving_string/Solution.php index db1e2f0..4d0a077 100644 --- a/src/Algorithms/0097.interleaving-string/interleaving-string.php +++ b/src/Algorithms/s0097_interleaving_string/Solution.php @@ -1,31 +1,31 @@ -class Solution { - - /** - * @param String $s1 - * @param String $s2 - * @param String $s3 - * @return Boolean - */ - function isInterleave($s1, $s2, $s3) { - $l1 = strlen($s1); $l2 = strlen($s2); $l3 = strlen($s3); - if ($l1 + $l2 != $l3) return false; - $dp = array_fill(0, $l1 + 1, array_fill(0, $l2 + 1, false)); - $dp[0][0] = true; - for ($i = 1; $i <= $l1; $i++) { - if ($s1[$i - 1] == $s3[$i - 1]) $dp[$i][0] = true; - else break; - } - - for ($j = 1; $j <= $l2; $j++) { - if ($s2[$j - 1] == $s3[$j - 1]) $dp[0][$j] = true; - else break; - } - for ($i = 1; $i <= $l1; $i++) { - for ($j = 1; $j <= $l2; $j++) { - $dp[$i][$j] = ($dp[$i - 1][$j] && $s1[$i - 1] == $s3[$i + $j - 1]) - || ($dp[$i][$j - 1] && $s2[$j - 1] == $s3[$i + $j - 1]); - } - } - return $dp[$l1][$l2]; - } -} +class Solution { + + /** + * @param String $s1 + * @param String $s2 + * @param String $s3 + * @return Boolean + */ + function isInterleave($s1, $s2, $s3) { + $l1 = strlen($s1); $l2 = strlen($s2); $l3 = strlen($s3); + if ($l1 + $l2 != $l3) return false; + $dp = array_fill(0, $l1 + 1, array_fill(0, $l2 + 1, false)); + $dp[0][0] = true; + for ($i = 1; $i <= $l1; $i++) { + if ($s1[$i - 1] == $s3[$i - 1]) $dp[$i][0] = true; + else break; + } + + for ($j = 1; $j <= $l2; $j++) { + if ($s2[$j - 1] == $s3[$j - 1]) $dp[0][$j] = true; + else break; + } + for ($i = 1; $i <= $l1; $i++) { + for ($j = 1; $j <= $l2; $j++) { + $dp[$i][$j] = ($dp[$i - 1][$j] && $s1[$i - 1] == $s3[$i + $j - 1]) + || ($dp[$i][$j - 1] && $s2[$j - 1] == $s3[$i + $j - 1]); + } + } + return $dp[$l1][$l2]; + } +} diff --git a/src/Algorithms/s0097_interleaving_string/readme.md b/src/Algorithms/s0097_interleaving_string/readme.md new file mode 100644 index 0000000..613d1d5 --- /dev/null +++ b/src/Algorithms/s0097_interleaving_string/readme.md @@ -0,0 +1,42 @@ +97\. Interleaving String + +Medium + +Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`. + +An **interleaving** of two strings `s` and `t` is a configuration where they are divided into **non-empty** substrings such that: + +* s = s1 + s2 + ... + sn +* t = t1 + t2 + ... + tm +* `|n - m| <= 1` +* The **interleaving** is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... + +**Note:** `a + b` is the concatenation of strings `a` and `b`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg) + +**Input:** s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" + +**Output:** true + +**Example 2:** + +**Input:** s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" + +**Output:** false + +**Example 3:** + +**Input:** s1 = "", s2 = "", s3 = "" + +**Output:** true + +**Constraints:** + +* `0 <= s1.length, s2.length <= 100` +* `0 <= s3.length <= 200` +* `s1`, `s2`, and `s3` consist of lowercase English letters. + +**Follow up:** Could you solve it using only `O(s2.length)` additional memory space? \ No newline at end of file diff --git a/src/Algorithms/0098.validate-binary-search-tree/validate-binary-search-tree.php b/src/Algorithms/s0098_validate_binary_search_tree/Solution.php similarity index 96% rename from src/Algorithms/0098.validate-binary-search-tree/validate-binary-search-tree.php rename to src/Algorithms/s0098_validate_binary_search_tree/Solution.php index fcfe6ad..f1dac96 100644 --- a/src/Algorithms/0098.validate-binary-search-tree/validate-binary-search-tree.php +++ b/src/Algorithms/s0098_validate_binary_search_tree/Solution.php @@ -1,25 +1,25 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Boolean - */ - function isValidBST($root) { - return self::helper($root, null, null); - } - - function helper($node, $min, $max) { - if ($node == null) return true; - if (($min != null && $node->val <= $min->val) || ($max != null && $node->val >= $max->val)) return false; - return self::helper($node->left, $min, $node) && self::helper($node->right, $node, $max); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Boolean + */ + function isValidBST($root) { + return self::helper($root, null, null); + } + + function helper($node, $min, $max) { + if ($node == null) return true; + if (($min != null && $node->val <= $min->val) || ($max != null && $node->val >= $max->val)) return false; + return self::helper($node->left, $min, $node) && self::helper($node->right, $node, $max); + } +} diff --git a/src/Algorithms/s0098_validate_binary_search_tree/readme.md b/src/Algorithms/s0098_validate_binary_search_tree/readme.md new file mode 100644 index 0000000..a65734a --- /dev/null +++ b/src/Algorithms/s0098_validate_binary_search_tree/readme.md @@ -0,0 +1,34 @@ +98\. Validate Binary Search Tree + +Medium + +Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. + +A **valid BST** is defined as follows: + +* The left subtree of a node contains only nodes with keys **less than** the node's key. +* The right subtree of a node contains only nodes with keys **greater than** the node's key. +* Both the left and right subtrees must also be binary search trees. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg) + +**Input:** root = [2,1,3] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg) + +**Input:** root = [5,1,4,null,null,3,6] + +**Output:** false + +**Explanation:** The root node's value is 5 but its right child's value is 4. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 104]. +* -231 <= Node.val <= 231 - 1 \ No newline at end of file diff --git a/src/Algorithms/0099.recover-binary-search-tree/recover-binary-search-tree.php b/src/Algorithms/s0099_recover_binary_search_tree/Solution.php similarity index 96% rename from src/Algorithms/0099.recover-binary-search-tree/recover-binary-search-tree.php rename to src/Algorithms/s0099_recover_binary_search_tree/Solution.php index b0ec176..5ae502f 100644 --- a/src/Algorithms/0099.recover-binary-search-tree/recover-binary-search-tree.php +++ b/src/Algorithms/s0099_recover_binary_search_tree/Solution.php @@ -1,34 +1,34 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return NULL - */ - function recoverTree($root) { - $stack = []; - $current = $root; $prev = null; $first = null; $second = null; - while ($current != null || count($stack) != 0) { - while ($current != null) { - array_push($stack, $current); - $current = $current->left; - } - $current = array_pop($stack); - if ($prev != null && $current->val < $prev->val) { - if ($first == null) $first = $prev; - $second = $current; - } - $prev = $current; $current = $current->right; - } - // swap - $temp = $first->val; $first->val = $second->val; $second->val = $temp; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return NULL + */ + function recoverTree($root) { + $stack = []; + $current = $root; $prev = null; $first = null; $second = null; + while ($current != null || count($stack) != 0) { + while ($current != null) { + array_push($stack, $current); + $current = $current->left; + } + $current = array_pop($stack); + if ($prev != null && $current->val < $prev->val) { + if ($first == null) $first = $prev; + $second = $current; + } + $prev = $current; $current = $current->right; + } + // swap + $temp = $first->val; $first->val = $second->val; $second->val = $temp; + } +} diff --git a/src/Algorithms/s0099_recover_binary_search_tree/readme.md b/src/Algorithms/s0099_recover_binary_search_tree/readme.md new file mode 100644 index 0000000..2e02463 --- /dev/null +++ b/src/Algorithms/s0099_recover_binary_search_tree/readme.md @@ -0,0 +1,32 @@ +99\. Recover Binary Search Tree + +Medium + +You are given the `root` of a binary search tree (BST), where the values of **exactly** two nodes of the tree were swapped by mistake. _Recover the tree without changing its structure_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg) + +**Input:** root = [1,3,null,null,2] + +**Output:** [3,1,null,null,2] + +**Explanation:** 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg) + +**Input:** root = [3,1,4,null,null,2] + +**Output:** [2,1,4,null,null,3] + +**Explanation:** 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. + +**Constraints:** + +* The number of nodes in the tree is in the range `[2, 1000]`. +* -231 <= Node.val <= 231 - 1 + +**Follow up:** A solution using `O(n)` space is pretty straight-forward. Could you devise a constant `O(1)` space solution? \ No newline at end of file diff --git a/src/Algorithms/0100.same-tree/same-tree.php b/src/Algorithms/s0100_same_tree/Solution.php similarity index 96% rename from src/Algorithms/0100.same-tree/same-tree.php rename to src/Algorithms/s0100_same_tree/Solution.php index db6c9b0..f2ac9fb 100644 --- a/src/Algorithms/0100.same-tree/same-tree.php +++ b/src/Algorithms/s0100_same_tree/Solution.php @@ -1,26 +1,26 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $p - * @param TreeNode $q - * @return Boolean - */ - function isSameTree($p, $q) { - if($p == null && $q == null) - return true; - - if($p == null || $q == null) - return false; - - return ($p->val == $q->val) && self::isSameTree($p->left, $q->left) && self::isSameTree($p->right,$q->right); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $p + * @param TreeNode $q + * @return Boolean + */ + function isSameTree($p, $q) { + if($p == null && $q == null) + return true; + + if($p == null || $q == null) + return false; + + return ($p->val == $q->val) && self::isSameTree($p->left, $q->left) && self::isSameTree($p->right,$q->right); + } +} diff --git a/src/Algorithms/s0100_same_tree/readme.md b/src/Algorithms/s0100_same_tree/readme.md new file mode 100644 index 0000000..0172a56 --- /dev/null +++ b/src/Algorithms/s0100_same_tree/readme.md @@ -0,0 +1,36 @@ +100\. Same Tree + +Easy + +Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. + +Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg) + +**Input:** p = [1,2,3], q = [1,2,3] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg) + +**Input:** p = [1,2], q = [1,null,2] + +**Output:** false + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg) + +**Input:** p = [1,2,1], q = [1,1,2] + +**Output:** false + +**Constraints:** + +* The number of nodes in both trees is in the range `[0, 100]`. +* -104 <= Node.val <= 104 \ No newline at end of file diff --git a/src/Algorithms/0101.symmetric-tree/symmetric-tree.php b/src/Algorithms/s0101_symmetric_tree/Solution.php similarity index 96% rename from src/Algorithms/0101.symmetric-tree/symmetric-tree.php rename to src/Algorithms/s0101_symmetric_tree/Solution.php index 53a983f..590e147 100644 --- a/src/Algorithms/0101.symmetric-tree/symmetric-tree.php +++ b/src/Algorithms/s0101_symmetric_tree/Solution.php @@ -1,32 +1,32 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Boolean - */ - function isSymmetric($root) { - //1. Top empty, return symmetric! - if($root == null) return true; - - //2. Recursion method: Single null always symm, so just put kids in. - return self::helper($root->left, $root->right); - } - - function helper($left, $right){ - //3. Both must be null, or false - if($left==null || $right==null) - return $left==$right; - - //4. Check values and next level of children - return $left->val==$right->val && self::helper($left->left, $right->right) && self::helper($left->right, $right->left); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Boolean + */ + function isSymmetric($root) { + //1. Top empty, return symmetric! + if($root == null) return true; + + //2. Recursion method: Single null always symm, so just put kids in. + return self::helper($root->left, $root->right); + } + + function helper($left, $right){ + //3. Both must be null, or false + if($left==null || $right==null) + return $left==$right; + + //4. Check values and next level of children + return $left->val==$right->val && self::helper($left->left, $right->right) && self::helper($left->right, $right->left); + } +} diff --git a/src/Algorithms/s0101_symmetric_tree/readme.md b/src/Algorithms/s0101_symmetric_tree/readme.md new file mode 100644 index 0000000..bd97864 --- /dev/null +++ b/src/Algorithms/s0101_symmetric_tree/readme.md @@ -0,0 +1,28 @@ +101\. Symmetric Tree + +Easy + +Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg) + +**Input:** root = [1,2,2,3,4,4,3] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg) + +**Input:** root = [1,2,2,null,3,null,3] + +**Output:** false + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 1000]`. +* `-100 <= Node.val <= 100` + +**Follow up:** Could you solve it both recursively and iteratively? \ No newline at end of file diff --git a/src/Algorithms/0102.binary-tree-level-order-traversal/binary-tree-level-order-traversal.php b/src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php similarity index 96% rename from src/Algorithms/0102.binary-tree-level-order-traversal/binary-tree-level-order-traversal.php rename to src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php index c01abee..cf24342 100644 --- a/src/Algorithms/0102.binary-tree-level-order-traversal/binary-tree-level-order-traversal.php +++ b/src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php @@ -1,36 +1,36 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Integer[][] - */ - function levelOrder($root) { - $lists=[]; - self::levelOrderTraverse($root,0,$lists); - return $lists; - } - - function levelOrderTraverse($root,$depth,&$lists) { - if($root==null){ - return ; - } - if(count($lists)<=$depth){ - array_push($lists, []); - array_push($lists[$depth], $root->val); - }else{ - array_push($lists[$depth], $root->val); - } - - self::levelOrderTraverse($root->left,$depth+1,$lists); - self::levelOrderTraverse($root->right,$depth+1,$lists); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Integer[][] + */ + function levelOrder($root) { + $lists=[]; + self::levelOrderTraverse($root,0,$lists); + return $lists; + } + + function levelOrderTraverse($root,$depth,&$lists) { + if($root==null){ + return ; + } + if(count($lists)<=$depth){ + array_push($lists, []); + array_push($lists[$depth], $root->val); + }else{ + array_push($lists[$depth], $root->val); + } + + self::levelOrderTraverse($root->left,$depth+1,$lists); + self::levelOrderTraverse($root->right,$depth+1,$lists); + } +} diff --git a/src/Algorithms/s0102_binary_tree_level_order_traversal/readme.md b/src/Algorithms/s0102_binary_tree_level_order_traversal/readme.md new file mode 100644 index 0000000..92fe4a4 --- /dev/null +++ b/src/Algorithms/s0102_binary_tree_level_order_traversal/readme.md @@ -0,0 +1,30 @@ +102\. Binary Tree Level Order Traversal + +Medium + +Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** [[3],[9,20],[15,7]] + +**Example 2:** + +**Input:** root = [1] + +**Output:** [[1]] + +**Example 3:** + +**Input:** root = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 2000]`. +* `-1000 <= Node.val <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.php b/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php similarity index 96% rename from src/Algorithms/0103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.php rename to src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php index c74f997..9b227a4 100644 --- a/src/Algorithms/0103.binary-tree-zigzag-level-order-traversal/binary-tree-zigzag-level-order-traversal.php +++ b/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php @@ -1,40 +1,40 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Integer[][] - */ - function zigzagLevelOrder($root) { - $leftRight = true; - $result = []; - $queue = []; - if ($root != null) array_push($queue, $root); - while (count($queue) > 0){ - $size = count($queue); - $list = []; - for ($i = 0; $i < $size; $i++){ - $node = array_shift($queue); - if ($leftRight){ - array_push($list, $node->val); - } else { - array_splice($list, 0, 0, $node->val); - } - if ($node->left != null) array_push($queue, $node->left); - if ($node->right != null) array_push($queue, $node->right); - } - array_push($result, $list); - $leftRight = !$leftRight; - } - - return $result; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Integer[][] + */ + function zigzagLevelOrder($root) { + $leftRight = true; + $result = []; + $queue = []; + if ($root != null) array_push($queue, $root); + while (count($queue) > 0){ + $size = count($queue); + $list = []; + for ($i = 0; $i < $size; $i++){ + $node = array_shift($queue); + if ($leftRight){ + array_push($list, $node->val); + } else { + array_splice($list, 0, 0, $node->val); + } + if ($node->left != null) array_push($queue, $node->left); + if ($node->right != null) array_push($queue, $node->right); + } + array_push($result, $list); + $leftRight = !$leftRight; + } + + return $result; + } +} diff --git a/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/readme.md b/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/readme.md new file mode 100644 index 0000000..3442925 --- /dev/null +++ b/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/readme.md @@ -0,0 +1,30 @@ +103\. Binary Tree Zigzag Level Order Traversal + +Medium + +Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** [[3],[20,9],[15,7]] + +**Example 2:** + +**Input:** root = [1] + +**Output:** [[1]] + +**Example 3:** + +**Input:** root = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 2000]`. +* `-100 <= Node.val <= 100` \ No newline at end of file diff --git a/src/Algorithms/0104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.php b/src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php similarity index 95% rename from src/Algorithms/0104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.php rename to src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php index 5b667fc..d469cc1 100644 --- a/src/Algorithms/0104.maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.php +++ b/src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php @@ -1,20 +1,20 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Integer - */ - function maxDepth($root) { - if($root == null) return 0; - return 1 + max(self::maxDepth($root->left), self::maxDepth($root->right) ); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Integer + */ + function maxDepth($root) { + if($root == null) return 0; + return 1 + max(self::maxDepth($root->left), self::maxDepth($root->right) ); + } +} diff --git a/src/Algorithms/s0104_maximum_depth_of_binary_tree/readme.md b/src/Algorithms/s0104_maximum_depth_of_binary_tree/readme.md new file mode 100644 index 0000000..052ac01 --- /dev/null +++ b/src/Algorithms/s0104_maximum_depth_of_binary_tree/readme.md @@ -0,0 +1,38 @@ +104\. Maximum Depth of Binary Tree + +Easy + +Given the `root` of a binary tree, return _its maximum depth_. + +A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** 3 + +**Example 2:** + +**Input:** root = [1,null,2] + +**Output:** 2 + +**Example 3:** + +**Input:** root = [] + +**Output:** 0 + +**Example 4:** + +**Input:** root = [0] + +**Output:** 1 + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 104]. +* `-100 <= Node.val <= 100` \ No newline at end of file diff --git a/src/Algorithms/0105.construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.php b/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php similarity index 96% rename from src/Algorithms/0105.construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.php rename to src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php index 0f7ca35..93852ca 100644 --- a/src/Algorithms/0105.construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.php +++ b/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php @@ -1,34 +1,34 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param Integer[] $preorder - * @param Integer[] $inorder - * @return TreeNode - */ - function buildTree($preorder, $inorder) { - $map = []; - for ($i = 0; $i < count($inorder); $i++) { - $map[$inorder[$i]] = $i; - } - return self::helper($preorder, $inorder, $map, 0, 0, count($inorder) - 1); - } - function helper($preorder, $inorder, $map, $index, $start, $end) { - if ($index >= count($preorder) || $start > $end) { - return null; - } - $root = new TreeNode($preorder[$index]); - $k = $map[$root->val]; - $root->left = self::helper($preorder, $inorder, $map, $index + 1, $start, $k - 1); - $root->right = self::helper($preorder, $inorder, $map, $index + 1 + $k - $start, $k + 1, $end); - return $root; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param Integer[] $preorder + * @param Integer[] $inorder + * @return TreeNode + */ + function buildTree($preorder, $inorder) { + $map = []; + for ($i = 0; $i < count($inorder); $i++) { + $map[$inorder[$i]] = $i; + } + return self::helper($preorder, $inorder, $map, 0, 0, count($inorder) - 1); + } + function helper($preorder, $inorder, $map, $index, $start, $end) { + if ($index >= count($preorder) || $start > $end) { + return null; + } + $root = new TreeNode($preorder[$index]); + $k = $map[$root->val]; + $root->left = self::helper($preorder, $inorder, $map, $index + 1, $start, $k - 1); + $root->right = self::helper($preorder, $inorder, $map, $index + 1 + $k - $start, $k + 1, $end); + return $root; + } +} diff --git a/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md b/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md new file mode 100644 index 0000000..fa4a8b4 --- /dev/null +++ b/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/readme.md @@ -0,0 +1,29 @@ +105\. Construct Binary Tree from Preorder and Inorder Traversal + +Medium + +Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/tree.jpg) + +**Input:** preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] + +**Output:** [3,9,20,null,null,15,7] + +**Example 2:** + +**Input:** preorder = [-1], inorder = [-1] + +**Output:** [-1] + +**Constraints:** + +* `1 <= preorder.length <= 3000` +* `inorder.length == preorder.length` +* `-3000 <= preorder[i], inorder[i] <= 3000` +* `preorder` and `inorder` consist of **unique** values. +* Each value of `inorder` also appears in `preorder`. +* `preorder` is **guaranteed** to be the preorder traversal of the tree. +* `inorder` is **guaranteed** to be the inorder traversal of the tree. \ No newline at end of file diff --git a/src/Algorithms/0106.construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.php b/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php similarity index 97% rename from src/Algorithms/0106.construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.php rename to src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php index a400f8e..c09facc 100644 --- a/src/Algorithms/0106.construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.php +++ b/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php @@ -1,34 +1,34 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param Integer[] $inorder - * @param Integer[] $postorder - * @return TreeNode - */ - function buildTree($inorder, $postorder) { - if($inorder==null || count($inorder)==0 || $postorder==null || count($postorder)==0) return null; - return self::recursive($inorder, 0, count($inorder)-1, $postorder, count($postorder)-1); - } - - function recursive($inorder, $inStart, $inEnd, $postorder, $postEnd) { - if($inStart>$inEnd || $postEnd<0) return null; - $root=new TreeNode($postorder[$postEnd]); - /** - manually check the index of postorder[postEnd] in inorder arr - **/ - $index=0; - while($inorder[$index]!=$root->val) $index++; - $root->left=self::recursive($inorder, $inStart, $index-1, $postorder, $postEnd-1-($inEnd-$index)); - $root->right=self::recursive($inorder, $index+1, $inEnd, $postorder, $postEnd-1); - return $root; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param Integer[] $inorder + * @param Integer[] $postorder + * @return TreeNode + */ + function buildTree($inorder, $postorder) { + if($inorder==null || count($inorder)==0 || $postorder==null || count($postorder)==0) return null; + return self::recursive($inorder, 0, count($inorder)-1, $postorder, count($postorder)-1); + } + + function recursive($inorder, $inStart, $inEnd, $postorder, $postEnd) { + if($inStart>$inEnd || $postEnd<0) return null; + $root=new TreeNode($postorder[$postEnd]); + /** + manually check the index of postorder[postEnd] in inorder arr + **/ + $index=0; + while($inorder[$index]!=$root->val) $index++; + $root->left=self::recursive($inorder, $inStart, $index-1, $postorder, $postEnd-1-($inEnd-$index)); + $root->right=self::recursive($inorder, $index+1, $inEnd, $postorder, $postEnd-1); + return $root; + } +} diff --git a/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md b/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md new file mode 100644 index 0000000..d4b6877 --- /dev/null +++ b/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/readme.md @@ -0,0 +1,29 @@ +106\. Construct Binary Tree from Inorder and Postorder Traversal + +Medium + +Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/tree.jpg) + +**Input:** inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] + +**Output:** [3,9,20,null,null,15,7] + +**Example 2:** + +**Input:** inorder = [-1], postorder = [-1] + +**Output:** [-1] + +**Constraints:** + +* `1 <= inorder.length <= 3000` +* `postorder.length == inorder.length` +* `-3000 <= inorder[i], postorder[i] <= 3000` +* `inorder` and `postorder` consist of **unique** values. +* Each value of `postorder` also appears in `inorder`. +* `inorder` is **guaranteed** to be the inorder traversal of the tree. +* `postorder` is **guaranteed** to be the postorder traversal of the tree. \ No newline at end of file diff --git a/src/Algorithms/0107.binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.php b/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php similarity index 96% rename from src/Algorithms/0107.binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.php rename to src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php index 91c25ec..3d500b7 100644 --- a/src/Algorithms/0107.binary-tree-level-order-traversal-ii/binary-tree-level-order-traversal-ii.php +++ b/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php @@ -1,46 +1,46 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Integer[][] - */ - function levelOrderBottom($root) { - $result = []; - // Hit the end, return an empty list directly - if ($root == null) { - return $result; - } - - $self = []; - array_push($self, $root->val); - - $left = self::levelOrderBottom($root->left); - $right = self::levelOrderBottom($root->right); - - // Return directly on leaf will cause the depth of left/right tree are not the same - // need to merge the lists based on different index. - $startIdx = abs(count($left) - count($right)); - if (count($left) >= count($right)) { - for ($i = $startIdx, $j = 0; $j < count($right); $j++) { - array_push($left[$i + $j], ...$right[$j]); - } - array_push($left, $self); - return $left; - } else { - for ($i = $startIdx, $j = 0; $j < count($left); $j++) { - array_splice($right[$i + $j], 0, 0, $left[$j]); - } - array_push($right, $self); - return $right; - } - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Integer[][] + */ + function levelOrderBottom($root) { + $result = []; + // Hit the end, return an empty list directly + if ($root == null) { + return $result; + } + + $self = []; + array_push($self, $root->val); + + $left = self::levelOrderBottom($root->left); + $right = self::levelOrderBottom($root->right); + + // Return directly on leaf will cause the depth of left/right tree are not the same + // need to merge the lists based on different index. + $startIdx = abs(count($left) - count($right)); + if (count($left) >= count($right)) { + for ($i = $startIdx, $j = 0; $j < count($right); $j++) { + array_push($left[$i + $j], ...$right[$j]); + } + array_push($left, $self); + return $left; + } else { + for ($i = $startIdx, $j = 0; $j < count($left); $j++) { + array_splice($right[$i + $j], 0, 0, $left[$j]); + } + array_push($right, $self); + return $right; + } + } +} diff --git a/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/readme.md b/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/readme.md new file mode 100644 index 0000000..b23bc4b --- /dev/null +++ b/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/readme.md @@ -0,0 +1,30 @@ +107\. Binary Tree Level Order Traversal II + +Medium + +Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** [[15,7],[9,20],[3]] + +**Example 2:** + +**Input:** root = [1] + +**Output:** [[1]] + +**Example 3:** + +**Input:** root = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 2000]`. +* `-1000 <= Node.val <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.php b/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php similarity index 96% rename from src/Algorithms/0108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.php rename to src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php index 60e298f..8f46af3 100644 --- a/src/Algorithms/0108.convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.php +++ b/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php @@ -1,36 +1,36 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param Integer[] $nums - * @return TreeNode - */ - function sortedArrayToBST($num) { - /*1. Set up recursion*/ - return self::makeTree($num, 0, count($num)-1); - } - - function makeTree($num, $left, $right){ - /*2. left as lowest# can't be greater than right*/ - if($left>$right) return null; - - /*3. Set median# as node*/ - $mid = intval(($left+$right)/2); - $midNode = new TreeNode($num[$mid]); - - /*4. Set mid node's kids*/ - $midNode->left = self::makeTree($num, $left, $mid-1); - $midNode->right = self::makeTree($num, $mid+1, $right); - - /*5. Sends node back || Goes back to prev node*/ - return $midNode; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param Integer[] $nums + * @return TreeNode + */ + function sortedArrayToBST($num) { + /*1. Set up recursion*/ + return self::makeTree($num, 0, count($num)-1); + } + + function makeTree($num, $left, $right){ + /*2. left as lowest# can't be greater than right*/ + if($left>$right) return null; + + /*3. Set median# as node*/ + $mid = intval(($left+$right)/2); + $midNode = new TreeNode($num[$mid]); + + /*4. Set mid node's kids*/ + $midNode->left = self::makeTree($num, $left, $mid-1); + $midNode->right = self::makeTree($num, $mid+1, $right); + + /*5. Sends node back || Goes back to prev node*/ + return $midNode; + } +} diff --git a/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/readme.md b/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/readme.md new file mode 100644 index 0000000..c5c6a1e --- /dev/null +++ b/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/readme.md @@ -0,0 +1,33 @@ +108\. Convert Sorted Array to Binary Search Tree + +Easy + +Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a **height-balanced** binary search tree_. + +A **height-balanced** binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg) + +**Input:** nums = [-10,-3,0,5,9] + +**Output:** [0,-3,9,-10,null,5] + +**Explanation:** [0,-10,5,null,-3,null,9] is also accepted: ![](https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg) + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/18/btree.jpg) + +**Input:** nums = [1,3] + +**Output:** [3,1] + +**Explanation:** [1,3] and [3,1] are both a height-balanced BSTs. + +**Constraints:** + +* 1 <= nums.length <= 104 +* -104 <= nums[i] <= 104 +* `nums` is sorted in a **strictly increasing** order. \ No newline at end of file diff --git a/src/Algorithms/0109.convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.php b/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php similarity index 95% rename from src/Algorithms/0109.convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.php rename to src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php index e250ab9..310c855 100644 --- a/src/Algorithms/0109.convert-sorted-list-to-binary-search-tree/convert-sorted-list-to-binary-search-tree.php +++ b/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php @@ -1,50 +1,50 @@ -/** - * Definition for a singly-linked list. - * class ListNode { - * public $val = 0; - * public $next = null; - * function __construct($val) { $this->val = $val; } - * } - */ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param ListNode $head - * @return TreeNode - */ - function sortedListToBST($head) { - $lst = []; - while ($head != null) { - array_push($lst, $head->val); - $head = $head->next; - } - - return self::helper($lst, 0, count($lst) - 1); - } - - function helper($lst, $start, $end) { - if ($start > $end) { - return null; - } - if ($start == $end) { - return new TreeNode($lst[$start]); - } - - $mid = intval(($end + $start) / 2); - $root = new TreeNode($lst[$mid]); - - $root->left = self::helper($lst, $start, $mid - 1); - $root->right = self::helper($lst, $mid + 1, $end); - - return $root; - } -} +/** + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val) { $this->val = $val; } + * } + */ +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param ListNode $head + * @return TreeNode + */ + function sortedListToBST($head) { + $lst = []; + while ($head != null) { + array_push($lst, $head->val); + $head = $head->next; + } + + return self::helper($lst, 0, count($lst) - 1); + } + + function helper($lst, $start, $end) { + if ($start > $end) { + return null; + } + if ($start == $end) { + return new TreeNode($lst[$start]); + } + + $mid = intval(($end + $start) / 2); + $root = new TreeNode($lst[$mid]); + + $root->left = self::helper($lst, $start, $mid - 1); + $root->right = self::helper($lst, $mid + 1, $end); + + return $root; + } +} diff --git a/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/readme.md b/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/readme.md new file mode 100644 index 0000000..f75e516 --- /dev/null +++ b/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/readme.md @@ -0,0 +1,40 @@ +109\. Convert Sorted List to Binary Search Tree + +Medium + +Given the `head` of a singly linked list where elements are **sorted in ascending order**, convert it to a height balanced BST. + +For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of _every_ node never differ by more than 1. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/08/17/linked.jpg) + +**Input:** head = [-10,-3,0,5,9] + +**Output:** [0,-3,9,-10,null,5] + +**Explanation:** One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. + +**Example 2:** + +**Input:** head = [] + +**Output:** [] + +**Example 3:** + +**Input:** head = [0] + +**Output:** [0] + +**Example 4:** + +**Input:** head = [1,3] + +**Output:** [3,1] + +**Constraints:** + +* The number of nodes in `head` is in the range [0, 2 * 104]. +* -105 <= Node.val <= 105 \ No newline at end of file diff --git a/src/Algorithms/0110.balanced-binary-tree/balanced-binary-tree.php b/src/Algorithms/s0110_balanced_binary_tree/Solution.php similarity index 96% rename from src/Algorithms/0110.balanced-binary-tree/balanced-binary-tree.php rename to src/Algorithms/s0110_balanced_binary_tree/Solution.php index 316febd..3e8abb4 100644 --- a/src/Algorithms/0110.balanced-binary-tree/balanced-binary-tree.php +++ b/src/Algorithms/s0110_balanced_binary_tree/Solution.php @@ -1,30 +1,30 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Boolean - */ - function isBalanced($root) { - return $root == null || self::checkDepth($root) != -1; - } - - function checkDepth($root) { - $lh = $root->left == null ? 0 : self::checkDepth($root->left); - $rh = $root->right == null ? 0 : self::checkDepth($root->right); - // Left subtree or right subtree is unbalanced - if ($lh == -1 || $rh == -1) return -1; - // This tree is unbalanced - if ($lh - $rh > 1 || $lh - $rh < -1) return -1; - // Return depth of this tree - return max($lh, $rh) + 1; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Boolean + */ + function isBalanced($root) { + return $root == null || self::checkDepth($root) != -1; + } + + function checkDepth($root) { + $lh = $root->left == null ? 0 : self::checkDepth($root->left); + $rh = $root->right == null ? 0 : self::checkDepth($root->right); + // Left subtree or right subtree is unbalanced + if ($lh == -1 || $rh == -1) return -1; + // This tree is unbalanced + if ($lh - $rh > 1 || $lh - $rh < -1) return -1; + // Return depth of this tree + return max($lh, $rh) + 1; + } +} diff --git a/src/Algorithms/s0110_balanced_binary_tree/readme.md b/src/Algorithms/s0110_balanced_binary_tree/readme.md new file mode 100644 index 0000000..10905d0 --- /dev/null +++ b/src/Algorithms/s0110_balanced_binary_tree/readme.md @@ -0,0 +1,36 @@ +110\. Balanced Binary Tree + +Easy + +Given a binary tree, determine if it is height-balanced. + +For this problem, a height-balanced binary tree is defined as: + +> a binary tree in which the left and right subtrees of _every_ node differ in height by no more than 1. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg) + +**Input:** root = [1,2,2,3,3,null,null,4,4] + +**Output:** false + +**Example 3:** + +**Input:** root = [] + +**Output:** true + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 5000]`. +* -104 <= Node.val <= 104 \ No newline at end of file diff --git a/src/Algorithms/0111.minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.php b/src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php similarity index 96% rename from src/Algorithms/0111.minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.php rename to src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php index 1ccb5d9..ca4d56b 100644 --- a/src/Algorithms/0111.minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.php +++ b/src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php @@ -1,26 +1,26 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return Integer - */ - function minDepth($root) { - if($root == null) - return 0; - else if($root->left == null) - return self::minDepth($root->right) + 1; - else if($root->right == null) - return self::minDepth($root->left) + 1; - else - return min(self::minDepth($root->left) + 1, self::minDepth($root->right) + 1); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return Integer + */ + function minDepth($root) { + if($root == null) + return 0; + else if($root->left == null) + return self::minDepth($root->right) + 1; + else if($root->right == null) + return self::minDepth($root->left) + 1; + else + return min(self::minDepth($root->left) + 1, self::minDepth($root->right) + 1); + } +} diff --git a/src/Algorithms/s0111_minimum_depth_of_binary_tree/readme.md b/src/Algorithms/s0111_minimum_depth_of_binary_tree/readme.md new file mode 100644 index 0000000..9583ec5 --- /dev/null +++ b/src/Algorithms/s0111_minimum_depth_of_binary_tree/readme.md @@ -0,0 +1,28 @@ +111\. Minimum Depth of Binary Tree + +Easy + +Given a binary tree, find its minimum depth. + +The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. + +**Note:** A leaf is a node with no children. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg) + +**Input:** root = [3,9,20,null,null,15,7] + +**Output:** 2 + +**Example 2:** + +**Input:** root = [2,null,3,null,4,null,5,null,6] + +**Output:** 5 + +**Constraints:** + +* The number of nodes in the tree is in the range [0, 105]. +* `-1000 <= Node.val <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0112.path-sum/path-sum.php b/src/Algorithms/s0112_path_sum/Solution.php similarity index 95% rename from src/Algorithms/0112.path-sum/path-sum.php rename to src/Algorithms/s0112_path_sum/Solution.php index 2162b70..ffe5f40 100644 --- a/src/Algorithms/0112.path-sum/path-sum.php +++ b/src/Algorithms/s0112_path_sum/Solution.php @@ -1,42 +1,42 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @param Integer $sum - * @return Boolean - */ - function hasPathSum($root, $sum) { - $s=0; - return self::hasPathSumUtil($root,$sum,$s); - } - - function hasPathSumUtil($root, $sum, $s) - { - if($root == null) - return false; - if($root->left==null && $root->right==null) - { - $s = $s + $root->val; - if ($s == $sum) - return true; - return false; - } - $s = $s + $root->val; - $left = self::hasPathSumUtil($root->left, $sum, $s); - $right = self::hasPathSumUtil($root->right, $sum, $s); - - if($left || $right) - return true; - - return false; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @param Integer $sum + * @return Boolean + */ + function hasPathSum($root, $sum) { + $s=0; + return self::hasPathSumUtil($root,$sum,$s); + } + + function hasPathSumUtil($root, $sum, $s) + { + if($root == null) + return false; + if($root->left==null && $root->right==null) + { + $s = $s + $root->val; + if ($s == $sum) + return true; + return false; + } + $s = $s + $root->val; + $left = self::hasPathSumUtil($root->left, $sum, $s); + $right = self::hasPathSumUtil($root->right, $sum, $s); + + if($left || $right) + return true; + + return false; + } +} diff --git a/src/Algorithms/s0112_path_sum/readme.md b/src/Algorithms/s0112_path_sum/readme.md new file mode 100644 index 0000000..9402da4 --- /dev/null +++ b/src/Algorithms/s0112_path_sum/readme.md @@ -0,0 +1,35 @@ +112\. Path Sum + +Easy + +Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. + +A **leaf** is a node with no children. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg) + +**Input:** root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 + +**Output:** true + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg) + +**Input:** root = [1,2,3], targetSum = 5 + +**Output:** false + +**Example 3:** + +**Input:** root = [1,2], targetSum = 0 + +**Output:** false + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 5000]`. +* `-1000 <= Node.val <= 1000` +* `-1000 <= targetSum <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0113.path-sum-ii/path-sum-ii.php b/src/Algorithms/s0113_path_sum_ii/Solution.php similarity index 95% rename from src/Algorithms/0113.path-sum-ii/path-sum-ii.php rename to src/Algorithms/s0113_path_sum_ii/Solution.php index 5389302..e36acba 100644 --- a/src/Algorithms/0113.path-sum-ii/path-sum-ii.php +++ b/src/Algorithms/s0113_path_sum_ii/Solution.php @@ -1,48 +1,48 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @param Integer $sum - * @return Integer[][] - */ - function pathSum($root, $sum) { - $res = []; - $temp = []; - - $curSum = 0; - self::pathSumUtil($root, $sum, $curSum, $res,$temp); - - return $res; - } - - function pathSumUtil($root, $sum, $curSum, &$res, &$temp) - { - - if($root==null) - return; - array_push($temp, $root->val); - if($root->left==null && $root->right==null) - { - $curSum = $curSum + $root->val; - - if($sum==$curSum) - { - array_push($res, $temp); - } - } - - $curSum = $curSum + $root->val; - self::pathSumUtil($root->left, $sum, $curSum, $res, $temp); - self::pathSumUtil($root->right, $sum, $curSum, $res, $temp); - array_pop($temp); - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @param Integer $sum + * @return Integer[][] + */ + function pathSum($root, $sum) { + $res = []; + $temp = []; + + $curSum = 0; + self::pathSumUtil($root, $sum, $curSum, $res,$temp); + + return $res; + } + + function pathSumUtil($root, $sum, $curSum, &$res, &$temp) + { + + if($root==null) + return; + array_push($temp, $root->val); + if($root->left==null && $root->right==null) + { + $curSum = $curSum + $root->val; + + if($sum==$curSum) + { + array_push($res, $temp); + } + } + + $curSum = $curSum + $root->val; + self::pathSumUtil($root->left, $sum, $curSum, $res, $temp); + self::pathSumUtil($root->right, $sum, $curSum, $res, $temp); + array_pop($temp); + } +} diff --git a/src/Algorithms/s0113_path_sum_ii/readme.md b/src/Algorithms/s0113_path_sum_ii/readme.md new file mode 100644 index 0000000..58c45e2 --- /dev/null +++ b/src/Algorithms/s0113_path_sum_ii/readme.md @@ -0,0 +1,37 @@ +113\. Path Sum II + +Medium + +Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. + +A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg) + +**Input:** root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 + +**Output:** [[5,4,11,2],[5,8,4,5]] + +**Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg) + +**Input:** root = [1,2,3], targetSum = 5 + +**Output:** [] + +**Example 3:** + +**Input:** root = [1,2], targetSum = 0 + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 5000]`. +* `-1000 <= Node.val <= 1000` +* `-1000 <= targetSum <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0114.flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.php b/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php similarity index 95% rename from src/Algorithms/0114.flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.php rename to src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php index e0ef07d..4924d1d 100644 --- a/src/Algorithms/0114.flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.php +++ b/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php @@ -1,32 +1,32 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($value) { $this->val = $value; } - * } - */ -class Solution { - - /** - * @param TreeNode $root - * @return NULL - */ - function flatten($root) { - if($root==null){ - return; - } - self::flatten($root->left); - self::flatten($root->right); - $left=$root->left; - $right=$root->right; - $root->left = null; - $root->right = $left; - $temp=$root; - while($temp->right != null){ - $temp = $temp->right; - } - $temp->right = $right; - } -} +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($value) { $this->val = $value; } + * } + */ +class Solution { + + /** + * @param TreeNode $root + * @return NULL + */ + function flatten($root) { + if($root==null){ + return; + } + self::flatten($root->left); + self::flatten($root->right); + $left=$root->left; + $right=$root->right; + $root->left = null; + $root->right = $left; + $temp=$root; + while($temp->right != null){ + $temp = $temp->right; + } + $temp->right = $right; + } +} diff --git a/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/readme.md b/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/readme.md new file mode 100644 index 0000000..ea101ac --- /dev/null +++ b/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/readme.md @@ -0,0 +1,35 @@ +114\. Flatten Binary Tree to Linked List + +Medium + +Given the `root` of a binary tree, flatten the tree into a "linked list": + +* The "linked list" should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. +* The "linked list" should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg) + +**Input:** root = [1,2,5,3,4,null,6] + +**Output:** [1,null,2,null,3,null,4,null,5,null,6] + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Example 3:** + +**Input:** root = [0] + +**Output:** [0] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 2000]`. +* `-100 <= Node.val <= 100` + +**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)? \ No newline at end of file diff --git a/src/Algorithms/0115.distinct-subsequences/distinct-subsequences.php b/src/Algorithms/s0115_distinct_subsequences/Solution.php similarity index 95% rename from src/Algorithms/0115.distinct-subsequences/distinct-subsequences.php rename to src/Algorithms/s0115_distinct_subsequences/Solution.php index 2fdfc30..64738fc 100644 --- a/src/Algorithms/0115.distinct-subsequences/distinct-subsequences.php +++ b/src/Algorithms/s0115_distinct_subsequences/Solution.php @@ -1,21 +1,21 @@ -class Solution { - - /** - * @param String $s - * @param String $t - * @return Integer - */ - function numDistinct($s, $t) { - $tLength = strlen($t); - $match = array_fill(0, $tLength + 1, 0); - $match[0] = 1; - for ($i = 0 ; $i < strlen($s); $i++){ - for ($j = $tLength; $j > 0; $j--){ - if ($s[$i] == $t[$j-1]){ - $match[$j] += $match[$j-1]; - } - } - } - return $match[$tLength]; - } -} +class Solution { + + /** + * @param String $s + * @param String $t + * @return Integer + */ + function numDistinct($s, $t) { + $tLength = strlen($t); + $match = array_fill(0, $tLength + 1, 0); + $match[0] = 1; + for ($i = 0 ; $i < strlen($s); $i++){ + for ($j = $tLength; $j > 0; $j--){ + if ($s[$i] == $t[$j-1]){ + $match[$j] += $match[$j-1]; + } + } + } + return $match[$tLength]; + } +} diff --git a/src/Algorithms/s0115_distinct_subsequences/readme.md b/src/Algorithms/s0115_distinct_subsequences/readme.md new file mode 100644 index 0000000..92e7337 --- /dev/null +++ b/src/Algorithms/s0115_distinct_subsequences/readme.md @@ -0,0 +1,30 @@ +115\. Distinct Subsequences + +Hard + +Given two strings `s` and `t`, return _the number of distinct subsequences of `s` which equals `t`_. + +A string's **subsequence** is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., `"ACE"` is a subsequence of `"ABCDE"` while `"AEC"` is not). + +It is guaranteed the answer fits on a 32-bit signed integer. + +**Example 1:** + +**Input:** s = "rabbbit", t = "rabbit" + +**Output:** 3 + +**Explanation:** As shown below, there are 3 ways you can generate "rabbit" from S. `**rabb**b**it**` `**ra**b**bbit**` `**rab**b**bit**` + +**Example 2:** + +**Input:** s = "babgbag", t = "bag" + +**Output:** 5 + +**Explanation:** As shown below, there are 5 ways you can generate "bag" from S. `**ba**b**g**bag` `**ba**bgba**g**` `**b**abgb**ag**` `ba**b**gb**ag**` `babg**bag**` + +**Constraints:** + +* `1 <= s.length, t.length <= 1000` +* `s` and `t` consist of English letters. \ No newline at end of file diff --git a/src/Algorithms/0116.populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.php b/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php similarity index 95% rename from src/Algorithms/0116.populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.php rename to src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php index fe45918..36abfaa 100644 --- a/src/Algorithms/0116.populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.php +++ b/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php @@ -1,44 +1,44 @@ -/* -// Definition for a Node. -class Node { - public $val; - public $left; - public $right; - public $next; - - @param Integer $val - @param Node $left - @param Node $right - @param Node $next - function __construct($val, $left, $right, $next) { - $this->val = $val; - $this->left = $left; - $this->right = $right; - $this->next = $next; - } -} -*/ -class Solution { - - /** - * @param Node $root - * @return Node - */ - function connect($root) { - if($root==null){ - return null; - } - - if($root->left!=null && $root->right!=null){ - $root->left->next = $root->right; - } - - if($root->next!=null && $root->right!=null){ - $root->right->next=$root->next->left; - } - - self::connect($root->left); - self::connect($root->right); - return $root; - } +/* +// Definition for a Node. +class Node { + public $val; + public $left; + public $right; + public $next; + + @param Integer $val + @param Node $left + @param Node $right + @param Node $next + function __construct($val, $left, $right, $next) { + $this->val = $val; + $this->left = $left; + $this->right = $right; + $this->next = $next; + } +} +*/ +class Solution { + + /** + * @param Node $root + * @return Node + */ + function connect($root) { + if($root==null){ + return null; + } + + if($root->left!=null && $root->right!=null){ + $root->left->next = $root->right; + } + + if($root->next!=null && $root->right!=null){ + $root->right->next=$root->next->left; + } + + self::connect($root->left); + self::connect($root->right); + return $root; + } } diff --git a/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/readme.md b/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/readme.md new file mode 100644 index 0000000..1b32768 --- /dev/null +++ b/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/readme.md @@ -0,0 +1,37 @@ +116\. Populating Next Right Pointers in Each Node + +Medium + +You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: + +struct Node { int val; Node \*left; Node \*right; Node \*next; } + +Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. + +Initially, all next pointers are set to `NULL`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/02/14/116_sample.png) + +**Input:** root = [1,2,3,4,5,6,7] + +**Output:** [1,#,2,3,#,4,5,6,7,#] + +**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 212 - 1]`. +* `-1000 <= Node.val <= 1000` + +**Follow-up:** + +* You may only use constant extra space. +* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem. \ No newline at end of file diff --git a/src/Algorithms/0117.populating-next-right-pointers-in-each-node-ii/populating-next-right-pointers-in-each-node-ii.php b/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php similarity index 95% rename from src/Algorithms/0117.populating-next-right-pointers-in-each-node-ii/populating-next-right-pointers-in-each-node-ii.php rename to src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php index 0db3001..4c3cc40 100644 --- a/src/Algorithms/0117.populating-next-right-pointers-in-each-node-ii/populating-next-right-pointers-in-each-node-ii.php +++ b/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php @@ -1,66 +1,66 @@ -/* -// Definition for a Node. -class Node { - public $val; - public $left; - public $right; - public $next; - - @param Integer $val - @param Node $left - @param Node $right - @param Node $next - function __construct($val, $left, $right, $next) { - $this->val = $val; - $this->left = $left; - $this->right = $right; - $this->next = $next; - } -} -*/ -class Solution { - - /** - * @param Node $root - * @return Node - */ - function connect($root) { - if ($root == null) - { - return null; - } - - $start = $root; - - while ($start != null) - { - $temp = $start; - $prev = new Node(-1, null, null, null); - $start = null; - - while ($temp != null) - { - if ($start == null) - { - $start = $temp->left == null ? $temp->right : $temp->left; - } - - if ($temp->left != null) - { - $prev->next = $temp->left; - $prev = $temp->left; - } - - if ($temp->right != null) - { - $prev->next = $temp->right; - $prev = $temp->right; - } - - $temp = $temp->next; - } - } - - return $root; - } -} +/* +// Definition for a Node. +class Node { + public $val; + public $left; + public $right; + public $next; + + @param Integer $val + @param Node $left + @param Node $right + @param Node $next + function __construct($val, $left, $right, $next) { + $this->val = $val; + $this->left = $left; + $this->right = $right; + $this->next = $next; + } +} +*/ +class Solution { + + /** + * @param Node $root + * @return Node + */ + function connect($root) { + if ($root == null) + { + return null; + } + + $start = $root; + + while ($start != null) + { + $temp = $start; + $prev = new Node(-1, null, null, null); + $start = null; + + while ($temp != null) + { + if ($start == null) + { + $start = $temp->left == null ? $temp->right : $temp->left; + } + + if ($temp->left != null) + { + $prev->next = $temp->left; + $prev = $temp->left; + } + + if ($temp->right != null) + { + $prev->next = $temp->right; + $prev = $temp->right; + } + + $temp = $temp->next; + } + } + + return $root; + } +} diff --git a/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/readme.md b/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/readme.md new file mode 100644 index 0000000..0d52734 --- /dev/null +++ b/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/readme.md @@ -0,0 +1,37 @@ +117\. Populating Next Right Pointers in Each Node II + +Medium + +Given a binary tree + +struct Node { int val; Node \*left; Node \*right; Node \*next; } + +Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. + +Initially, all next pointers are set to `NULL`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/02/15/117_sample.png) + +**Input:** root = [1,2,3,4,5,null,7] + +**Output:** [1,#,2,3,#,4,5,7,#] + +**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 6000]`. +* `-100 <= Node.val <= 100` + +**Follow-up:** + +* You may only use constant extra space. +* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem. \ No newline at end of file diff --git a/src/Algorithms/0118.pascals-triangle/pascals-triangle.php b/src/Algorithms/s0118_pascals_triangle/Solution.php similarity index 95% rename from src/Algorithms/0118.pascals-triangle/pascals-triangle.php rename to src/Algorithms/s0118_pascals_triangle/Solution.php index 5edd692..16fb754 100644 --- a/src/Algorithms/0118.pascals-triangle/pascals-triangle.php +++ b/src/Algorithms/s0118_pascals_triangle/Solution.php @@ -1,28 +1,28 @@ -class Solution { - - /** - * @param Integer $numRows - * @return Integer[][] - */ - function generate($numRows) { - $ans=[]; - if($numRows==0) - return $ans; - $t1=[]; - - array_push($t1, 1); - $count=0; - while($count!=$numRows) { - array_push($ans, $t1); - $t2=[]; - array_push($t2, 1); - for($i=1;$i$rowIndex) - return; - - $numElem = $row + 1; - $prev = 0; - for ($i=0; $i<$numElem; $i++) { - if ($i==$numElem-1) - array_push($lvl, 1); - else { - // in-place replacement using temporary `prev` - $curr = $lvl[$i]; - $lvl[$i] = $curr+$prev; - $prev = $curr; // update prev for next iteration - } - } - // recurse - self::getRowHelper($lvl, $row+1, $rowIndex); - } -} +class Solution { + + /** + * @param Integer $rowIndex + * @return Integer[] + */ + function getRow($rowIndex) { + $lvl = []; + self::getRowHelper($lvl, 0, $rowIndex); + return $lvl; + } + + function getRowHelper(&$lvl, $row, $rowIndex) { + // base case when the recursion should stop + if ($row>$rowIndex) + return; + + $numElem = $row + 1; + $prev = 0; + for ($i=0; $i<$numElem; $i++) { + if ($i==$numElem-1) + array_push($lvl, 1); + else { + // in-place replacement using temporary `prev` + $curr = $lvl[$i]; + $lvl[$i] = $curr+$prev; + $prev = $curr; // update prev for next iteration + } + } + // recurse + self::getRowHelper($lvl, $row+1, $rowIndex); + } +} diff --git a/src/Algorithms/s0119_pascals_triangle_ii/readme.md b/src/Algorithms/s0119_pascals_triangle_ii/readme.md new file mode 100644 index 0000000..8b074d7 --- /dev/null +++ b/src/Algorithms/s0119_pascals_triangle_ii/readme.md @@ -0,0 +1,33 @@ +119\. Pascal's Triangle II + +Easy + +Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. + +In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: + +![](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) + +**Example 1:** + +**Input:** rowIndex = 3 + +**Output:** [1,3,3,1] + +**Example 2:** + +**Input:** rowIndex = 0 + +**Output:** [1] + +**Example 3:** + +**Input:** rowIndex = 1 + +**Output:** [1,1] + +**Constraints:** + +* `0 <= rowIndex <= 33` + +**Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space? \ No newline at end of file diff --git a/src/Algorithms/0120.triangle/triangle.php b/src/Algorithms/s0120_triangle/Solution.php similarity index 97% rename from src/Algorithms/0120.triangle/triangle.php rename to src/Algorithms/s0120_triangle/Solution.php index a960626..32c2a27 100644 --- a/src/Algorithms/0120.triangle/triangle.php +++ b/src/Algorithms/s0120_triangle/Solution.php @@ -1,27 +1,27 @@ -class Solution { - - function minimumTotalOfLayer( - $triangle, &$cache, $layer, $totalLayerSize) { - $currentLayer = $triangle[$layer]; - if ($layer == $totalLayerSize - 1) { - for ($i = 0; $i < $totalLayerSize; $i++) $cache[$i] = $currentLayer[$i]; - return; - } - self::minimumTotalOfLayer($triangle, $cache, $layer + 1, $totalLayerSize); - $currentLayerSize = count($currentLayer); - for ($i = 0; $i < $currentLayerSize; $i++) { - $cache[$i] = min($cache[$i], $cache[$i + 1]) + $currentLayer[$i]; - } - } - - /** - * @param Integer[][] $triangle - * @return Integer - */ - function minimumTotal($triangle) { - if (empty($triangle)) return 0; - $cache = array_fill(0, count($triangle) + 1, 0); - self::minimumTotalOfLayer($triangle, $cache, 0, count($triangle)); - return $cache[0]; - } -} +class Solution { + + function minimumTotalOfLayer( + $triangle, &$cache, $layer, $totalLayerSize) { + $currentLayer = $triangle[$layer]; + if ($layer == $totalLayerSize - 1) { + for ($i = 0; $i < $totalLayerSize; $i++) $cache[$i] = $currentLayer[$i]; + return; + } + self::minimumTotalOfLayer($triangle, $cache, $layer + 1, $totalLayerSize); + $currentLayerSize = count($currentLayer); + for ($i = 0; $i < $currentLayerSize; $i++) { + $cache[$i] = min($cache[$i], $cache[$i + 1]) + $currentLayer[$i]; + } + } + + /** + * @param Integer[][] $triangle + * @return Integer + */ + function minimumTotal($triangle) { + if (empty($triangle)) return 0; + $cache = array_fill(0, count($triangle) + 1, 0); + self::minimumTotalOfLayer($triangle, $cache, 0, count($triangle)); + return $cache[0]; + } +} diff --git a/src/Algorithms/s0120_triangle/readme.md b/src/Algorithms/s0120_triangle/readme.md new file mode 100644 index 0000000..3441abb --- /dev/null +++ b/src/Algorithms/s0120_triangle/readme.md @@ -0,0 +1,37 @@ +120\. Triangle + +Medium + +Given a `triangle` array, return _the minimum path sum from top to bottom_. + +For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. + +**Example 1:** + +**Input:** triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] + +**Output:** 11 + +**Explanation:** + + The triangle looks like: + 2 + 3 4 + 6 5 7 + 4 1 8 3 + The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). + +**Example 2:** + +**Input:** triangle = [[-10]] + +**Output:** -10 + +**Constraints:** + +* `1 <= triangle.length <= 200` +* `triangle[0].length == 1` +* `triangle[i].length == triangle[i - 1].length + 1` +* -104 <= triangle[i][j] <= 104 + +**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle? \ No newline at end of file diff --git a/src/Algorithms/0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.php b/src/Algorithms/s0121_best_time_to_buy_and_sell_stock/Solution.php similarity index 96% rename from src/Algorithms/0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.php rename to src/Algorithms/s0121_best_time_to_buy_and_sell_stock/Solution.php index eb32558..d233957 100644 --- a/src/Algorithms/0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.php +++ b/src/Algorithms/s0121_best_time_to_buy_and_sell_stock/Solution.php @@ -1,30 +1,30 @@ -class Solution { - - /** - * @param Integer[] $prices - * @return Integer - */ - function maxProfit($prices) { - $max_profit=0; - $cur_profit=0; - $cur_min=0; - $cur_max= 0; - for($i = 0; $i < count($prices); $i++){ - if($i==0) { - $cur_min = $prices[$i]; - $cur_max = $prices[$i]; - continue; - } - if ($prices[$i]< $cur_min){ - $cur_min = $prices[$i]; - $cur_max = $prices[$i]; - } - else if($prices[$i] > $cur_max){ - $cur_max = $prices[$i]; - } - $cur_profit = $cur_max - $cur_min; - if($cur_profit > $max_profit) $max_profit = $cur_profit; - } - return $max_profit; - } -} +class Solution { + + /** + * @param Integer[] $prices + * @return Integer + */ + function maxProfit($prices) { + $max_profit=0; + $cur_profit=0; + $cur_min=0; + $cur_max= 0; + for($i = 0; $i < count($prices); $i++){ + if($i==0) { + $cur_min = $prices[$i]; + $cur_max = $prices[$i]; + continue; + } + if ($prices[$i]< $cur_min){ + $cur_min = $prices[$i]; + $cur_max = $prices[$i]; + } + else if($prices[$i] > $cur_max){ + $cur_max = $prices[$i]; + } + $cur_profit = $cur_max - $cur_min; + if($cur_profit > $max_profit) $max_profit = $cur_profit; + } + return $max_profit; + } +} diff --git a/src/Algorithms/s0121_best_time_to_buy_and_sell_stock/readme.md b/src/Algorithms/s0121_best_time_to_buy_and_sell_stock/readme.md new file mode 100644 index 0000000..6e22ccf --- /dev/null +++ b/src/Algorithms/s0121_best_time_to_buy_and_sell_stock/readme.md @@ -0,0 +1,30 @@ +121\. Best Time to Buy and Sell Stock + +Easy + +You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. + +You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. + +Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. + +**Example 1:** + +**Input:** prices = [7,1,5,3,6,4] + +**Output:** 5 + +**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + +**Example 2:** + +**Input:** prices = [7,6,4,3,1] + +**Output:** 0 + +**Explanation:** In this case, no transactions are done and the max profit = 0. + +**Constraints:** + +* 1 <= prices.length <= 105 +* 0 <= prices[i] <= 104 \ No newline at end of file diff --git a/src/Algorithms/0122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.php b/src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php similarity index 95% rename from src/Algorithms/0122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.php rename to src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php index 0f9d5c7..0aed8a0 100644 --- a/src/Algorithms/0122.best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.php +++ b/src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php @@ -1,15 +1,15 @@ -class Solution { - - /** - * @param Integer[] $prices - * @return Integer - */ - function maxProfit($prices) { - $res=0; - - for($i=0;$i1 <= prices.length <= 3 * 104 +* 0 <= prices[i] <= 104 \ No newline at end of file diff --git a/src/Algorithms/0123.best-time-to-buy-and-sell-stock-iii/best-time-to-buy-and-sell-stock-iii.php b/src/Algorithms/s0123_best_time_to_buy_and_sell_stock_iii/Solution.php similarity index 100% rename from src/Algorithms/0123.best-time-to-buy-and-sell-stock-iii/best-time-to-buy-and-sell-stock-iii.php rename to src/Algorithms/s0123_best_time_to_buy_and_sell_stock_iii/Solution.php diff --git a/src/Algorithms/s0123_best_time_to_buy_and_sell_stock_iii/readme.md b/src/Algorithms/s0123_best_time_to_buy_and_sell_stock_iii/readme.md new file mode 100644 index 0000000..d702747 --- /dev/null +++ b/src/Algorithms/s0123_best_time_to_buy_and_sell_stock_iii/readme.md @@ -0,0 +1,44 @@ +123\. Best Time to Buy and Sell Stock III + +Hard + +You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. + +Find the maximum profit you can achieve. You may complete **at most two transactions**. + +**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + +**Example 1:** + +**Input:** prices = [3,3,5,0,0,3,1,4] + +**Output:** 6 + +**Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. + +**Example 2:** + +**Input:** prices = [1,2,3,4,5] + +**Output:** 4 + +**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. + +**Example 3:** + +**Input:** prices = [7,6,4,3,1] + +**Output:** 0 + +**Explanation:** In this case, no transaction is done, i.e. max profit = 0. + +**Example 4:** + +**Input:** prices = [1] + +**Output:** 0 + +**Constraints:** + +* 1 <= prices.length <= 105 +* 0 <= prices[i] <= 105 \ No newline at end of file diff --git a/src/Algorithms/0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.php b/src/Algorithms/s0124_binary_tree_maximum_path_sum/Solution.php similarity index 100% rename from src/Algorithms/0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.php rename to src/Algorithms/s0124_binary_tree_maximum_path_sum/Solution.php diff --git a/src/Algorithms/s0124_binary_tree_maximum_path_sum/readme.md b/src/Algorithms/s0124_binary_tree_maximum_path_sum/readme.md new file mode 100644 index 0000000..29f9180 --- /dev/null +++ b/src/Algorithms/s0124_binary_tree_maximum_path_sum/readme.md @@ -0,0 +1,34 @@ +124\. Binary Tree Maximum Path Sum + +Hard + +A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. + +The **path sum** of a path is the sum of the node's values in the path. + +Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg) + +**Input:** root = [1,2,3] + +**Output:** 6 + +**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg) + +**Input:** root = [-10,9,20,null,null,15,7] + +**Output:** 42 + +**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. + +**Constraints:** + +* The number of nodes in the tree is in the range [1, 3 * 104]. +* `-1000 <= Node.val <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0125.valid-palindrome/valid-palindrome.php b/src/Algorithms/s0125_valid_palindrome/Solution.php similarity index 100% rename from src/Algorithms/0125.valid-palindrome/valid-palindrome.php rename to src/Algorithms/s0125_valid_palindrome/Solution.php diff --git a/src/Algorithms/s0125_valid_palindrome/readme.md b/src/Algorithms/s0125_valid_palindrome/readme.md new file mode 100644 index 0000000..3623442 --- /dev/null +++ b/src/Algorithms/s0125_valid_palindrome/readme.md @@ -0,0 +1,36 @@ +125\. Valid Palindrome + +Easy + +A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. + +Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_. + +**Example 1:** + +**Input:** s = "A man, a plan, a canal: Panama" + +**Output:** true + +**Explanation:** "amanaplanacanalpanama" is a palindrome. + +**Example 2:** + +**Input:** s = "race a car" + +**Output:** false + +**Explanation:** "raceacar" is not a palindrome. + +**Example 3:** + +**Input:** s = " " + +**Output:** true + +**Explanation:** s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. + +**Constraints:** + +* 1 <= s.length <= 2 * 105 +* `s` consists only of printable ASCII characters. \ No newline at end of file diff --git a/src/Algorithms/0128.longest-consecutive-sequence/longest-consecutive-sequence.php b/src/Algorithms/s0128_longest_consecutive_sequence/Solution.php similarity index 100% rename from src/Algorithms/0128.longest-consecutive-sequence/longest-consecutive-sequence.php rename to src/Algorithms/s0128_longest_consecutive_sequence/Solution.php diff --git a/src/Algorithms/s0128_longest_consecutive_sequence/readme.md b/src/Algorithms/s0128_longest_consecutive_sequence/readme.md new file mode 100644 index 0000000..b516939 --- /dev/null +++ b/src/Algorithms/s0128_longest_consecutive_sequence/readme.md @@ -0,0 +1,26 @@ +128\. Longest Consecutive Sequence + +Medium + +Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ + +You must write an algorithm that runs in `O(n)` time. + +**Example 1:** + +**Input:** nums = [100,4,200,1,3,2] + +**Output:** 4 + +**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. + +**Example 2:** + +**Input:** nums = [0,3,7,2,5,8,4,6,0,1] + +**Output:** 9 + +**Constraints:** + +* 0 <= nums.length <= 105 +* -109 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/Algorithms/0129.sum-root-to-leaf-numbers/sum-root-to-leaf-numbers.php b/src/Algorithms/s0129_sum_root_to_leaf_numbers/Solution.php similarity index 100% rename from src/Algorithms/0129.sum-root-to-leaf-numbers/sum-root-to-leaf-numbers.php rename to src/Algorithms/s0129_sum_root_to_leaf_numbers/Solution.php diff --git a/src/Algorithms/s0129_sum_root_to_leaf_numbers/readme.md b/src/Algorithms/s0129_sum_root_to_leaf_numbers/readme.md new file mode 100644 index 0000000..66a3401 --- /dev/null +++ b/src/Algorithms/s0129_sum_root_to_leaf_numbers/readme.md @@ -0,0 +1,39 @@ +129\. Sum Root to Leaf Numbers + +Medium + +You are given the `root` of a binary tree containing digits from `0` to `9` only. + +Each root-to-leaf path in the tree represents a number. + +* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. + +Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. + +A **leaf** node is a node with no children. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg) + +**Input:** root = [1,2,3] + +**Output:** 25 + +**Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg) + +**Input:** root = [4,9,0,5,1] + +**Output:** 1026 + +**Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. + +**Constraints:** + +* The number of nodes in the tree is in the range `[1, 1000]`. +* `0 <= Node.val <= 9` +* The depth of the tree will not exceed `10`. \ No newline at end of file diff --git a/src/Algorithms/0130.surrounded-regions/surrounded-regions.php b/src/Algorithms/s0130_surrounded_regions/Solution.php similarity index 100% rename from src/Algorithms/0130.surrounded-regions/surrounded-regions.php rename to src/Algorithms/s0130_surrounded_regions/Solution.php diff --git a/src/Algorithms/s0130_surrounded_regions/readme.md b/src/Algorithms/s0130_surrounded_regions/readme.md new file mode 100644 index 0000000..6b12aaa --- /dev/null +++ b/src/Algorithms/s0130_surrounded_regions/readme.md @@ -0,0 +1,30 @@ +130\. Surrounded Regions + +Medium + +Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. + +A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg) + +**Input:** board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] + +**Output:** [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] + +**Explanation:** Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically. + +**Example 2:** + +**Input:** board = [["X"]] + +**Output:** [["X"]] + +**Constraints:** + +* `m == board.length` +* `n == board[i].length` +* `1 <= m, n <= 200` +* `board[i][j]` is `'X'` or `'O'`. \ No newline at end of file diff --git a/src/Algorithms/0131.palindrome-partitioning/palindrome-partitioning.php b/src/Algorithms/s0131_palindrome_partitioning/Solution.php similarity index 100% rename from src/Algorithms/0131.palindrome-partitioning/palindrome-partitioning.php rename to src/Algorithms/s0131_palindrome_partitioning/Solution.php diff --git a/src/Algorithms/s0131_palindrome_partitioning/readme.md b/src/Algorithms/s0131_palindrome_partitioning/readme.md new file mode 100644 index 0000000..450d879 --- /dev/null +++ b/src/Algorithms/s0131_palindrome_partitioning/readme.md @@ -0,0 +1,24 @@ +131\. Palindrome Partitioning + +Medium + +Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return all possible palindrome partitioning of `s`. + +A **palindrome** string is a string that reads the same backward as forward. + +**Example 1:** + +**Input:** s = "aab" + +**Output:** [["a","a","b"],["aa","b"]] + +**Example 2:** + +**Input:** s = "a" + +**Output:** [["a"]] + +**Constraints:** + +* `1 <= s.length <= 16` +* `s` contains only lowercase English letters. \ No newline at end of file diff --git a/src/Algorithms/0132.palindrome-partitioning-ii/palindrome-partitioning-ii.php b/src/Algorithms/s0132_palindrome_partitioning_ii/Solution.php similarity index 96% rename from src/Algorithms/0132.palindrome-partitioning-ii/palindrome-partitioning-ii.php rename to src/Algorithms/s0132_palindrome_partitioning_ii/Solution.php index 25d1aff..264f753 100644 --- a/src/Algorithms/0132.palindrome-partitioning-ii/palindrome-partitioning-ii.php +++ b/src/Algorithms/s0132_palindrome_partitioning_ii/Solution.php @@ -1,26 +1,26 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function minCut($s) { - $n = strlen($s); - $dp = array_fill(0, $n, array_fill(0, $n, false)); - $cut = array_fill(0, $n, $n - 1); - - for($j = 0; $j < $n; $j++) { - for($i = 0; $i <= $j; $i++) { - if($s[$i] == $s[$j] && ($j - $i <= 1 || $dp[$i + 1][$j - 1])) { - $dp[$i][$j] = true; - if($i == 0) - $cut[$j] = 0; //no cut needed - else - $cut[$j] = min($cut[$j], $cut[$i - 1] + 1); - } - } - } - - return $cut[$n - 1]; - } -} +class Solution { + + /** + * @param String $s + * @return Integer + */ + function minCut($s) { + $n = strlen($s); + $dp = array_fill(0, $n, array_fill(0, $n, false)); + $cut = array_fill(0, $n, $n - 1); + + for($j = 0; $j < $n; $j++) { + for($i = 0; $i <= $j; $i++) { + if($s[$i] == $s[$j] && ($j - $i <= 1 || $dp[$i + 1][$j - 1])) { + $dp[$i][$j] = true; + if($i == 0) + $cut[$j] = 0; //no cut needed + else + $cut[$j] = min($cut[$j], $cut[$i - 1] + 1); + } + } + } + + return $cut[$n - 1]; + } +} diff --git a/src/Algorithms/s0132_palindrome_partitioning_ii/readme.md b/src/Algorithms/s0132_palindrome_partitioning_ii/readme.md new file mode 100644 index 0000000..b1aa3db --- /dev/null +++ b/src/Algorithms/s0132_palindrome_partitioning_ii/readme.md @@ -0,0 +1,32 @@ +132\. Palindrome Partitioning II + +Hard + +Given a string `s`, partition `s` such that every substring of the partition is a palindrome. + +Return _the minimum cuts needed_ for a palindrome partitioning of `s`. + +**Example 1:** + +**Input:** s = "aab" + +**Output:** 1 + +**Explanation:** The palindrome partitioning ["aa","b"] could be produced using 1 cut. + +**Example 2:** + +**Input:** s = "a" + +**Output:** 0 + +**Example 3:** + +**Input:** s = "ab" + +**Output:** 1 + +**Constraints:** + +* `1 <= s.length <= 2000` +* `s` consists of lower-case English letters only. \ No newline at end of file diff --git a/src/Algorithms/0133.clone-graph/clone-graph.php b/src/Algorithms/s0133_clone_graph/Solution.php similarity index 95% rename from src/Algorithms/0133.clone-graph/clone-graph.php rename to src/Algorithms/s0133_clone_graph/Solution.php index b370908..494e31f 100644 --- a/src/Algorithms/0133.clone-graph/clone-graph.php +++ b/src/Algorithms/s0133_clone_graph/Solution.php @@ -1,39 +1,39 @@ -/* -// Definition for a Node. -class Node { - public $val; - public $neighbors; - - @param Integer $val - @param list $neighbors - function __construct($val, $neighbors) { - $this->val = $val; - $this->neighbors = $neighbors; - } -} -*/ -class Solution { - - /** - * @param Node $node - * @return Node - */ - function cloneGraph($node) { - $seen = []; - return self::cloneHelper($node, $seen); - } - - function cloneHelper(&$origNode, &$seen) { - if ($origNode == null) - return null; - $iter = $seen[$origNode->val]; - if ($iter != null) - return $iter; - - $newNode = new Node($origNode->val, []); - $seen[$origNode->val] = $newNode; - foreach ($origNode->neighbors as $neigh) - array_push($newNode->neighbors, self::cloneHelper($neigh, $seen)); - return $newNode; - } -} +/* +// Definition for a Node. +class Node { + public $val; + public $neighbors; + + @param Integer $val + @param list $neighbors + function __construct($val, $neighbors) { + $this->val = $val; + $this->neighbors = $neighbors; + } +} +*/ +class Solution { + + /** + * @param Node $node + * @return Node + */ + function cloneGraph($node) { + $seen = []; + return self::cloneHelper($node, $seen); + } + + function cloneHelper(&$origNode, &$seen) { + if ($origNode == null) + return null; + $iter = $seen[$origNode->val]; + if ($iter != null) + return $iter; + + $newNode = new Node($origNode->val, []); + $seen[$origNode->val] = $newNode; + foreach ($origNode->neighbors as $neigh) + array_push($newNode->neighbors, self::cloneHelper($neigh, $seen)); + return $newNode; + } +} diff --git a/src/Algorithms/s0133_clone_graph/readme.md b/src/Algorithms/s0133_clone_graph/readme.md new file mode 100644 index 0000000..97ec332 --- /dev/null +++ b/src/Algorithms/s0133_clone_graph/readme.md @@ -0,0 +1,69 @@ +133\. Clone Graph + +Medium + +Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. + +Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. + +Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. + +class Node { public int val; public List neighbors; } + +**Test case format:** + +For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. + +**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. + +The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png) + +**Input:** adjList = [[2,4],[1,3],[2,4],[1,3]] + +**Output:** [[2,4],[1,3],[2,4],[1,3]] + +**Explanation:** + + There are 4 nodes in the graph. + 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). + 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). + 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). + 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/01/07/graph.png) + +**Input:** adjList = [[]] + +**Output:** [[]] + +**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. + +**Example 3:** + +**Input:** adjList = [] + +**Output:** [] + +**Explanation:** This an empty graph, it does not have any nodes. + +**Example 4:** + +![](https://assets.leetcode.com/uploads/2020/01/07/graph-1.png) + +**Input:** adjList = [[2],[1]] + +**Output:** [[2],[1]] + +**Constraints:** + +* The number of nodes in the graph is in the range `[0, 100]`. +* `1 <= Node.val <= 100` +* `Node.val` is unique for each node. +* There are no repeated edges and no self-loops in the graph. +* The Graph is connected and all nodes can be visited starting from the given node. \ No newline at end of file diff --git a/src/Algorithms/0134.gas-station/gas-station.php b/src/Algorithms/s0134_gas_station/Solution.php similarity index 95% rename from src/Algorithms/0134.gas-station/gas-station.php rename to src/Algorithms/s0134_gas_station/Solution.php index 22a178d..4bee582 100644 --- a/src/Algorithms/0134.gas-station/gas-station.php +++ b/src/Algorithms/s0134_gas_station/Solution.php @@ -1,22 +1,22 @@ -class Solution { - - /** - * @param Integer[] $gas - * @param Integer[] $cost - * @return Integer - */ - function canCompleteCircuit($gas, $cost) { - $sum = 0; - $min = 2147483647; - $minIndex = 0; - for($i=0; $iith station is `gas[i]`. + +You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. + +Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** + +**Example 1:** + +**Input:** gas = [1,2,3,4,5], cost = [3,4,5,1,2] + +**Output:** 3 + +**Explanation:** + + Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 + Travel to station 4. Your tank = 4 - 1 + 5 = 8 + Travel to station 0. Your tank = 8 - 2 + 1 = 7 + Travel to station 1. Your tank = 7 - 3 + 2 = 6 + Travel to station 2. Your tank = 6 - 4 + 3 = 5 + Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. + Therefore, return 3 as the starting index. + +**Example 2:** + +**Input:** gas = [2,3,4], cost = [3,4,3] + +**Output:** -1 + +**Explanation:** + + You can't start at station 0 or 1, as there is not enough gas to travel to the next station. + Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 + Travel to station 0. Your tank = 4 - 3 + 2 = 3 + Travel to station 1. Your tank = 3 - 3 + 3 = 3 + You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. + Therefore, you can't travel around the circuit once no matter where you start. + +**Constraints:** + +* `gas.length == n` +* `cost.length == n` +* 1 <= n <= 105 +* 0 <= gas[i], cost[i] <= 104 \ No newline at end of file diff --git a/src/Algorithms/0135.candy/candy.php b/src/Algorithms/s0135_candy/Solution.php similarity index 94% rename from src/Algorithms/0135.candy/candy.php rename to src/Algorithms/s0135_candy/Solution.php index 6ceaad0..324b5b7 100644 --- a/src/Algorithms/0135.candy/candy.php +++ b/src/Algorithms/s0135_candy/Solution.php @@ -1,33 +1,33 @@ -class Solution { - - /** - * @param Integer[] $ratings - * @return Integer - */ - function candy($ratings) { - $n = count($ratings); - $sum = 0; - $candies = array_fill(0, $n, 1); - - for($i = 1; $i < $n; $i++) - { - if($ratings[$i] > $ratings[$i - 1]) - { - $candies[$i] = $candies[$i - 1] + 1; - } - } - - for($i = $n - 1; $i > 0; $i--) - { - if($ratings[$i - 1] > $ratings[$i] && $candies[$i - 1] <= $candies[$i]) - { - $candies[$i - 1] = $candies[$i] + 1; - } - } - - foreach($candies as $candy) - $sum += $candy; - - return $sum; - } -} +class Solution { + + /** + * @param Integer[] $ratings + * @return Integer + */ + function candy($ratings) { + $n = count($ratings); + $sum = 0; + $candies = array_fill(0, $n, 1); + + for($i = 1; $i < $n; $i++) + { + if($ratings[$i] > $ratings[$i - 1]) + { + $candies[$i] = $candies[$i - 1] + 1; + } + } + + for($i = $n - 1; $i > 0; $i--) + { + if($ratings[$i - 1] > $ratings[$i] && $candies[$i - 1] <= $candies[$i]) + { + $candies[$i - 1] = $candies[$i] + 1; + } + } + + foreach($candies as $candy) + $sum += $candy; + + return $sum; + } +} diff --git a/src/Algorithms/s0135_candy/readme.md b/src/Algorithms/s0135_candy/readme.md new file mode 100644 index 0000000..ad9d72a --- /dev/null +++ b/src/Algorithms/s0135_candy/readme.md @@ -0,0 +1,34 @@ +135\. Candy + +Hard + +There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. + +You are giving candies to these children subjected to the following requirements: + +* Each child must have at least one candy. +* Children with a higher rating get more candies than their neighbors. + +Return _the minimum number of candies you need to have to distribute the candies to the children_. + +**Example 1:** + +**Input:** ratings = [1,0,2] + +**Output:** 5 + +**Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively. + +**Example 2:** + +**Input:** ratings = [1,2,2] + +**Output:** 4 + +**Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. + +**Constraints:** + +* `n == ratings.length` +* 1 <= n <= 2 * 104 +* 0 <= ratings[i] <= 2 * 104 \ No newline at end of file diff --git a/src/Algorithms/0136.single-number/single-number.php b/src/Algorithms/s0136_single_number/Solution.php similarity index 95% rename from src/Algorithms/0136.single-number/single-number.php rename to src/Algorithms/s0136_single_number/Solution.php index 8840ebe..ee9989d 100644 --- a/src/Algorithms/0136.single-number/single-number.php +++ b/src/Algorithms/s0136_single_number/Solution.php @@ -1,13 +1,13 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function singleNumber($nums) { - for ($i = 1; $i < count($nums); $i++) { - $nums[0] = $nums[0] ^ $nums[$i]; - } - return $nums[0]; - } -} +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function singleNumber($nums) { + for ($i = 1; $i < count($nums); $i++) { + $nums[0] = $nums[0] ^ $nums[$i]; + } + return $nums[0]; + } +} diff --git a/src/Algorithms/s0136_single_number/readme.md b/src/Algorithms/s0136_single_number/readme.md new file mode 100644 index 0000000..5f9d3df --- /dev/null +++ b/src/Algorithms/s0136_single_number/readme.md @@ -0,0 +1,31 @@ +136\. Single Number + +Easy + +Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + +**Example 1:** + +**Input:** nums = [2,2,1] + +**Output:** 1 + +**Example 2:** + +**Input:** nums = [4,1,2,1,2] + +**Output:** 4 + +**Example 3:** + +**Input:** nums = [1] + +**Output:** 1 + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* -3 * 104 <= nums[i] <= 3 * 104 +* Each element in the array appears twice except for one element which appears only once. \ No newline at end of file diff --git a/src/Algorithms/0137.single-number-ii/single-number-ii.php b/src/Algorithms/s0137_single_number_ii/Solution.php similarity index 100% rename from src/Algorithms/0137.single-number-ii/single-number-ii.php rename to src/Algorithms/s0137_single_number_ii/Solution.php diff --git a/src/Algorithms/s0137_single_number_ii/readme.md b/src/Algorithms/s0137_single_number_ii/readme.md new file mode 100644 index 0000000..9b9aafe --- /dev/null +++ b/src/Algorithms/s0137_single_number_ii/readme.md @@ -0,0 +1,25 @@ +137\. Single Number II + +Medium + +Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + +**Example 1:** + +**Input:** nums = [2,2,3,2] + +**Output:** 3 + +**Example 2:** + +**Input:** nums = [0,1,0,1,0,1,99] + +**Output:** 99 + +**Constraints:** + +* 1 <= nums.length <= 3 * 104 +* -231 <= nums[i] <= 231 - 1 +* Each element in `nums` appears exactly **three times** except for one element which appears **once**. \ No newline at end of file diff --git a/src/Algorithms/0138.copy-list-with-random-pointer/copy-list-with-random-pointer.php b/src/Algorithms/s0138_copy_list_with_random_pointer/Solution.php similarity index 100% rename from src/Algorithms/0138.copy-list-with-random-pointer/copy-list-with-random-pointer.php rename to src/Algorithms/s0138_copy_list_with_random_pointer/Solution.php diff --git a/src/Algorithms/s0138_copy_list_with_random_pointer/readme.md b/src/Algorithms/s0138_copy_list_with_random_pointer/readme.md new file mode 100644 index 0000000..9e2f939 --- /dev/null +++ b/src/Algorithms/s0138_copy_list_with_random_pointer/readme.md @@ -0,0 +1,56 @@ +138\. Copy List with Random Pointer + +Medium + +A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. + +Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. + +For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. + +Return _the head of the copied linked list_. + +The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: + +* `val`: an integer representing `Node.val` +* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. + +Your code will **only** be given the `head` of the original linked list. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2019/12/18/e1.png) + +**Input:** head = [[7,null],[13,0],[11,4],[10,2],[1,0]] + +**Output:** [[7,null],[13,0],[11,4],[10,2],[1,0]] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2019/12/18/e2.png) + +**Input:** head = [[1,1],[2,1]] + +**Output:** [[1,1],[2,1]] + +**Example 3:** + +**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)** + +**Input:** head = [[3,null],[3,0],[3,null]] + +**Output:** [[3,null],[3,0],[3,null]] + +**Example 4:** + +**Input:** head = [] + +**Output:** [] + +**Explanation:** The given linked list is empty (null pointer), so return null. + +**Constraints:** + +* `0 <= n <= 1000` +* `-10000 <= Node.val <= 10000` +* `Node.random` is `null` or is pointing to some node in the linked list. \ No newline at end of file diff --git a/src/Algorithms/0139.word-break/word-break.php b/src/Algorithms/s0139_word_break/Solution.php similarity index 100% rename from src/Algorithms/0139.word-break/word-break.php rename to src/Algorithms/s0139_word_break/Solution.php diff --git a/src/Algorithms/s0139_word_break/readme.md b/src/Algorithms/s0139_word_break/readme.md new file mode 100644 index 0000000..7e152e6 --- /dev/null +++ b/src/Algorithms/s0139_word_break/readme.md @@ -0,0 +1,37 @@ +139\. Word Break + +Medium + +Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. + +**Note** that the same word in the dictionary may be reused multiple times in the segmentation. + +**Example 1:** + +**Input:** s = "leetcode", wordDict = ["leet","code"] + +**Output:** true + +**Explanation:** Return true because "leetcode" can be segmented as "leet code". + +**Example 2:** + +**Input:** s = "applepenapple", wordDict = ["apple","pen"] + +**Output:** true + +**Explanation:** Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word. + +**Example 3:** + +**Input:** s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] + +**Output:** false + +**Constraints:** + +* `1 <= s.length <= 300` +* `1 <= wordDict.length <= 1000` +* `1 <= wordDict[i].length <= 20` +* `s` and `wordDict[i]` consist of only lowercase English letters. +* All the strings of `wordDict` are **unique**. \ No newline at end of file diff --git a/src/Algorithms/0140.word-break-ii/word-break-ii.php b/src/Algorithms/s0140_word_break_ii/Solution.php similarity index 100% rename from src/Algorithms/0140.word-break-ii/word-break-ii.php rename to src/Algorithms/s0140_word_break_ii/Solution.php diff --git a/src/Algorithms/s0140_word_break_ii/readme.md b/src/Algorithms/s0140_word_break_ii/readme.md new file mode 100644 index 0000000..f62297a --- /dev/null +++ b/src/Algorithms/s0140_word_break_ii/readme.md @@ -0,0 +1,35 @@ +140\. Word Break II + +Hard + +Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. + +**Note** that the same word in the dictionary may be reused multiple times in the segmentation. + +**Example 1:** + +**Input:** s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] + +**Output:** ["cats and dog","cat sand dog"] + +**Example 2:** + +**Input:** s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] + +**Output:** ["pine apple pen apple","pineapple pen apple","pine applepen apple"] + +**Explanation:** Note that you are allowed to reuse a dictionary word. + +**Example 3:** + +**Input:** s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] + +**Output:** [] + +**Constraints:** + +* `1 <= s.length <= 20` +* `1 <= wordDict.length <= 1000` +* `1 <= wordDict[i].length <= 10` +* `s` and `wordDict[i]` consist of only lowercase English letters. +* All the strings of `wordDict` are **unique**. \ No newline at end of file diff --git a/src/Algorithms/0143.reorder-list/reorder-list.php b/src/Algorithms/s0143_reorder_list/Solution.php similarity index 100% rename from src/Algorithms/0143.reorder-list/reorder-list.php rename to src/Algorithms/s0143_reorder_list/Solution.php diff --git a/src/Algorithms/s0143_reorder_list/readme.md b/src/Algorithms/s0143_reorder_list/readme.md new file mode 100644 index 0000000..b02bacd --- /dev/null +++ b/src/Algorithms/s0143_reorder_list/readme.md @@ -0,0 +1,34 @@ +143\. Reorder List + +Medium + +You are given the head of a singly linked-list. The list can be represented as: + +L0 → L1 → … → Ln - 1 → Ln + +_Reorder the list to be on the following form:_ + +L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … + +You may not modify the values in the list's nodes. Only nodes themselves may be changed. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg) + +**Input:** head = [1,2,3,4] + +**Output:** [1,4,2,3] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg) + +**Input:** head = [1,2,3,4,5] + +**Output:** [1,5,2,4,3] + +**Constraints:** + +* The number of nodes in the list is in the range [1, 5 * 104]. +* `1 <= Node.val <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0144.binary-tree-preorder-traversal/binary-tree-preorder-traversal.php b/src/Algorithms/s0144_binary_tree_preorder_traversal/Solution.php similarity index 100% rename from src/Algorithms/0144.binary-tree-preorder-traversal/binary-tree-preorder-traversal.php rename to src/Algorithms/s0144_binary_tree_preorder_traversal/Solution.php diff --git a/src/Algorithms/s0144_binary_tree_preorder_traversal/readme.md b/src/Algorithms/s0144_binary_tree_preorder_traversal/readme.md new file mode 100644 index 0000000..3e28992 --- /dev/null +++ b/src/Algorithms/s0144_binary_tree_preorder_traversal/readme.md @@ -0,0 +1,48 @@ +144\. Binary Tree Preorder Traversal + +Easy + +Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg) + +**Input:** root = [1,null,2,3] + +**Output:** [1,2,3] + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Example 3:** + +**Input:** root = [1] + +**Output:** [1] + +**Example 4:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_5.jpg) + +**Input:** root = [1,2] + +**Output:** [1,2] + +**Example 5:** + +![](https://assets.leetcode.com/uploads/2020/09/15/inorder_4.jpg) + +**Input:** root = [1,null,2] + +**Output:** [1,2] + +**Constraints:** + +* The number of nodes in the tree is in the range `[0, 100]`. +* `-100 <= Node.val <= 100` + +**Follow up:** Recursive solution is trivial, could you do it iteratively? \ No newline at end of file diff --git a/src/Algorithms/0145.binary-tree-postorder-traversal/binary-tree-postorder-traversal.php b/src/Algorithms/s0145_binary_tree_postorder_traversal/Solution.php similarity index 100% rename from src/Algorithms/0145.binary-tree-postorder-traversal/binary-tree-postorder-traversal.php rename to src/Algorithms/s0145_binary_tree_postorder_traversal/Solution.php diff --git a/src/Algorithms/s0145_binary_tree_postorder_traversal/readme.md b/src/Algorithms/s0145_binary_tree_postorder_traversal/readme.md new file mode 100644 index 0000000..b41490e --- /dev/null +++ b/src/Algorithms/s0145_binary_tree_postorder_traversal/readme.md @@ -0,0 +1,48 @@ +145\. Binary Tree Postorder Traversal + +Easy + +Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg) + +**Input:** root = [1,null,2,3] + +**Output:** [3,2,1] + +**Example 2:** + +**Input:** root = [] + +**Output:** [] + +**Example 3:** + +**Input:** root = [1] + +**Output:** [1] + +**Example 4:** + +![](https://assets.leetcode.com/uploads/2020/08/28/pre3.jpg) + +**Input:** root = [1,2] + +**Output:** [2,1] + +**Example 5:** + +![](https://assets.leetcode.com/uploads/2020/08/28/pre2.jpg) + +**Input:** root = [1,null,2] + +**Output:** [2,1] + +**Constraints:** + +* The number of the nodes in the tree is in the range `[0, 100]`. +* `-100 <= Node.val <= 100` + +**Follow up:** Recursive solution is trivial, could you do it iteratively? \ No newline at end of file diff --git a/src/Algorithms/0146.lru-cache/lru-cache.php b/src/Algorithms/s0146_lru_cache/LRUCache.php similarity index 100% rename from src/Algorithms/0146.lru-cache/lru-cache.php rename to src/Algorithms/s0146_lru_cache/LRUCache.php diff --git a/src/Algorithms/s0146_lru_cache/readme.md b/src/Algorithms/s0146_lru_cache/readme.md new file mode 100644 index 0000000..8bc0954 --- /dev/null +++ b/src/Algorithms/s0146_lru_cache/readme.md @@ -0,0 +1,39 @@ +146\. LRU Cache + +Medium + +Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. + +Implement the `LRUCache` class: + +* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. +* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. +* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. + +The functions `get` and `put` must each run in `O(1)` average time complexity. + +**Example 1:** + +**Input** ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] + +**Output:** [null, null, null, 1, null, -1, null, -1, 3, 4] + +**Explanation:** + + LRUCache lRUCache = new LRUCache(2); + lRUCache.put(1, 1); // cache is {1=1} + lRUCache.put(2, 2); // cache is {1=1, 2=2} + lRUCache.get(1); // return 1 + lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} + lRUCache.get(2); // returns -1 (not found) + lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} + lRUCache.get(1); // return -1 (not found) + lRUCache.get(3); // return 3 + lRUCache.get(4); // return 4 + +**Constraints:** + +* `1 <= capacity <= 3000` +* 0 <= key <= 104 +* 0 <= value <= 105 +* At most 2 * 105 calls will be made to `get` and `put`. diff --git a/src/Algorithms/0147.insertion-sort-list/insertion-sort-list.php b/src/Algorithms/s0147_insertion_sort_list/Solution.php similarity index 100% rename from src/Algorithms/0147.insertion-sort-list/insertion-sort-list.php rename to src/Algorithms/s0147_insertion_sort_list/Solution.php diff --git a/src/Algorithms/s0147_insertion_sort_list/readme.md b/src/Algorithms/s0147_insertion_sort_list/readme.md new file mode 100644 index 0000000..b533808 --- /dev/null +++ b/src/Algorithms/s0147_insertion_sort_list/readme.md @@ -0,0 +1,36 @@ +147\. Insertion Sort List + +Medium + +Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. + +The steps of the **insertion sort** algorithm: + +1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. +2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. +3. It repeats until no input elements remain. + +The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. + +![](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg) + +**Input:** head = [4,2,1,3] + +**Output:** [1,2,3,4] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg) + +**Input:** head = [-1,5,3,4,0] + +**Output:** [-1,0,3,4,5] + +**Constraints:** + +* The number of nodes in the list is in the range `[1, 5000]`. +* `-5000 <= Node.val <= 5000` \ No newline at end of file diff --git a/src/Algorithms/0148.sort-list/sort-list.php b/src/Algorithms/s0148_sort_list/Solution.php similarity index 100% rename from src/Algorithms/0148.sort-list/sort-list.php rename to src/Algorithms/s0148_sort_list/Solution.php diff --git a/src/Algorithms/s0148_sort_list/readme.md b/src/Algorithms/s0148_sort_list/readme.md new file mode 100644 index 0000000..94f637d --- /dev/null +++ b/src/Algorithms/s0148_sort_list/readme.md @@ -0,0 +1,34 @@ +148\. Sort List + +Medium + +Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg) + +**Input:** head = [4,2,1,3] + +**Output:** [1,2,3,4] + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg) + +**Input:** head = [-1,5,3,4,0] + +**Output:** [-1,0,3,4,5] + +**Example 3:** + +**Input:** head = [] + +**Output:** [] + +**Constraints:** + +* The number of nodes in the list is in the range [0, 5 * 104]. +* -105 <= Node.val <= 105 + +**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)? \ No newline at end of file diff --git a/src/Algorithms/0149.max-points-on-a-line/max-points-on-a-line.php b/src/Algorithms/s0149_max_points_on_a_line/Solution.php similarity index 100% rename from src/Algorithms/0149.max-points-on-a-line/max-points-on-a-line.php rename to src/Algorithms/s0149_max_points_on_a_line/Solution.php diff --git a/src/Algorithms/s0149_max_points_on_a_line/readme.md b/src/Algorithms/s0149_max_points_on_a_line/readme.md new file mode 100644 index 0000000..5e23330 --- /dev/null +++ b/src/Algorithms/s0149_max_points_on_a_line/readme.md @@ -0,0 +1,28 @@ +149\. Max Points on a Line + +Hard + +Given an array of `points` where points[i] = [xi, yi] represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg) + +**Input:** points = [[1,1],[2,2],[3,3]] + +**Output:** 3 + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg) + +**Input:** points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] + +**Output:** 4 + +**Constraints:** + +* `1 <= points.length <= 300` +* `points[i].length == 2` +* -104 <= xi, yi <= 104 +* All the `points` are **unique**. \ No newline at end of file diff --git a/src/Algorithms/0150.evaluate-reverse-polish-notation/evaluate-reverse-polish-notation.php b/src/Algorithms/s0150_evaluate_reverse_polish_notation/Solution.php similarity index 100% rename from src/Algorithms/0150.evaluate-reverse-polish-notation/evaluate-reverse-polish-notation.php rename to src/Algorithms/s0150_evaluate_reverse_polish_notation/Solution.php diff --git a/src/Algorithms/s0150_evaluate_reverse_polish_notation/readme.md b/src/Algorithms/s0150_evaluate_reverse_polish_notation/readme.md new file mode 100644 index 0000000..a16fe93 --- /dev/null +++ b/src/Algorithms/s0150_evaluate_reverse_polish_notation/readme.md @@ -0,0 +1,48 @@ +150\. Evaluate Reverse Polish Notation + +Medium + +Evaluate the value of an arithmetic expression in [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). + +Valid operators are `+`, `-`, `*`, and `/`. Each operand may be an integer or another expression. + +**Note** that division between two integers should truncate toward zero. + +It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. + +**Example 1:** + +**Input:** tokens = ["2","1","+","3","\*"] + +**Output:** 9 + +**Explanation:** ((2 + 1) \* 3) = 9 + +**Example 2:** + +**Input:** tokens = ["4","13","5","/","+"] + +**Output:** 6 + +**Explanation:** (4 + (13 / 5)) = 6 + +**Example 3:** + +**Input:** tokens = ["10","6","9","3","+","-11","\*","/","\*","17","+","5","+"] + +**Output:** 22 + +**Explanation:** + + ((10 \* (6 / ((9 + 3) \* -11))) + 17) + 5 + = ((10 \* (6 / (12 \* -11))) + 17) + 5 + = ((10 \* (6 / -132)) + 17) + 5 + = ((10 \* 0) + 17) + 5 + = (0 + 17) + 5 + = 17 + 5 + = 22 + +**Constraints:** + +* 1 <= tokens.length <= 104 +* `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"`, or `"/"`, or an integer in the range `[-200, 200]`. \ No newline at end of file diff --git a/src/Algorithms/0151.reverse-words-in-a-string/reverse-words-in-a-string.php b/src/Algorithms/s0151_reverse_words_in_a_string/Solution.php similarity index 100% rename from src/Algorithms/0151.reverse-words-in-a-string/reverse-words-in-a-string.php rename to src/Algorithms/s0151_reverse_words_in_a_string/Solution.php diff --git a/src/Algorithms/s0151_reverse_words_in_a_string/readme.md b/src/Algorithms/s0151_reverse_words_in_a_string/readme.md new file mode 100644 index 0000000..8817dec --- /dev/null +++ b/src/Algorithms/s0151_reverse_words_in_a_string/readme.md @@ -0,0 +1,53 @@ +151\. Reverse Words in a String + +Medium + +Given an input string `s`, reverse the order of the **words**. + +A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. + +Return _a string of the words in reverse order concatenated by a single space._ + +**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + +**Example 1:** + +**Input:** s = "the sky is blue" + +**Output:** "blue is sky the" + +**Example 2:** + +**Input:** s = " hello world " + +**Output:** "world hello" + +**Explanation:** Your reversed string should not contain leading or trailing spaces. + +**Example 3:** + +**Input:** s = "a good example" + +**Output:** "example good a" + +**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. + +**Example 4:** + +**Input:** s = " Bob Loves Alice " + +**Output:** "Alice Loves Bob" + +**Example 5:** + +**Input:** s = "Alice does not even like bob" + +**Output:** "bob like even not does Alice" + +**Constraints:** + +* 1 <= s.length <= 104 +* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. +* There is **at least one** word in `s`. + +**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space? \ No newline at end of file diff --git a/src/Algorithms/0152.maximum-product-subarray/maximum-product-subarray.php b/src/Algorithms/s0152_maximum_product_subarray/Solution.php similarity index 100% rename from src/Algorithms/0152.maximum-product-subarray/maximum-product-subarray.php rename to src/Algorithms/s0152_maximum_product_subarray/Solution.php diff --git a/src/Algorithms/s0152_maximum_product_subarray/readme.md b/src/Algorithms/s0152_maximum_product_subarray/readme.md new file mode 100644 index 0000000..13f4e95 --- /dev/null +++ b/src/Algorithms/s0152_maximum_product_subarray/readme.md @@ -0,0 +1,31 @@ +152\. Maximum Product Subarray + +Medium + +Given an integer array `nums`, find a contiguous non-empty subarray within the array that has the largest product, and return _the product_. + +It is **guaranteed** that the answer will fit in a **32-bit** integer. + +A **subarray** is a contiguous subsequence of the array. + +**Example 1:** + +**Input:** nums = [2,3,-2,4] + +**Output:** 6 + +**Explanation:** [2,3] has the largest product 6. + +**Example 2:** + +**Input:** nums = [-2,0,-1] + +**Output:** 0 + +**Explanation:** The result cannot be 2, because [-2,-1] is not a subarray. + +**Constraints:** + +* 1 <= nums.length <= 2 * 104 +* `-10 <= nums[i] <= 10` +* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. \ No newline at end of file diff --git a/src/Algorithms/0153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.php b/src/Algorithms/s0153_find_minimum_in_rotated_sorted_array/Solution.php similarity index 95% rename from src/Algorithms/0153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.php rename to src/Algorithms/s0153_find_minimum_in_rotated_sorted_array/Solution.php index c0c9a73..9af26a7 100644 --- a/src/Algorithms/0153.find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.php +++ b/src/Algorithms/s0153_find_minimum_in_rotated_sorted_array/Solution.php @@ -1,14 +1,14 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function findMin($nums) { - for($i=1;$i=$nums[$l]) $l=$m; - else $r=$m; - } - return $nums[$r]; - } +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function findMin($nums) { + $r=count($nums)-1; + $l=0; + if($r<0) return -1; + $first=$nums[0]; + if($first==$nums[$r]){//move util the start is not equal to the end any more; + while($l<$r && $nums[$l]==$first) $l++; + while($l<$r && $nums[$r]==$first) $r--; + } + if($nums[$l]<=$nums[$r]){ //deal with the ascending condition. + return $nums[$l]<$first?$nums[$l]:$first; + } + while($l<$r-1){//now we are bold to handle it as there must be a steep and the minimum is the right one. + $m=intval($l+($r-$l)/2); + if($nums[$m]>=$nums[$l]) $l=$m; + else $r=$m; + } + return $nums[$r]; + } } diff --git a/src/Algorithms/s0154_find_minimum_in_rotated_sorted_array_ii/readme.md b/src/Algorithms/s0154_find_minimum_in_rotated_sorted_array_ii/readme.md new file mode 100644 index 0000000..a5b2746 --- /dev/null +++ b/src/Algorithms/s0154_find_minimum_in_rotated_sorted_array_ii/readme.md @@ -0,0 +1,35 @@ +154\. Find Minimum in Rotated Sorted Array II + +Hard + +Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become: + +* `[4,5,6,7,0,1,4]` if it was rotated `4` times. +* `[0,1,4,4,5,6,7]` if it was rotated `7` times. + +Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. + +Given the sorted rotated array `nums` that may contain **duplicates**, return _the minimum element of this array_. + +You must decrease the overall operation steps as much as possible. + +**Example 1:** + +**Input:** nums = [1,3,5] + +**Output:** 1 + +**Example 2:** + +**Input:** nums = [2,2,2,0,1] + +**Output:** 0 + +**Constraints:** + +* `n == nums.length` +* `1 <= n <= 5000` +* `-5000 <= nums[i] <= 5000` +* `nums` is sorted and rotated between `1` and `n` times. + +**Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why? \ No newline at end of file diff --git a/src/Algorithms/0162.find-peak-element/find-peak-element.php b/src/Algorithms/s0162_find_peak_element/Solution.php similarity index 96% rename from src/Algorithms/0162.find-peak-element/find-peak-element.php rename to src/Algorithms/s0162_find_peak_element/Solution.php index 158fa85..62a9dbf 100644 --- a/src/Algorithms/0162.find-peak-element/find-peak-element.php +++ b/src/Algorithms/s0162_find_peak_element/Solution.php @@ -1,20 +1,20 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function findPeakElement($nums) { - if($nums==null||count($nums)<=1)return 0; - - if(count($nums)>=2){ - if($nums[count($nums)-1]>$nums[count($nums)-2])return count($nums)-1; - } - - for($i=1;$i$nums[$i-1]&&$nums[$i]>$nums[$i+1])return $i; - } - - return 0; - } +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function findPeakElement($nums) { + if($nums==null||count($nums)<=1)return 0; + + if(count($nums)>=2){ + if($nums[count($nums)-1]>$nums[count($nums)-2])return count($nums)-1; + } + + for($i=1;$i$nums[$i-1]&&$nums[$i]>$nums[$i+1])return $i; + } + + return 0; + } } diff --git a/src/Algorithms/s0162_find_peak_element/readme.md b/src/Algorithms/s0162_find_peak_element/readme.md new file mode 100644 index 0000000..06b6684 --- /dev/null +++ b/src/Algorithms/s0162_find_peak_element/readme.md @@ -0,0 +1,33 @@ +162\. Find Peak Element + +Medium + +A peak element is an element that is strictly greater than its neighbors. + +Given an integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**. + +You may imagine that `nums[-1] = nums[n] = -∞`. + +You must write an algorithm that runs in `O(log n)` time. + +**Example 1:** + +**Input:** nums = [1,2,3,1] + +**Output:** 2 + +**Explanation:** 3 is a peak element and your function should return the index number 2. + +**Example 2:** + +**Input:** nums = [1,2,1,3,5,6,4] + +**Output:** 5 + +**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. + +**Constraints:** + +* `1 <= nums.length <= 1000` +* -231 <= nums[i] <= 231 - 1 +* `nums[i] != nums[i + 1]` for all valid `i`. \ No newline at end of file diff --git a/src/Algorithms/0164.maximum-gap/maximum-gap.php b/src/Algorithms/s0164_maximum_gap/Solution.php similarity index 96% rename from src/Algorithms/0164.maximum-gap/maximum-gap.php rename to src/Algorithms/s0164_maximum_gap/Solution.php index 3cd991a..5a7bb82 100644 --- a/src/Algorithms/0164.maximum-gap/maximum-gap.php +++ b/src/Algorithms/s0164_maximum_gap/Solution.php @@ -1,67 +1,67 @@ -class Bucket { - var $leftClose; - var $rightOpen; - var $usedFlag; - - function __construct() { - $this->leftClose = 0; - $this->rightOpen = 0; - $this->usedFlag = false; - } -} - -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function maximumGap($nums) { - if ($nums==null || count($nums)<2) { - return 0; - } - - // find the maximum value and the minimum value in array - $max = $nums[0]; - $min = $nums[0]; - foreach ($nums as $num) { - $max = $max<$num ? $num : $max; - $min = $min>$num ? $num : $min; - } - - // the size of bucket must > 1 - $bucketSize = intval(max(1, ($max - $min) / (count($nums) - 1))); - $bucketNum = intval(($max-$min) / $bucketSize + 1); - - $buckets = array_fill(0, $bucketNum, null); - for ($i=0; $iusedFlag == false) { - $buckets[$bucketIndex]->leftClose = $num; - $buckets[$bucketIndex]->rightOpen = $num; - $buckets[$bucketIndex]->usedFlag = true; - } else { - $buckets[$bucketIndex]->leftClose = min($num, $buckets[$bucketIndex]->leftClose); - $buckets[$bucketIndex]->rightOpen = max($num, $buckets[$bucketIndex]->rightOpen); - } - } - - $maxGap = 0; - $preRightOpen = $buckets[0]->rightOpen; - for ($i=1; $iusedFlag == false) { - continue; - } - $maxGap = max($maxGap, $buckets[$i]->leftClose-$preRightOpen); - $preRightOpen = $buckets[$i]->rightOpen; - } - - return $maxGap; - } +class Bucket { + var $leftClose; + var $rightOpen; + var $usedFlag; + + function __construct() { + $this->leftClose = 0; + $this->rightOpen = 0; + $this->usedFlag = false; + } +} + +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function maximumGap($nums) { + if ($nums==null || count($nums)<2) { + return 0; + } + + // find the maximum value and the minimum value in array + $max = $nums[0]; + $min = $nums[0]; + foreach ($nums as $num) { + $max = $max<$num ? $num : $max; + $min = $min>$num ? $num : $min; + } + + // the size of bucket must > 1 + $bucketSize = intval(max(1, ($max - $min) / (count($nums) - 1))); + $bucketNum = intval(($max-$min) / $bucketSize + 1); + + $buckets = array_fill(0, $bucketNum, null); + for ($i=0; $iusedFlag == false) { + $buckets[$bucketIndex]->leftClose = $num; + $buckets[$bucketIndex]->rightOpen = $num; + $buckets[$bucketIndex]->usedFlag = true; + } else { + $buckets[$bucketIndex]->leftClose = min($num, $buckets[$bucketIndex]->leftClose); + $buckets[$bucketIndex]->rightOpen = max($num, $buckets[$bucketIndex]->rightOpen); + } + } + + $maxGap = 0; + $preRightOpen = $buckets[0]->rightOpen; + for ($i=1; $iusedFlag == false) { + continue; + } + $maxGap = max($maxGap, $buckets[$i]->leftClose-$preRightOpen); + $preRightOpen = $buckets[$i]->rightOpen; + } + + return $maxGap; + } } diff --git a/src/Algorithms/s0164_maximum_gap/readme.md b/src/Algorithms/s0164_maximum_gap/readme.md new file mode 100644 index 0000000..f10db05 --- /dev/null +++ b/src/Algorithms/s0164_maximum_gap/readme.md @@ -0,0 +1,28 @@ +164\. Maximum Gap + +Hard + +Given an integer array `nums`, return _the maximum difference between two successive elements in its sorted form_. If the array contains less than two elements, return `0`. + +You must write an algorithm that runs in linear time and uses linear extra space. + +**Example 1:** + +**Input:** nums = [3,6,9,1] + +**Output:** 3 + +**Explanation:** The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. + +**Example 2:** + +**Input:** nums = [10] + +**Output:** 0 + +**Explanation:** The array contains less than 2 elements, therefore return 0. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 0 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/Algorithms/0165.compare-version-numbers/compare-version-numbers.php b/src/Algorithms/s0165_compare_version_numbers/Solution.php similarity index 96% rename from src/Algorithms/0165.compare-version-numbers/compare-version-numbers.php rename to src/Algorithms/s0165_compare_version_numbers/Solution.php index 5e2b389..5937ef3 100644 --- a/src/Algorithms/0165.compare-version-numbers/compare-version-numbers.php +++ b/src/Algorithms/s0165_compare_version_numbers/Solution.php @@ -1,24 +1,24 @@ -class Solution { - - /** - * @param String $version1 - * @param String $version2 - * @return Integer - */ - function compareVersion($v1, $v2) { - $i1 = 0; $i2 = 0; $n1 = 0; $n2 = 0; - while ($i1 < strlen($v1) || $i2 < strlen($v2)) { - while ($i1 < strlen($v1) && $v1[$i1] != '.') { - $n1 = $n1 * 10 + ord($v1[$i1++]) - ord('0'); - } - while ($i2 < strlen($v2) && $v2[$i2] != '.') { - $n2 = $n2 * 10 + ord($v2[$i2++]) - ord('0'); - } - if ($n1 > $n2) return 1; - if ($n1 < $n2) return -1; - $n1 = $n2 = 0; - $i1++; $i2++; - } - return 0; - } +class Solution { + + /** + * @param String $version1 + * @param String $version2 + * @return Integer + */ + function compareVersion($v1, $v2) { + $i1 = 0; $i2 = 0; $n1 = 0; $n2 = 0; + while ($i1 < strlen($v1) || $i2 < strlen($v2)) { + while ($i1 < strlen($v1) && $v1[$i1] != '.') { + $n1 = $n1 * 10 + ord($v1[$i1++]) - ord('0'); + } + while ($i2 < strlen($v2) && $v2[$i2] != '.') { + $n2 = $n2 * 10 + ord($v2[$i2++]) - ord('0'); + } + if ($n1 > $n2) return 1; + if ($n1 < $n2) return -1; + $n1 = $n2 = 0; + $i1++; $i2++; + } + return 0; + } } diff --git a/src/Algorithms/s0165_compare_version_numbers/readme.md b/src/Algorithms/s0165_compare_version_numbers/readme.md new file mode 100644 index 0000000..2953d2d --- /dev/null +++ b/src/Algorithms/s0165_compare_version_numbers/readme.md @@ -0,0 +1,58 @@ +165\. Compare Version Numbers + +Medium + +Given two version numbers, `version1` and `version2`, compare them. + +Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers. + +To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`. + +_Return the following:_ + +* If `version1 < version2`, return `-1`. +* If `version1 > version2`, return `1`. +* Otherwise, return `0`. + +**Example 1:** + +**Input:** version1 = "1.01", version2 = "1.001" + +**Output:** 0 + +**Explanation:** Ignoring leading zeroes, both "01" and "001" represent the same integer "1". + +**Example 2:** + +**Input:** version1 = "1.0", version2 = "1.0.0" + +**Output:** 0 + +**Explanation:** version1 does not specify revision 2, which means it is treated as "0". + +**Example 3:** + +**Input:** version1 = "0.1", version2 = "1.1" + +**Output:** -1 + +**Explanation:** version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. + +**Example 4:** + +**Input:** version1 = "1.0.1", version2 = "1" + +**Output:** 1 + +**Example 5:** + +**Input:** version1 = "7.5.2.4", version2 = "7.5.3" + +**Output:** -1 + +**Constraints:** + +* `1 <= version1.length, version2.length <= 500` +* `version1` and `version2` only contain digits and `'.'`. +* `version1` and `version2` **are valid version numbers**. +* All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**. \ No newline at end of file diff --git a/src/Algorithms/0166.fraction-to-recurring-decimal/fraction-to-recurring-decimal.php b/src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php similarity index 96% rename from src/Algorithms/0166.fraction-to-recurring-decimal/fraction-to-recurring-decimal.php rename to src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php index 91f39d6..77427f6 100644 --- a/src/Algorithms/0166.fraction-to-recurring-decimal/fraction-to-recurring-decimal.php +++ b/src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php @@ -1,58 +1,58 @@ -class Solution { - - /** - * @param Integer $numerator - * @param Integer $denominator - * @return String - */ - function fractionToDecimal($num1, $deno1) { - $neg = $num1 > 0 && $deno1 < 0 || $num1 < 0 && $deno1 > 0; - $ret = $neg ? "-":""; - $num = abs($num1); - $deno = abs($deno1); - - - $p1 = intval($num/$deno); - $remain = $num%$deno; - if($remain == 0) return $ret . $p1; - - $map = []; - $sb = ""; - - $start = -1; - $end = -1; - $map[$remain] = 0; - echo($sb); - while($remain != 0) { - $remain *= 10; - while($remain < $deno) { - $sb .= '0'; - $map[$remain] = strlen($sb); - $remain *= 10; - } - - $res = intval($remain/$deno); - $sb = $sb . chr($res + ord('0')); - - $remain %= $deno; - if($remain == 0) break; - - $len = strlen($sb); - if(array_key_exists($remain, $map)) { - $start = $map[$remain]; - break; - } else { - $map[$remain] = $len; - } - } - - $ret = $ret . $p1 . "."; - if($start == -1) { - $ret .= $sb; - } else { - $ret = $ret . substr($sb, 0, $start) . "(" . substr($sb, $start) . ")"; - } - - return $ret; - } -} +class Solution { + + /** + * @param Integer $numerator + * @param Integer $denominator + * @return String + */ + function fractionToDecimal($num1, $deno1) { + $neg = $num1 > 0 && $deno1 < 0 || $num1 < 0 && $deno1 > 0; + $ret = $neg ? "-":""; + $num = abs($num1); + $deno = abs($deno1); + + + $p1 = intval($num/$deno); + $remain = $num%$deno; + if($remain == 0) return $ret . $p1; + + $map = []; + $sb = ""; + + $start = -1; + $end = -1; + $map[$remain] = 0; + echo($sb); + while($remain != 0) { + $remain *= 10; + while($remain < $deno) { + $sb .= '0'; + $map[$remain] = strlen($sb); + $remain *= 10; + } + + $res = intval($remain/$deno); + $sb = $sb . chr($res + ord('0')); + + $remain %= $deno; + if($remain == 0) break; + + $len = strlen($sb); + if(array_key_exists($remain, $map)) { + $start = $map[$remain]; + break; + } else { + $map[$remain] = $len; + } + } + + $ret = $ret . $p1 . "."; + if($start == -1) { + $ret .= $sb; + } else { + $ret = $ret . substr($sb, 0, $start) . "(" . substr($sb, $start) . ")"; + } + + return $ret; + } +} diff --git a/src/Algorithms/s0166_fraction_to_recurring_decimal/readme.md b/src/Algorithms/s0166_fraction_to_recurring_decimal/readme.md new file mode 100644 index 0000000..c749c48 --- /dev/null +++ b/src/Algorithms/s0166_fraction_to_recurring_decimal/readme.md @@ -0,0 +1,46 @@ +166\. Fraction to Recurring Decimal + +Medium + +Given two integers representing the `numerator` and `denominator` of a fraction, return _the fraction in string format_. + +If the fractional part is repeating, enclose the repeating part in parentheses. + +If multiple answers are possible, return **any of them**. + +It is **guaranteed** that the length of the answer string is less than 104 for all the given inputs. + +**Example 1:** + +**Input:** numerator = 1, denominator = 2 + +**Output:** "0.5" + +**Example 2:** + +**Input:** numerator = 2, denominator = 1 + +**Output:** "2" + +**Example 3:** + +**Input:** numerator = 2, denominator = 3 + +**Output:** "0.(6)" + +**Example 4:** + +**Input:** numerator = 4, denominator = 333 + +**Output:** "0.(012)" + +**Example 5:** + +**Input:** numerator = 1, denominator = 5 + +**Output:** "0.2" + +**Constraints:** + +* -231 <= numerator, denominator <= 231 - 1 +* `denominator != 0` \ No newline at end of file diff --git a/src/Algorithms/0167.two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.php b/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php similarity index 96% rename from src/Algorithms/0167.two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.php rename to src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php index b2b60b6..5828702 100644 --- a/src/Algorithms/0167.two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.php +++ b/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php @@ -1,21 +1,21 @@ -class Solution { - - /** - * @param Integer[] $numbers - * @param Integer $target - * @return Integer[] - */ - function twoSum($numbers, $target) { - $res=array_fill(0, 2, 0); - for ($i=0,$j=count($numbers)-1;$i<$j;){ - $sum = $numbers[$i]+$numbers[$j]; - if ($sum==$target){ - $res[0]=$i+1; $res[1]=$j+1; - return $res; - } - else if ($sum<$target)$i++; - else $j--; - } - return $res; - } -} +class Solution { + + /** + * @param Integer[] $numbers + * @param Integer $target + * @return Integer[] + */ + function twoSum($numbers, $target) { + $res=array_fill(0, 2, 0); + for ($i=0,$j=count($numbers)-1;$i<$j;){ + $sum = $numbers[$i]+$numbers[$j]; + if ($sum==$target){ + $res[0]=$i+1; $res[1]=$j+1; + return $res; + } + else if ($sum<$target)$i++; + else $j--; + } + return $res; + } +} diff --git a/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/readme.md b/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/readme.md new file mode 100644 index 0000000..81d951f --- /dev/null +++ b/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/readme.md @@ -0,0 +1,41 @@ +167\. Two Sum II - Input Array Is Sorted + +Easy + +Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. + +Return _the indices of the two numbers,_ index1 _and_ index2_, **added by one** as an integer array_ [index1, index2] _of length 2._ + +The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. + +**Example 1:** + +**Input:** numbers = [2,7,11,15], target = 9 + +**Output:** [1,2] + +**Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. + +**Example 2:** + +**Input:** numbers = [2,3,4], target = 6 + +**Output:** [1,3] + +**Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. + +**Example 3:** + +**Input:** numbers = [\-1,0], target = -1 + +**Output:** [1,2] + +**Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. + +**Constraints:** + +* 2 <= numbers.length <= 3 * 104 +* `-1000 <= numbers[i] <= 1000` +* `numbers` is sorted in **non-decreasing order**. +* `-1000 <= target <= 1000` +* The tests are generated such that there is **exactly one solution**. \ No newline at end of file diff --git a/src/Algorithms/0168.excel-sheet-column-title/excel-sheet-column-title.php b/src/Algorithms/s0168_excel_sheet_column_title/Solution.php similarity index 96% rename from src/Algorithms/0168.excel-sheet-column-title/excel-sheet-column-title.php rename to src/Algorithms/s0168_excel_sheet_column_title/Solution.php index 5e1e3ef..6cc274b 100644 --- a/src/Algorithms/0168.excel-sheet-column-title/excel-sheet-column-title.php +++ b/src/Algorithms/s0168_excel_sheet_column_title/Solution.php @@ -1,16 +1,16 @@ -class Solution { - - /** - * @param Integer $n - * @return String - */ - function convertToTitle($n) { - $mapping = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; - $sb = ""; - while($n > 0) { - $sb .= $mapping [--$n % 26]; //Since for a base 26 the numbers would be from 0 to 25. Deducting 1 - $n = intval($n / 26); - } - return strrev($sb); - } +class Solution { + + /** + * @param Integer $n + * @return String + */ + function convertToTitle($n) { + $mapping = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; + $sb = ""; + while($n > 0) { + $sb .= $mapping [--$n % 26]; //Since for a base 26 the numbers would be from 0 to 25. Deducting 1 + $n = intval($n / 26); + } + return strrev($sb); + } } diff --git a/src/Algorithms/s0168_excel_sheet_column_title/readme.md b/src/Algorithms/s0168_excel_sheet_column_title/readme.md new file mode 100644 index 0000000..51f246a --- /dev/null +++ b/src/Algorithms/s0168_excel_sheet_column_title/readme.md @@ -0,0 +1,44 @@ +168\. Excel Sheet Column Title + +Easy + +Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. + +For example: + + A -> 1 + B -> 2 + C -> 3 + ... + Z -> 26 + AA -> 27 + AB -> 28 + ... + +**Example 1:** + +**Input:** columnNumber = 1 + +**Output:** "A" + +**Example 2:** + +**Input:** columnNumber = 28 + +**Output:** "AB" + +**Example 3:** + +**Input:** columnNumber = 701 + +**Output:** "ZY" + +**Example 4:** + +**Input:** columnNumber = 2147483647 + +**Output:** "FXSHRXW" + +**Constraints:** + +* 1 <= columnNumber <= 231 - 1 \ No newline at end of file diff --git a/src/Algorithms/0169.majority-element/majority-element.php b/src/Algorithms/s0169_majority_element/Solution.php similarity index 95% rename from src/Algorithms/0169.majority-element/majority-element.php rename to src/Algorithms/s0169_majority_element/Solution.php index 314fffb..3ea48be 100644 --- a/src/Algorithms/0169.majority-element/majority-element.php +++ b/src/Algorithms/s0169_majority_element/Solution.php @@ -1,11 +1,11 @@ -class Solution { - - /** - * @param Integer[] $nums - * @return Integer - */ - function majorityElement($nums) { - sort($nums); - return $nums[intval(count($nums)/2)]; - } +class Solution { + + /** + * @param Integer[] $nums + * @return Integer + */ + function majorityElement($nums) { + sort($nums); + return $nums[intval(count($nums)/2)]; + } } diff --git a/src/Algorithms/s0169_majority_element/readme.md b/src/Algorithms/s0169_majority_element/readme.md new file mode 100644 index 0000000..5ea5071 --- /dev/null +++ b/src/Algorithms/s0169_majority_element/readme.md @@ -0,0 +1,27 @@ +169\. Majority Element + +Easy + +Given an array `nums` of size `n`, return _the majority element_. + +The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. + +**Example 1:** + +**Input:** nums = [3,2,3] + +**Output:** 3 + +**Example 2:** + +**Input:** nums = [2,2,1,1,1,2,2] + +**Output:** 2 + +**Constraints:** + +* `n == nums.length` +* 1 <= n <= 5 * 104 +* -231 <= nums[i] <= 231 - 1 + +**Follow-up:** Could you solve the problem in linear time and in `O(1)` space? \ No newline at end of file diff --git a/src/Algorithms/0171.excel-sheet-column-number/excel-sheet-column-number.php b/src/Algorithms/s0171_excel_sheet_column_number/Solution.php similarity index 95% rename from src/Algorithms/0171.excel-sheet-column-number/excel-sheet-column-number.php rename to src/Algorithms/s0171_excel_sheet_column_number/Solution.php index 30d6256..dba97dc 100644 --- a/src/Algorithms/0171.excel-sheet-column-number/excel-sheet-column-number.php +++ b/src/Algorithms/s0171_excel_sheet_column_number/Solution.php @@ -1,19 +1,19 @@ -class Solution { - - /** - * @param String $s - * @return Integer - */ - function titleToNumber($s) { - $len=strlen($s); - $jinzhi=1; - $sum=0; - for($i=$len-1;$i>=0;$i--) - { - - $sum=$sum+(ord($s[$i])-64)*$jinzhi; - $jinzhi=$jinzhi*26; - } - return $sum; - } +class Solution { + + /** + * @param String $s + * @return Integer + */ + function titleToNumber($s) { + $len=strlen($s); + $jinzhi=1; + $sum=0; + for($i=$len-1;$i>=0;$i--) + { + + $sum=$sum+(ord($s[$i])-64)*$jinzhi; + $jinzhi=$jinzhi*26; + } + return $sum; + } } diff --git a/src/Algorithms/s0171_excel_sheet_column_number/readme.md b/src/Algorithms/s0171_excel_sheet_column_number/readme.md new file mode 100644 index 0000000..86714d6 --- /dev/null +++ b/src/Algorithms/s0171_excel_sheet_column_number/readme.md @@ -0,0 +1,46 @@ +171\. Excel Sheet Column Number + +Easy + +Given a string `columnTitle` that represents the column title as appear in an Excel sheet, return _its corresponding column number_. + +For example: + + A -> 1 + B -> 2 + C -> 3 + ... + Z -> 26 + AA -> 27 + AB -> 28 + ... + +**Example 1:** + +**Input:** columnTitle = "A" + +**Output:** 1 + +**Example 2:** + +**Input:** columnTitle = "AB" + +**Output:** 28 + +**Example 3:** + +**Input:** columnTitle = "ZY" + +**Output:** 701 + +**Example 4:** + +**Input:** columnTitle = "FXSHRXW" + +**Output:** 2147483647 + +**Constraints:** + +* `1 <= columnTitle.length <= 7` +* `columnTitle` consists only of uppercase English letters. +* `columnTitle` is in the range `["A", "FXSHRXW"]`. \ No newline at end of file diff --git a/src/Algorithms/0172.factorial-trailing-zeroes/factorial-trailing-zeroes.php b/src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php similarity index 94% rename from src/Algorithms/0172.factorial-trailing-zeroes/factorial-trailing-zeroes.php rename to src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php index 85dd380..a760e87 100644 --- a/src/Algorithms/0172.factorial-trailing-zeroes/factorial-trailing-zeroes.php +++ b/src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php @@ -1,15 +1,15 @@ -class Solution { - - /** - * @param Integer $n - * @return Integer - */ - function trailingZeroes($n) { - $res = 0; - while($n >= 5){ - $n = intval($n / 5); - $res += $n; - } - return $res; - } +class Solution { + + /** + * @param Integer $n + * @return Integer + */ + function trailingZeroes($n) { + $res = 0; + while($n >= 5){ + $n = intval($n / 5); + $res += $n; + } + return $res; + } } diff --git a/src/Algorithms/s0172_factorial_trailing_zeroes/readme.md b/src/Algorithms/s0172_factorial_trailing_zeroes/readme.md new file mode 100644 index 0000000..17dc991 --- /dev/null +++ b/src/Algorithms/s0172_factorial_trailing_zeroes/readme.md @@ -0,0 +1,35 @@ +172\. Factorial Trailing Zeroes + +Medium + +Given an integer `n`, return _the number of trailing zeroes in_ `n!`. + +Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`. + +**Example 1:** + +**Input:** n = 3 + +**Output:** 0 + +**Explanation:** 3! = 6, no trailing zero. + +**Example 2:** + +**Input:** n = 5 + +**Output:** 1 + +**Explanation:** 5! = 120, one trailing zero. + +**Example 3:** + +**Input:** n = 0 + +**Output:** 0 + +**Constraints:** + +* 0 <= n <= 104 + +**Follow up:** Could you write a solution that works in logarithmic time complexity? \ No newline at end of file diff --git a/src/Algorithms/0174.dungeon-game/dungeon-game.php b/src/Algorithms/s0174_dungeon_game/Solution.php similarity index 96% rename from src/Algorithms/0174.dungeon-game/dungeon-game.php rename to src/Algorithms/s0174_dungeon_game/Solution.php index 47cb5fc..41a495c 100644 --- a/src/Algorithms/0174.dungeon-game/dungeon-game.php +++ b/src/Algorithms/s0174_dungeon_game/Solution.php @@ -1,33 +1,33 @@ -class Solution { - - private $dp; - private $visited; - - /** - * @param Integer[][] $dungeon - * @return Integer - */ - function calculateMinimumHP(&$dungeon) { - $dp = array_fill(0, count($dungeon), array_fill(0, count($dungeon[0]), 0)); - $visited = array_fill(0, count($dungeon), array_fill(0, count($dungeon[0]), false)); - $val = self::solve($dungeon, 0, 0); - return $val >= 1 ? 1 : 1-$val; - } - - function solve(&$dungeon, $i, $j) { - if($i == count($dungeon)-1 && $j == count($dungeon[0])-1) return $dungeon[$i][$j]; - if($i == count($dungeon)) return -2147483647; - if($j == count($dungeon[0])) return -2147483647; - - if($visited[$i][$j]) { - return $dp[$i][$j]; - } - - $val = min($dungeon[$i][$j] + max(self::solve($dungeon, $i+1, $j), self::solve($dungeon, $i, $j+1)), $dungeon[$i][$j]); - - $dp[$i][$j] = $val; - $visited[$i][$j] = true; - - return $val; - } -} +class Solution { + + private $dp; + private $visited; + + /** + * @param Integer[][] $dungeon + * @return Integer + */ + function calculateMinimumHP(&$dungeon) { + $dp = array_fill(0, count($dungeon), array_fill(0, count($dungeon[0]), 0)); + $visited = array_fill(0, count($dungeon), array_fill(0, count($dungeon[0]), false)); + $val = self::solve($dungeon, 0, 0); + return $val >= 1 ? 1 : 1-$val; + } + + function solve(&$dungeon, $i, $j) { + if($i == count($dungeon)-1 && $j == count($dungeon[0])-1) return $dungeon[$i][$j]; + if($i == count($dungeon)) return -2147483647; + if($j == count($dungeon[0])) return -2147483647; + + if($visited[$i][$j]) { + return $dp[$i][$j]; + } + + $val = min($dungeon[$i][$j] + max(self::solve($dungeon, $i+1, $j), self::solve($dungeon, $i, $j+1)), $dungeon[$i][$j]); + + $dp[$i][$j] = $val; + $visited[$i][$j] = true; + + return $val; + } +} diff --git a/src/Algorithms/s0174_dungeon_game/readme.md b/src/Algorithms/s0174_dungeon_game/readme.md new file mode 100644 index 0000000..502030f --- /dev/null +++ b/src/Algorithms/s0174_dungeon_game/readme.md @@ -0,0 +1,38 @@ +174\. Dungeon Game + +Hard + +The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess. + +The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately. + +Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). + +To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step. + +Return _the knight's minimum initial health so that he can rescue the princess_. + +**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg) + +**Input:** dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] + +**Output:** 7 + +**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. + +**Example 2:** + +**Input:** dungeon = [[0]] + +**Output:** 1 + +**Constraints:** + +* `m == dungeon.length` +* `n == dungeon[i].length` +* `1 <= m, n <= 200` +* `-1000 <= dungeon[i][j] <= 1000` \ No newline at end of file diff --git a/src/Algorithms/0179.largest-number/largest-number.php b/src/Algorithms/s0179_largest_number/Solution.php similarity index 95% rename from src/Algorithms/0179.largest-number/largest-number.php rename to src/Algorithms/s0179_largest_number/Solution.php index 3d03175..13efc70 100644 --- a/src/Algorithms/0179.largest-number/largest-number.php +++ b/src/Algorithms/s0179_largest_number/Solution.php @@ -1,32 +1,32 @@ -class Solution { - - function cmp($str1, $str2) { - $s1 = $str1 . $str2; - $s2 = $str2 . $str1; - return strcmp($s2, $s1); - } - - /** - * @param Integer[] $nums - * @return String - */ - function largestNumber($nums) { - $strs = array_fill(0, count($nums), ""); - for ($i=0; $i0 <= nums[i] <= 109 \ No newline at end of file diff --git a/src/Algorithms/0771.jewels-and-stones/jewels-and-stones.php b/src/Algorithms/s0771_jewels_and_stones/Solution.php similarity index 100% rename from src/Algorithms/0771.jewels-and-stones/jewels-and-stones.php rename to src/Algorithms/s0771_jewels_and_stones/Solution.php diff --git a/src/Algorithms/s0771_jewels_and_stones/readme.md b/src/Algorithms/s0771_jewels_and_stones/readme.md new file mode 100644 index 0000000..62930fa --- /dev/null +++ b/src/Algorithms/s0771_jewels_and_stones/readme.md @@ -0,0 +1,25 @@ +771\. Jewels and Stones + +Easy + +You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. + +Letters are case sensitive, so `"a"` is considered a different type of stone from `"A"`. + +**Example 1:** + +**Input:** jewels = "aA", stones = "aAAbbbb" + +**Output:** 3 + +**Example 2:** + +**Input:** jewels = "z", stones = "ZZ" + +**Output:** 0 + +**Constraints:** + +* `1 <= jewels.length, stones.length <= 50` +* `jewels` and `stones` consist of only English letters. +* All the characters of `jewels` are **unique**. \ No newline at end of file diff --git a/src/Algorithms/0864.shortest-path-to-get-all-keys/shortest-path-to-get-all-keys.php b/src/Algorithms/s0864_shortest_path_to_get_all_keys/Solution.php similarity index 100% rename from src/Algorithms/0864.shortest-path-to-get-all-keys/shortest-path-to-get-all-keys.php rename to src/Algorithms/s0864_shortest_path_to_get_all_keys/Solution.php diff --git a/src/Algorithms/s0864_shortest_path_to_get_all_keys/readme.md b/src/Algorithms/s0864_shortest_path_to_get_all_keys/readme.md new file mode 100644 index 0000000..d2bbc22 --- /dev/null +++ b/src/Algorithms/s0864_shortest_path_to_get_all_keys/readme.md @@ -0,0 +1,55 @@ +864\. Shortest Path to Get All Keys + +Hard + +You are given an `m x n` grid `grid` where: + +* `'.'` is an empty cell. +* `'#'` is a wall. +* `'@'` is the starting point. +* Lowercase letters represent keys. +* Uppercase letters represent locks. + +You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. + +If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. + +For some `1 <= k <= 6`, there is exactly one lowercase and one uppercase letter of the first `k` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. + +Return _the lowest number of moves to acquire all keys_. If it is impossible, return `-1`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg) + +**Input:** grid = ["@.a.#","###.#","b.A.B"] + +**Output:** 8 + +**Explanation:** Note that the goal is to obtain all the keys not to open all the locks. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg) + +**Input:** grid = ["@..aA","..B#.","....b"] + +**Output:** 6 + +**Example 3:** + +![](https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg) + +**Input:** grid = ["@Aa"] + +**Output:** -1 + +**Constraints:** + +* `m == grid.length` +* `n == grid[i].length` +* `1 <= m, n <= 30` +* `grid[i][j]` is either an English letter, `'.'`, `'#'`, or `'@'`. +* The number of keys in the grid is in the range `[1, 6]`. +* Each key in the grid is **unique**. +* Each key in the grid has a matching lock. \ No newline at end of file diff --git a/src/Algorithms/0973.k-closest-points-to-origin/k-closest-points-to-origin.php b/src/Algorithms/s0973_k_closest_points_to_origin/Solution.php similarity index 96% rename from src/Algorithms/0973.k-closest-points-to-origin/k-closest-points-to-origin.php rename to src/Algorithms/s0973_k_closest_points_to_origin/Solution.php index 17338cf..695fc82 100644 --- a/src/Algorithms/0973.k-closest-points-to-origin/k-closest-points-to-origin.php +++ b/src/Algorithms/s0973_k_closest_points_to_origin/Solution.php @@ -1,61 +1,61 @@ -class Solution { - - /** - * @param Integer[][] $points - * @param Integer $K - * @return Integer[][] - */ - function kClosest($points, $K) { - if ($points == null || count($points) == 0 || $K == 0) { - throw new Exception("Input should not be empty"); - } - self::quickSelect($points, $K, 0, count($points) - 1); - return array_slice($points, 0, $K); - } - - function quickSelect(&$points, $K, $low, $high) { - $partition = self::partition($points, $low, $high); - if ($partition == $K || $partition == $K - 1) { - // If the location is K after partition, the points before it can be used; - // If the location is K-1, the points before it plus itself can be used. - return; - } else if ($partition < $K - 1) { - self::quickSelect($points, $K,$partition + 1, $high); - } - else { - self::quickSelect($points, $K, $low, $partition - 1); - } - } - - /** - * The low is smaller - * @param points - * @param low - * @param high - * @@return The index that points are closer before it, and points are further after it. - */ - function partition(&$points, $low, $high) { - $pivotPoint = $points[$high]; - $partitionIndex = $low; - - for ($i = $low; $i < $high; $i++) { - if (self::compare($points[$i], $pivotPoint) <= 0) { - self::swap($points, $i, $partitionIndex); - $partitionIndex++; - } - } - self::swap($points, $partitionIndex, $high); - return $partitionIndex; - } - - function compare($point1, $point2) { - return $point1[0] * $point1[0] + $point1[1] * $point1[1] - - $point2[0] * $point2[0] - $point2[1] * $point2[1]; - } - - function swap(&$points, $location1, $location2) { - $tempPoint = $points[$location1]; - $points[$location1] = $points[$location2]; - $points[$location2] = $tempPoint; - } -} +class Solution { + + /** + * @param Integer[][] $points + * @param Integer $K + * @return Integer[][] + */ + function kClosest($points, $K) { + if ($points == null || count($points) == 0 || $K == 0) { + throw new Exception("Input should not be empty"); + } + self::quickSelect($points, $K, 0, count($points) - 1); + return array_slice($points, 0, $K); + } + + function quickSelect(&$points, $K, $low, $high) { + $partition = self::partition($points, $low, $high); + if ($partition == $K || $partition == $K - 1) { + // If the location is K after partition, the points before it can be used; + // If the location is K-1, the points before it plus itself can be used. + return; + } else if ($partition < $K - 1) { + self::quickSelect($points, $K,$partition + 1, $high); + } + else { + self::quickSelect($points, $K, $low, $partition - 1); + } + } + + /** + * The low is smaller + * @param points + * @param low + * @param high + * @@return The index that points are closer before it, and points are further after it. + */ + function partition(&$points, $low, $high) { + $pivotPoint = $points[$high]; + $partitionIndex = $low; + + for ($i = $low; $i < $high; $i++) { + if (self::compare($points[$i], $pivotPoint) <= 0) { + self::swap($points, $i, $partitionIndex); + $partitionIndex++; + } + } + self::swap($points, $partitionIndex, $high); + return $partitionIndex; + } + + function compare($point1, $point2) { + return $point1[0] * $point1[0] + $point1[1] * $point1[1] - + $point2[0] * $point2[0] - $point2[1] * $point2[1]; + } + + function swap(&$points, $location1, $location2) { + $tempPoint = $points[$location1]; + $points[$location1] = $points[$location2]; + $points[$location2] = $tempPoint; + } +} diff --git a/src/Algorithms/s0973_k_closest_points_to_origin/readme.md b/src/Algorithms/s0973_k_closest_points_to_origin/readme.md new file mode 100644 index 0000000..352242e --- /dev/null +++ b/src/Algorithms/s0973_k_closest_points_to_origin/readme.md @@ -0,0 +1,40 @@ +973\. K Closest Points to Origin + +Medium + +Given an array of `points` where points[i] = [xi, yi] represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. + +The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). + +You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg) + +**Input:** points = [[1,3],[-2,2]], k = 1 + +**Output:** [[-2,2]] + +**Explanation:** + +The distance between (1, 3) and the origin is sqrt(10). + +The distance between (-2, 2) and the origin is sqrt(8). + +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. + +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + +**Example 2:** + +**Input:** points = [[3,3],[5,-1],[-2,4]], k = 2 + +**Output:** [[3,3],[-2,4]] + +**Explanation:** The answer [[-2,4],[3,3]] would also be accepted. + +**Constraints:** + +* 1 <= k <= points.length <= 104 +* -104 < xi, yi < 104 \ No newline at end of file diff --git a/tests/CalculatorTest.php b/tests/CalculatorTest.php deleted file mode 100644 index 3c9a607..0000000 --- a/tests/CalculatorTest.php +++ /dev/null @@ -1,50 +0,0 @@ -calc = new Calculator(); - parent::__construct(); - } - public function testInstanceCalculator() - { - $this->assertInstanceOf(Calculator::class, $this->calc); - } - public function testAdd() - { - $value = $this->calc->add(2, 3); - $this->assertEquals($value, 5); - } - public function testMultiply() - { - $value = $this->calc->multiply(2, 3); - $this->assertEquals($value, 6); - } - public function testSubtract() - { - $value = $this->calc->subtract(4, 2); - $this->assertEquals($value, 2); - } - public function testNormalDivide() - { - $value = $this->calc->divide(4, 2); - $this->assertEquals($value, 2); - } - public function testDivisorCanNotBeZero() - { - $this->expectException(\InvalidArgumentException::class); - $this->calc->divide(4, 0); - } -} \ No newline at end of file From eec8e1ebb21f18914b5c43982f02f851fea6f146 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 04:00:23 +0200 Subject: [PATCH 02/12] Fixed build --- composer.json | 7 ++++++- tests/SolutionTest.php | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/SolutionTest.php diff --git a/composer.json b/composer.json index 03f47a4..54dfa9d 100644 --- a/composer.json +++ b/composer.json @@ -4,7 +4,12 @@ "license": "MIT", "autoload": { "psr-4": { - "Javadev\\LeetCodePhp\\": "" + "\\": "Algorithms/s0001_two_sum" + } + }, + "autoload-dev": { + "psr-4": { + "\\": "tests" } }, "authors": [ diff --git a/tests/SolutionTest.php b/tests/SolutionTest.php new file mode 100644 index 0000000..9219f0a --- /dev/null +++ b/tests/SolutionTest.php @@ -0,0 +1,21 @@ +assertEquals([0, 1], (new Solution())->twoSum([2, 7, 11, 15], 9)); + } + + public function testTwoSum2() { + $this->assertEquals([1, 2], (new Solution())->twoSum([3, 2, 4], 6)); + } + + public function testTwoSum3() { + $this->assertEquals([0, 1], (new Solution())->twoSum([3, 3], 6)); + } + + public function testTwoSum4() { + $this->assertEquals([-1, -1], (new Solution())->twoSum([3, 3], 7)); + } +} From fad3cf1512d8369e72a8035c4386c54fd9751829 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 04:02:47 +0200 Subject: [PATCH 03/12] Fixed build --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 54dfa9d..43531e9 100644 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "license": "MIT", "autoload": { "psr-4": { - "\\": "Algorithms/s0001_two_sum" + "\\": "Algorithms/s0001_two_sum/" } }, "autoload-dev": { From 1261649bab723014d4ff63a672e851698b5ba5c6 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 04:04:10 +0200 Subject: [PATCH 04/12] Fixed test --- src/Algorithms/s0001_two_sum/Solution.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Algorithms/s0001_two_sum/Solution.php b/src/Algorithms/s0001_two_sum/Solution.php index f368863..dd94166 100644 --- a/src/Algorithms/s0001_two_sum/Solution.php +++ b/src/Algorithms/s0001_two_sum/Solution.php @@ -1,3 +1,5 @@ + Date: Fri, 22 Dec 2023 04:06:39 +0200 Subject: [PATCH 05/12] Fixed phpunit --- phpunit.xml.dist | 2 +- src/Algorithms/s0001_two_sum/Solution.php | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 904590f..049fa27 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -17,7 +17,7 @@ - ./src + ./src/Algorithms/s0001_two_sum \ No newline at end of file diff --git a/src/Algorithms/s0001_two_sum/Solution.php b/src/Algorithms/s0001_two_sum/Solution.php index dd94166..f368863 100644 --- a/src/Algorithms/s0001_two_sum/Solution.php +++ b/src/Algorithms/s0001_two_sum/Solution.php @@ -1,5 +1,3 @@ - Date: Fri, 22 Dec 2023 04:09:12 +0200 Subject: [PATCH 06/12] Fixed task --- src/Algorithms/s0001_two_sum/Solution.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Algorithms/s0001_two_sum/Solution.php b/src/Algorithms/s0001_two_sum/Solution.php index f368863..dd94166 100644 --- a/src/Algorithms/s0001_two_sum/Solution.php +++ b/src/Algorithms/s0001_two_sum/Solution.php @@ -1,3 +1,5 @@ + Date: Fri, 22 Dec 2023 04:10:45 +0200 Subject: [PATCH 07/12] Fixed build --- composer.json | 2 +- src/Algorithms/s0001_two_sum/Solution.php | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 43531e9..d1bb89d 100644 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "license": "MIT", "autoload": { "psr-4": { - "\\": "Algorithms/s0001_two_sum/" + "\\": "src/Algorithms/s0001_two_sum/" } }, "autoload-dev": { diff --git a/src/Algorithms/s0001_two_sum/Solution.php b/src/Algorithms/s0001_two_sum/Solution.php index dd94166..f368863 100644 --- a/src/Algorithms/s0001_two_sum/Solution.php +++ b/src/Algorithms/s0001_two_sum/Solution.php @@ -1,5 +1,3 @@ - Date: Fri, 22 Dec 2023 04:12:39 +0200 Subject: [PATCH 08/12] Fixed build --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d1bb89d..08299fa 100644 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "license": "MIT", "autoload": { "psr-4": { - "\\": "src/Algorithms/s0001_two_sum/" + "\\": "src/Algorithms/s0001_two_sum" } }, "autoload-dev": { From a5d0796c7ffaf6025846d519b6519a504e25795a Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 04:14:26 +0200 Subject: [PATCH 09/12] Fixed test --- tests/Solution.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tests/Solution.php diff --git a/tests/Solution.php b/tests/Solution.php new file mode 100644 index 0000000..dd94166 --- /dev/null +++ b/tests/Solution.php @@ -0,0 +1,23 @@ + Date: Fri, 22 Dec 2023 04:15:56 +0200 Subject: [PATCH 10/12] Fixed test --- tests/Solution.php | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/tests/Solution.php b/tests/Solution.php index dd94166..97d8585 100644 --- a/tests/Solution.php +++ b/tests/Solution.php @@ -7,17 +7,15 @@ class Solution { * @param Integer $target * @return Integer[] */ - function twoSum($nums, $target) { - $map = []; - for ($i = 0; $i < count($nums); $i++) { - $map[$nums[$i]] = $i; - } - for ($i = 0; $i < count($nums); $i++) { + public function twoSum($nums, $target) { + $ind = []; + for ($i = 0; $i < count($nums); ++$i) { $complement = $target - $nums[$i]; - if (array_key_exists($complement, $map) && $map[$complement] != $i) { - return [$i, $map[$complement] ]; + if (array_key_exists($complement, $ind)) { + return [$ind[$complement], $i]; } + $ind[$nums[$i]] = $i; } - throw new IllegalArgumentException("No two sum solution"); + return [-1, -1]; } } From 76498c442af006b554848c97e83f96d0dfd49127 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 04:20:09 +0200 Subject: [PATCH 11/12] Fixed build --- phpunit.xml.dist | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 049fa27..8e8e3d5 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -9,6 +9,14 @@ convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"> + + + ./tests + + + + + ./tests @@ -17,7 +25,7 @@ - ./src/Algorithms/s0001_two_sum + ./tests \ No newline at end of file From 38d1aca1deba44d0da7c613335bf98b0b08b3e09 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Fri, 22 Dec 2023 04:24:05 +0200 Subject: [PATCH 12/12] Fixed build --- .github/workflows/php.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 05bfc09..93adbc4 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -12,14 +12,14 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Validate composer.json and composer.lock run: composer validate --strict - name: Cache Composer packages id: composer-cache - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: vendor key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} @@ -31,6 +31,3 @@ jobs: - name: Run test suite run: vendor/bin/phpunit - - name: phpunit-coverage-badge - uses: timkrase/phpunit-coverage-badge@v1.2.0 -